title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How can SciPy be used to calculate the eigen values and eigen vectors of a matrix in Python?
Eigen vectors and Eigen values find their uses in many situations. The word ‘Eigen’ in German means ‘own’ or ‘typical’. An Eigen vector is also known as a ‘characteristic vector’. Suppose we need to perform some transformation on a dataset but the given condition is that the direction of data in the dataset shouldn’t change. This is when Eigen vectors and Eigen values can be used. Given a square matrix (a matrix where the number of rows is equal to the number of columns), an Eigen value and an Eigen vector fulfil the below equation. Eigen vectors are computed after finding the Eigen values. Note − Eigen values work well with dimensions 3 or greater as well. Instead of manually perfroming these mathematical computations, SciPy provides a function in the library called ‘eig’ which helps compute the Eigenvalue and the Eigenvector. Syntax of ‘eig’ function scipy.linalg.eig(matrix) Let us see how the ‘eig’ function can be used − Live Demo from scipy import linalg import numpy as np my_arr = np.array([[5,7],[11,3]]) eg_val, eg_vect = linalg.eig(my_arr) print("The Eigenvalues are :") print(eg_val) print("The Eigenvectors are :") print(eg_vect) The Eigenvalues are : [12.83176087+0.j -4.83176087+0.j] The Eigenvectors are : [[ 0.66640536 -0.57999285] [ 0.74558963 0.81462157]] The required libraries are imported. A matrix is defined with certain values in it, using the Numpy library. The matrix is passed as a parameter to the ‘eig’ function that computes the eigenvalues and the eigenvectors of the matrix. These computed data is stored in two different variables. This output is displayed on the console.
[ { "code": null, "e": 1446, "s": 1062, "text": "Eigen vectors and Eigen values find their uses in many situations. The word ‘Eigen’ in German means ‘own’ or ‘typical’. An Eigen vector is also known as a ‘characteristic vector’. Suppose we need to perform some transformation on a dataset but the given condition is that the direction of data in the dataset shouldn’t change. This is when Eigen vectors and Eigen values can be used." }, { "code": null, "e": 1601, "s": 1446, "text": "Given a square matrix (a matrix where the number of rows is equal to the number of columns), an Eigen value and an Eigen vector fulfil the below equation." }, { "code": null, "e": 1660, "s": 1601, "text": "Eigen vectors are computed after finding the Eigen values." }, { "code": null, "e": 1728, "s": 1660, "text": "Note − Eigen values work well with dimensions 3 or greater as well." }, { "code": null, "e": 1902, "s": 1728, "text": "Instead of manually perfroming these mathematical computations, SciPy provides a function in the library called ‘eig’ which helps compute the Eigenvalue and the Eigenvector." }, { "code": null, "e": 1927, "s": 1902, "text": "Syntax of ‘eig’ function" }, { "code": null, "e": 1952, "s": 1927, "text": "scipy.linalg.eig(matrix)" }, { "code": null, "e": 2000, "s": 1952, "text": "Let us see how the ‘eig’ function can be used −" }, { "code": null, "e": 2011, "s": 2000, "text": " Live Demo" }, { "code": null, "e": 2218, "s": 2011, "text": "from scipy import linalg\nimport numpy as np\nmy_arr = np.array([[5,7],[11,3]])\neg_val, eg_vect = linalg.eig(my_arr)\nprint(\"The Eigenvalues are :\")\nprint(eg_val)\nprint(\"The Eigenvectors are :\")\nprint(eg_vect)" }, { "code": null, "e": 2350, "s": 2218, "text": "The Eigenvalues are :\n[12.83176087+0.j -4.83176087+0.j]\nThe Eigenvectors are :\n[[ 0.66640536 -0.57999285]\n[ 0.74558963 0.81462157]]" }, { "code": null, "e": 2387, "s": 2350, "text": "The required libraries are imported." }, { "code": null, "e": 2459, "s": 2387, "text": "A matrix is defined with certain values in it, using the Numpy library." }, { "code": null, "e": 2583, "s": 2459, "text": "The matrix is passed as a parameter to the ‘eig’ function that computes the eigenvalues and the eigenvectors of the matrix." }, { "code": null, "e": 2641, "s": 2583, "text": "These computed data is stored in two different variables." }, { "code": null, "e": 2682, "s": 2641, "text": "This output is displayed on the console." } ]
CSS Background Shorthand
To shorten the code, it is also possible to specify all the background properties in one single property. This is called a shorthand property. Instead of writing: You can use the shorthand property background: Use the shorthand property to set the background properties in one declaration: When using the shorthand property the order of the property values is: background-color background-image background-repeat background-attachment background-position It does not matter if one of the property values is missing, as long as the other ones are in this order. Note that we do not use the background-attachment property in the examples above, as it does not have a value. Set the background color of the <h1> element to "lightblue". <style> h1 { : lightblue; } </style> <body> <h1>This is a heading</h1> <p>This is a paragraph</p> <p>This is a paragraph</p> </body> Start the Exercise 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": 144, "s": 0, "text": "To shorten the code, it is also possible to specify all the background properties in one \nsingle property. This is called a shorthand property." }, { "code": null, "e": 164, "s": 144, "text": "Instead of writing:" }, { "code": null, "e": 211, "s": 164, "text": "You can use the shorthand property background:" }, { "code": null, "e": 294, "s": 211, "text": "Use the shorthand property to set the background properties in one \n declaration:" }, { "code": null, "e": 366, "s": 294, "text": "\nWhen using the shorthand property the order of the property values is:" }, { "code": null, "e": 383, "s": 366, "text": "background-color" }, { "code": null, "e": 400, "s": 383, "text": "background-image" }, { "code": null, "e": 418, "s": 400, "text": "background-repeat" }, { "code": null, "e": 440, "s": 418, "text": "background-attachment" }, { "code": null, "e": 460, "s": 440, "text": "background-position" }, { "code": null, "e": 678, "s": 460, "text": "It does not matter if one of the property values is missing, as long as the \nother ones are in this order. Note that we do not use the background-attachment property in the examples above, as it does not have a value." }, { "code": null, "e": 739, "s": 678, "text": "Set the background color of the <h1> element to \"lightblue\"." }, { "code": null, "e": 882, "s": 739, "text": "<style>\nh1 {\n : lightblue;\n}\n</style>\n\n<body>\n <h1>This is a heading</h1>\n <p>This is a paragraph</p>\n <p>This is a paragraph</p>\n</body>\n" }, { "code": null, "e": 901, "s": 882, "text": "Start the Exercise" }, { "code": null, "e": 934, "s": 901, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 976, "s": 934, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1083, "s": 976, "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": 1102, "s": 1083, "text": "help@w3schools.com" } ]
Auto Tagging Stack Overflow Questions | by Susan Li | Towards Data Science
One of the most interesting applications of NLP is automatically infer and tag the topic of a question. In this post, we’ll start from exploratory analysis of Stack Overflow questions and answers, and then we will build a simple model to predict the tag of a Stack Overflow question. We’ll solve this text classification problem using Scikit-Learn. Let’s get started. For this project, we’ll use text from 10% of Stack Overflow questions and answers on programming topics, and it is freely available on Kaggle. Because ggplot is one of our favourite data visualization tools. So, we will do EDA in R. Load the necessary pacakges library(readr)library(dplyr)library(ggplot2)library(lubridate)library(tidytext)library(tidyverse)library(broom)library(purrr)library(scales)theme_set(theme_bw()) The questions data and tags data are stored separately, so we will read them separately. questions <- read_csv("Questions.csv")question_tags <- read_csv("Tags.csv") Tags Data So, what are the most popular tags? question_tags %>% count(Tag, sort = TRUE) Questions Data The number of questions asked per week: questions <- questions[ -c(8:29)]questions %>% count(Week = round_date(CreationDate, "week")) %>% ggplot(aes(Week, n)) + geom_line() + ggtitle('The Number of Questions Asked Per Week') Compare the growth or shrinking of particular tags over time: tags <- c("c#", "javascript", "python", "r", "php")q_per_year <- questions %>% count(Year = year(CreationDate)) %>% rename(YearTotal = n)tags_per_year <- question_tags %>% filter(Tag %in% tags) %>% inner_join(questions) %>% count(Year = year(CreationDate), Tag) %>% inner_join(q_per_year)ggplot(tags_per_year, aes(Year, n / YearTotal, color = Tag)) + geom_line() + scale_y_continuous(labels = scales::percent_format()) + ylab("% of Stack Overflow questions with this tag") + ggtitle('Growth or Shrinking of Particular Tags Overtime') What are the most common words in the titles? title_word_counts <- title_words %>% anti_join(stop_words, c(Word = "word")) %>% count(Word, sort = TRUE)title_word_counts %>% head(20) %>% mutate(Word = reorder(Word, n)) %>% ggplot(aes(Word, n)) + geom_col(fill = "cyan4", alpha = 0.8, width = 0.6) + ylab("Number of appearances in question titles") + ggtitle('The most common words in the question titles') + coord_flip() Finding tf-idf within tags category We’d expect the tag category to differ in terms of titles content, and therefore for the frequency of words to differ between them. We will use tf-idf to find the title words that most associated with particular tags. common_tags <- question_tags %>% group_by(Tag) %>% mutate(TagTotal = n()) %>% ungroup() %>% filter(TagTotal >= 100)tag_word_tfidf <- common_tags %>% inner_join(title_words, by = "Id") %>% count(Tag, Word, TagTotal, sort = TRUE) %>% ungroup() %>% bind_tf_idf(Word, Tag, n)tag_word_tfidf %>% filter(TagTotal > 1000) %>% arrange(desc(tf_idf)) %>% head(10) We will examine the top tf-idf for all tag categories to extract words specific to those tags. tag_word_tfidf %>% filter(Tag %in% c("c#", "python", "java", "php", "javascript", "android")) %>% group_by(Tag) %>% top_n(12, tf_idf) %>% ungroup() %>% mutate(Word = reorder(Word, tf_idf)) %>% ggplot(aes(Word, tf_idf, fill = Tag)) + geom_col(show.legend = FALSE, width = 0.6) + facet_wrap(~ Tag, scales = "free") + ylab("tf-idf") + coord_flip() + ggtitle('The 12 terms with the highest tf-idf within each of the top tag categories') Change over time What words and terms have become more frequent, or less frequent, over time? These could give us a sense of the changing software ecosystem, and let us predict what words will continue to grow in relevance. To achieve that, we need to get the slope of each word. questions$month<-month(questions$CreationDate)questions$year <- year(questions$CreationDate)titles_per_month <- questions %>% group_by(month) %>% summarize(month_total = n())title_words <- questions %>% arrange(desc(Score)) %>% distinct(Title, .keep_all = TRUE) %>% unnest_tokens(word, Title, drop = FALSE) %>% distinct(Id, word, .keep_all = TRUE) %>% anti_join(stop_words, by = "word") %>% filter(str_detect(word, "[^\\d]")) %>% group_by(word) %>% mutate(word_total = n()) %>% ungroup()word_month_counts <- title_words %>% filter(word_total >= 1000) %>% count(word, month, year) %>% complete(word, month, year, fill = list(n = 0)) %>% inner_join(titles_per_month, by = "month") %>% mutate(percent = n / month_total)mod <- ~ glm(cbind(n, month_total - n) ~ year, ., family = "binomial")slopes <- word_month_counts %>% nest(-word) %>% mutate(model = map(data, mod)) %>% unnest(map(model, tidy)) %>% filter(term == "year") %>% arrange(desc(estimate))slopes Then plot the top 16 fastest growing words: slopes %>% head(16) %>% inner_join(word_month_counts, by = "word") %>% mutate(word = reorder(word, -estimate)) %>% ggplot(aes(year, n / month_total, color = word)) + geom_point(show.legend = FALSE) + geom_smooth(show.legend = FALSE) + scale_y_continuous(labels = percent_format()) + facet_wrap(~ word, scales = "free_y") + expand_limits(y = 0) + labs(x = "Year", y = "Percentage of titles containing this term", title = "16 fastest growing words in Stack Overflow question titles") And top 16 fastest shrinking words: slopes %>% tail(16) %>% inner_join(word_month_counts, by = "word") %>% mutate(word = reorder(word, -estimate)) %>% ggplot(aes(year, n / month_total, color = word)) + geom_point(show.legend = FALSE) + geom_smooth(show.legend = FALSE) + scale_y_continuous(labels = percent_format()) + facet_wrap(~ word, scales = "free_y") + expand_limits(y = 0) + labs(x = "Year", y = "Percentage of titles containing this term", title = "16 fastest shrinking words in Stack Overflow question titles") N-gram Analysis N-grams are used to develop not just unigram models but also bigram and trigram models. A bigram is an n-gram for n=2. The following are the most common bigram in the question titles. title_bigrams <- questions %>% unnest_tokens(bigram, Title, token = "ngrams", n = 2)title_bigrams %>% count(bigram, sort = TRUE) I am sure you find them meaningless. Let’s find the most common meaningful bigrams. bigrams_separated <- title_bigrams %>% separate(bigram, c("word1", "word2"), sep = " ")bigrams_filtered <- bigrams_separated %>% filter(!word1 %in% stop_words$word) %>% filter(!word2 %in% stop_words$word)bigram_counts <- bigrams_filtered %>% count(word1, word2, sort = TRUE)bigrams_united <- bigrams_filtered %>% unite(bigram, word1, word2, sep = " ")bigrams_united %>% count(bigram, sort = TRUE) And most common trigrams: questions %>% unnest_tokens(trigram, Title, token = "ngrams", n = 3) %>% separate(trigram, c("word1", "word2", "word3"), sep = " ") %>% filter(!word1 %in% stop_words$word, !word2 %in% stop_words$word, !word3 %in% stop_words$word) %>% count(word1, word2, word3, sort = TRUE) That was fun! Now we are going to develop a predictive model to automatically tag Stack Overflow questions. We will do that in Python. write.csv(total, file = "/Users/sli/Documents/total.csv", row.names = FALSE) Here are the first five rows of the combined question and tag table: import pandas as pdtotal = pd.read_csv('total.csv', encoding='latin-1')total.head() Below is the full text of the first question: total['Body'][0] The raw text data is messy and needs to be cleaned up for any further analysis. We exclude HTML tags, links and code snippets from the data. from collections import Counterimport numpy as np import stringimport redef clean_text(text): global EMPTY EMPTY = '' if not isinstance(text, str): return text text = re.sub('<pre><code>.*?</code></pre>', EMPTY, text)def replace_link(match): return EMPTY if re.match('[a-z]+://', match.group(1)) else match.group(1) text = re.sub('<a[^>]+>(.*)</a>', replace_link, text) return re.sub('<[^>]+>', EMPTY, text) Then we create a new “Text” column for cleaned text from “Body” column. total['Text'] = total['Body'].apply(clean_text).str.lower()total.Text = total.Text.apply(lambda x: x.replace('"','').replace("\n","").replace("\t","")) There are more than 20,000 unique tags in our data. total['Tag'].nunique() 21981 To simplify the problem, we will only work on the top 10 most frequently used tags, as show below: def plot_tags(tagCount): x,y = zip(*tagCount) colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired colors = [colormap(i) for i in np.linspace(0, 0.8,50)] area = [i/4000 for i in list(y)] # 0 to 15 point radiuses plt.figure(figsize=(10,6)) plt.ylabel("Number of question associations") for i in range(len(y)): plt.plot(i,y[i],marker='o',linestyle='',ms=area[i],label=x[i]) plt.legend(numpoints=1) plt.show()import collectionsimport matplotlib.pyplot as plttagCount = collections.Counter(list(total['Tag'])).most_common(10)print(tagCount)plot_tags(tagCount) total = total[(total.Tag == 'c#') | (total.Tag == 'java') | (total.Tag == 'php') | (total.Tag =='javascript') | (total.Tag =='jquery') | (total.Tag == 'android') | (total.Tag == 'c++') | (total.Tag == 'iphone') | (total.Tag == 'python') | (total.Tag == 'asp.net')] We will scikit-learn’s bag-of-words approach to classify text by tags. So, we are only interested in two columns — “Text” and “Tag”. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(total['Text'], total['Tag'], random_state=42, test_size=0.2, shuffle=True) We are going to try various classifiers that can efficiently handle our text data that have been transformed to sparse matrices. The bar plot indicates the accuracy, training time (normalized) and test time (normalized) of each classifier. from __future__ import print_functionfrom time import timeimport matplotlib.pyplot as pltfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.feature_extraction.text import HashingVectorizerfrom sklearn.feature_selection import SelectFromModelfrom sklearn.feature_selection import SelectKBest, chi2from sklearn.linear_model import RidgeClassifierfrom sklearn.pipeline import Pipelinefrom sklearn.svm import LinearSVCfrom sklearn.linear_model import SGDClassifierfrom sklearn.linear_model import Perceptronfrom sklearn.linear_model import PassiveAggressiveClassifierfrom sklearn.naive_bayes import BernoulliNB, MultinomialNBfrom sklearn.neighbors import NearestCentroidfrom sklearn.utils.extmath import densityfrom sklearn import metricstarget_names=total['Tag'].unique()def benchmark(clf): print('_' * 80) print("Training: ") print(clf) t0 = time() clf.fit(X_train_1, y_train) train_time = time() - t0 print("train time: %0.3fs" % train_time)t0 = time() pred = clf.predict(X_test_1) test_time = time() - t0 print("test time: %0.3fs" % test_time)score = metrics.accuracy_score(y_test, pred) print("accuracy: %0.3f" % score)if hasattr(clf, 'coef_'): print("dimensionality: %d" % clf.coef_.shape[1]) print("density: %f" % density(clf.coef_))if opts.print_top10 and feature_names is not None: print("top 10 keywords per class:") for i, label in enumerate(target_names): top10 = np.argsort(clf.coef_[i])[-10:] print(trim("%s: %s" % (label, " ".join(feature_names[top10])))) print()if opts.print_report: print("classification report:") print(metrics.classification_report(y_test, pred, target_names=target_names))if opts.print_cm: print("confusion matrix:") print(metrics.confusion_matrix(y_test, pred))print() clf_descr = str(clf).split('(')[0] return clf_descr, score, train_time, test_timeresults = []for clf, name in ( (RidgeClassifier(tol=1e-2, solver="lsqr"), "Ridge Classifier"), (Perceptron(n_iter=50), "Perceptron"), (PassiveAggressiveClassifier(n_iter=50), "Passive-Aggressive")): print('=' * 80) print(name) results.append(benchmark(clf)) print('=' * 80)print("Elastic-Net penalty")results.append(benchmark(SGDClassifier(alpha=.0001, n_iter=50, penalty="elasticnet")))print('=' * 80)print("NearestCentroid (aka Rocchio classifier)")results.append(benchmark(NearestCentroid()))print('=' * 80)print("Naive Bayes")results.append(benchmark(MultinomialNB(alpha=.01)))results.append(benchmark(BernoulliNB(alpha=.01)))print('=' * 80)print("LinearSVC with L1-based feature selection")results.append(benchmark(Pipeline([ ('feature_selection', SelectFromModel(LinearSVC(penalty="l1", dual=False, tol=1e-3))), ('classification', LinearSVC(penalty="l2"))])))indices = np.arange(len(results))results = [[x[i] for x in results] for i in range(4)]clf_names, score, training_time, test_time = resultstraining_time = np.array(training_time) / np.max(training_time)test_time = np.array(test_time) / np.max(test_time)plt.figure(figsize=(12, 8))plt.title("Score")plt.barh(indices, score, .2, label="score", color='navy')plt.barh(indices + .3, training_time, .2, label="training time", color='c')plt.barh(indices + .6, test_time, .2, label="test time", color='darkorange')plt.yticks(())plt.legend(loc='best')plt.subplots_adjust(left=.25)plt.subplots_adjust(top=.95)plt.subplots_adjust(bottom=.05)for i, c in zip(indices, clf_names): plt.text(-.3, i, c)plt.show() Classifier using Ridge regression achieved the best results so far. Therefore, we print out the precision and recall for each tag. model = RidgeClassifier(tol=1e-2, solver="lsqr")model.fit(X_train_1, y_train)predicted = model.predict(X_test_1)from sklearn.metrics import classification_reportprint(classification_report(y_test, predicted, target_names=target_names)) We probably can achieve a better result by parameter tuning, but I leave it to you to do that. Source code can be found at Github. I look forward to hear any feedback or questions. References: Scikit-Learn Text Mining with R
[ { "code": null, "e": 540, "s": 172, "text": "One of the most interesting applications of NLP is automatically infer and tag the topic of a question. In this post, we’ll start from exploratory analysis of Stack Overflow questions and answers, and then we will build a simple model to predict the tag of a Stack Overflow question. We’ll solve this text classification problem using Scikit-Learn. Let’s get started." }, { "code": null, "e": 683, "s": 540, "text": "For this project, we’ll use text from 10% of Stack Overflow questions and answers on programming topics, and it is freely available on Kaggle." }, { "code": null, "e": 773, "s": 683, "text": "Because ggplot is one of our favourite data visualization tools. So, we will do EDA in R." }, { "code": null, "e": 801, "s": 773, "text": "Load the necessary pacakges" }, { "code": null, "e": 963, "s": 801, "text": "library(readr)library(dplyr)library(ggplot2)library(lubridate)library(tidytext)library(tidyverse)library(broom)library(purrr)library(scales)theme_set(theme_bw())" }, { "code": null, "e": 1052, "s": 963, "text": "The questions data and tags data are stored separately, so we will read them separately." }, { "code": null, "e": 1128, "s": 1052, "text": "questions <- read_csv(\"Questions.csv\")question_tags <- read_csv(\"Tags.csv\")" }, { "code": null, "e": 1138, "s": 1128, "text": "Tags Data" }, { "code": null, "e": 1174, "s": 1138, "text": "So, what are the most popular tags?" }, { "code": null, "e": 1217, "s": 1174, "text": "question_tags %>% count(Tag, sort = TRUE)" }, { "code": null, "e": 1232, "s": 1217, "text": "Questions Data" }, { "code": null, "e": 1272, "s": 1232, "text": "The number of questions asked per week:" }, { "code": null, "e": 1462, "s": 1272, "text": "questions <- questions[ -c(8:29)]questions %>% count(Week = round_date(CreationDate, \"week\")) %>% ggplot(aes(Week, n)) + geom_line() + ggtitle('The Number of Questions Asked Per Week')" }, { "code": null, "e": 1524, "s": 1462, "text": "Compare the growth or shrinking of particular tags over time:" }, { "code": null, "e": 2068, "s": 1524, "text": "tags <- c(\"c#\", \"javascript\", \"python\", \"r\", \"php\")q_per_year <- questions %>% count(Year = year(CreationDate)) %>% rename(YearTotal = n)tags_per_year <- question_tags %>% filter(Tag %in% tags) %>% inner_join(questions) %>% count(Year = year(CreationDate), Tag) %>% inner_join(q_per_year)ggplot(tags_per_year, aes(Year, n / YearTotal, color = Tag)) + geom_line() + scale_y_continuous(labels = scales::percent_format()) + ylab(\"% of Stack Overflow questions with this tag\") + ggtitle('Growth or Shrinking of Particular Tags Overtime')" }, { "code": null, "e": 2114, "s": 2068, "text": "What are the most common words in the titles?" }, { "code": null, "e": 2497, "s": 2114, "text": "title_word_counts <- title_words %>% anti_join(stop_words, c(Word = \"word\")) %>% count(Word, sort = TRUE)title_word_counts %>% head(20) %>% mutate(Word = reorder(Word, n)) %>% ggplot(aes(Word, n)) + geom_col(fill = \"cyan4\", alpha = 0.8, width = 0.6) + ylab(\"Number of appearances in question titles\") + ggtitle('The most common words in the question titles') + coord_flip()" }, { "code": null, "e": 2533, "s": 2497, "text": "Finding tf-idf within tags category" }, { "code": null, "e": 2751, "s": 2533, "text": "We’d expect the tag category to differ in terms of titles content, and therefore for the frequency of words to differ between them. We will use tf-idf to find the title words that most associated with particular tags." }, { "code": null, "e": 3137, "s": 2751, "text": "common_tags <- question_tags %>% group_by(Tag) %>% mutate(TagTotal = n()) %>% ungroup() %>% filter(TagTotal >= 100)tag_word_tfidf <- common_tags %>% inner_join(title_words, by = \"Id\") %>% count(Tag, Word, TagTotal, sort = TRUE) %>% ungroup() %>% bind_tf_idf(Word, Tag, n)tag_word_tfidf %>% filter(TagTotal > 1000) %>% arrange(desc(tf_idf)) %>% head(10)" }, { "code": null, "e": 3232, "s": 3137, "text": "We will examine the top tf-idf for all tag categories to extract words specific to those tags." }, { "code": null, "e": 3676, "s": 3232, "text": "tag_word_tfidf %>% filter(Tag %in% c(\"c#\", \"python\", \"java\", \"php\", \"javascript\", \"android\")) %>% group_by(Tag) %>% top_n(12, tf_idf) %>% ungroup() %>% mutate(Word = reorder(Word, tf_idf)) %>% ggplot(aes(Word, tf_idf, fill = Tag)) + geom_col(show.legend = FALSE, width = 0.6) + facet_wrap(~ Tag, scales = \"free\") + ylab(\"tf-idf\") + coord_flip() + ggtitle('The 12 terms with the highest tf-idf within each of the top tag categories')" }, { "code": null, "e": 3693, "s": 3676, "text": "Change over time" }, { "code": null, "e": 3956, "s": 3693, "text": "What words and terms have become more frequent, or less frequent, over time? These could give us a sense of the changing software ecosystem, and let us predict what words will continue to grow in relevance. To achieve that, we need to get the slope of each word." }, { "code": null, "e": 4932, "s": 3956, "text": "questions$month<-month(questions$CreationDate)questions$year <- year(questions$CreationDate)titles_per_month <- questions %>% group_by(month) %>% summarize(month_total = n())title_words <- questions %>% arrange(desc(Score)) %>% distinct(Title, .keep_all = TRUE) %>% unnest_tokens(word, Title, drop = FALSE) %>% distinct(Id, word, .keep_all = TRUE) %>% anti_join(stop_words, by = \"word\") %>% filter(str_detect(word, \"[^\\\\d]\")) %>% group_by(word) %>% mutate(word_total = n()) %>% ungroup()word_month_counts <- title_words %>% filter(word_total >= 1000) %>% count(word, month, year) %>% complete(word, month, year, fill = list(n = 0)) %>% inner_join(titles_per_month, by = \"month\") %>% mutate(percent = n / month_total)mod <- ~ glm(cbind(n, month_total - n) ~ year, ., family = \"binomial\")slopes <- word_month_counts %>% nest(-word) %>% mutate(model = map(data, mod)) %>% unnest(map(model, tidy)) %>% filter(term == \"year\") %>% arrange(desc(estimate))slopes" }, { "code": null, "e": 4976, "s": 4932, "text": "Then plot the top 16 fastest growing words:" }, { "code": null, "e": 5480, "s": 4976, "text": "slopes %>% head(16) %>% inner_join(word_month_counts, by = \"word\") %>% mutate(word = reorder(word, -estimate)) %>% ggplot(aes(year, n / month_total, color = word)) + geom_point(show.legend = FALSE) + geom_smooth(show.legend = FALSE) + scale_y_continuous(labels = percent_format()) + facet_wrap(~ word, scales = \"free_y\") + expand_limits(y = 0) + labs(x = \"Year\", y = \"Percentage of titles containing this term\", title = \"16 fastest growing words in Stack Overflow question titles\")" }, { "code": null, "e": 5516, "s": 5480, "text": "And top 16 fastest shrinking words:" }, { "code": null, "e": 6022, "s": 5516, "text": "slopes %>% tail(16) %>% inner_join(word_month_counts, by = \"word\") %>% mutate(word = reorder(word, -estimate)) %>% ggplot(aes(year, n / month_total, color = word)) + geom_point(show.legend = FALSE) + geom_smooth(show.legend = FALSE) + scale_y_continuous(labels = percent_format()) + facet_wrap(~ word, scales = \"free_y\") + expand_limits(y = 0) + labs(x = \"Year\", y = \"Percentage of titles containing this term\", title = \"16 fastest shrinking words in Stack Overflow question titles\")" }, { "code": null, "e": 6038, "s": 6022, "text": "N-gram Analysis" }, { "code": null, "e": 6222, "s": 6038, "text": "N-grams are used to develop not just unigram models but also bigram and trigram models. A bigram is an n-gram for n=2. The following are the most common bigram in the question titles." }, { "code": null, "e": 6353, "s": 6222, "text": "title_bigrams <- questions %>% unnest_tokens(bigram, Title, token = \"ngrams\", n = 2)title_bigrams %>% count(bigram, sort = TRUE)" }, { "code": null, "e": 6437, "s": 6353, "text": "I am sure you find them meaningless. Let’s find the most common meaningful bigrams." }, { "code": null, "e": 6841, "s": 6437, "text": "bigrams_separated <- title_bigrams %>% separate(bigram, c(\"word1\", \"word2\"), sep = \" \")bigrams_filtered <- bigrams_separated %>% filter(!word1 %in% stop_words$word) %>% filter(!word2 %in% stop_words$word)bigram_counts <- bigrams_filtered %>% count(word1, word2, sort = TRUE)bigrams_united <- bigrams_filtered %>% unite(bigram, word1, word2, sep = \" \")bigrams_united %>% count(bigram, sort = TRUE)" }, { "code": null, "e": 6867, "s": 6841, "text": "And most common trigrams:" }, { "code": null, "e": 7161, "s": 6867, "text": "questions %>% unnest_tokens(trigram, Title, token = \"ngrams\", n = 3) %>% separate(trigram, c(\"word1\", \"word2\", \"word3\"), sep = \" \") %>% filter(!word1 %in% stop_words$word, !word2 %in% stop_words$word, !word3 %in% stop_words$word) %>% count(word1, word2, word3, sort = TRUE)" }, { "code": null, "e": 7175, "s": 7161, "text": "That was fun!" }, { "code": null, "e": 7296, "s": 7175, "text": "Now we are going to develop a predictive model to automatically tag Stack Overflow questions. We will do that in Python." }, { "code": null, "e": 7373, "s": 7296, "text": "write.csv(total, file = \"/Users/sli/Documents/total.csv\", row.names = FALSE)" }, { "code": null, "e": 7442, "s": 7373, "text": "Here are the first five rows of the combined question and tag table:" }, { "code": null, "e": 7526, "s": 7442, "text": "import pandas as pdtotal = pd.read_csv('total.csv', encoding='latin-1')total.head()" }, { "code": null, "e": 7572, "s": 7526, "text": "Below is the full text of the first question:" }, { "code": null, "e": 7589, "s": 7572, "text": "total['Body'][0]" }, { "code": null, "e": 7730, "s": 7589, "text": "The raw text data is messy and needs to be cleaned up for any further analysis. We exclude HTML tags, links and code snippets from the data." }, { "code": null, "e": 8179, "s": 7730, "text": "from collections import Counterimport numpy as np import stringimport redef clean_text(text): global EMPTY EMPTY = '' if not isinstance(text, str): return text text = re.sub('<pre><code>.*?</code></pre>', EMPTY, text)def replace_link(match): return EMPTY if re.match('[a-z]+://', match.group(1)) else match.group(1) text = re.sub('<a[^>]+>(.*)</a>', replace_link, text) return re.sub('<[^>]+>', EMPTY, text)" }, { "code": null, "e": 8251, "s": 8179, "text": "Then we create a new “Text” column for cleaned text from “Body” column." }, { "code": null, "e": 8403, "s": 8251, "text": "total['Text'] = total['Body'].apply(clean_text).str.lower()total.Text = total.Text.apply(lambda x: x.replace('\"','').replace(\"\\n\",\"\").replace(\"\\t\",\"\"))" }, { "code": null, "e": 8455, "s": 8403, "text": "There are more than 20,000 unique tags in our data." }, { "code": null, "e": 8478, "s": 8455, "text": "total['Tag'].nunique()" }, { "code": null, "e": 8484, "s": 8478, "text": "21981" }, { "code": null, "e": 8583, "s": 8484, "text": "To simplify the problem, we will only work on the top 10 most frequently used tags, as show below:" }, { "code": null, "e": 9186, "s": 8583, "text": "def plot_tags(tagCount): x,y = zip(*tagCount) colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired colors = [colormap(i) for i in np.linspace(0, 0.8,50)] area = [i/4000 for i in list(y)] # 0 to 15 point radiuses plt.figure(figsize=(10,6)) plt.ylabel(\"Number of question associations\") for i in range(len(y)): plt.plot(i,y[i],marker='o',linestyle='',ms=area[i],label=x[i]) plt.legend(numpoints=1) plt.show()import collectionsimport matplotlib.pyplot as plttagCount = collections.Counter(list(total['Tag'])).most_common(10)print(tagCount)plot_tags(tagCount)" }, { "code": null, "e": 9451, "s": 9186, "text": "total = total[(total.Tag == 'c#') | (total.Tag == 'java') | (total.Tag == 'php') | (total.Tag =='javascript') | (total.Tag =='jquery') | (total.Tag == 'android') | (total.Tag == 'c++') | (total.Tag == 'iphone') | (total.Tag == 'python') | (total.Tag == 'asp.net')]" }, { "code": null, "e": 9584, "s": 9451, "text": "We will scikit-learn’s bag-of-words approach to classify text by tags. So, we are only interested in two columns — “Text” and “Tag”." }, { "code": null, "e": 9763, "s": 9584, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(total['Text'], total['Tag'], random_state=42, test_size=0.2, shuffle=True)" }, { "code": null, "e": 9892, "s": 9763, "text": "We are going to try various classifiers that can efficiently handle our text data that have been transformed to sparse matrices." }, { "code": null, "e": 10003, "s": 9892, "text": "The bar plot indicates the accuracy, training time (normalized) and test time (normalized) of each classifier." }, { "code": null, "e": 13688, "s": 10003, "text": "from __future__ import print_functionfrom time import timeimport matplotlib.pyplot as pltfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.feature_extraction.text import HashingVectorizerfrom sklearn.feature_selection import SelectFromModelfrom sklearn.feature_selection import SelectKBest, chi2from sklearn.linear_model import RidgeClassifierfrom sklearn.pipeline import Pipelinefrom sklearn.svm import LinearSVCfrom sklearn.linear_model import SGDClassifierfrom sklearn.linear_model import Perceptronfrom sklearn.linear_model import PassiveAggressiveClassifierfrom sklearn.naive_bayes import BernoulliNB, MultinomialNBfrom sklearn.neighbors import NearestCentroidfrom sklearn.utils.extmath import densityfrom sklearn import metricstarget_names=total['Tag'].unique()def benchmark(clf): print('_' * 80) print(\"Training: \") print(clf) t0 = time() clf.fit(X_train_1, y_train) train_time = time() - t0 print(\"train time: %0.3fs\" % train_time)t0 = time() pred = clf.predict(X_test_1) test_time = time() - t0 print(\"test time: %0.3fs\" % test_time)score = metrics.accuracy_score(y_test, pred) print(\"accuracy: %0.3f\" % score)if hasattr(clf, 'coef_'): print(\"dimensionality: %d\" % clf.coef_.shape[1]) print(\"density: %f\" % density(clf.coef_))if opts.print_top10 and feature_names is not None: print(\"top 10 keywords per class:\") for i, label in enumerate(target_names): top10 = np.argsort(clf.coef_[i])[-10:] print(trim(\"%s: %s\" % (label, \" \".join(feature_names[top10])))) print()if opts.print_report: print(\"classification report:\") print(metrics.classification_report(y_test, pred, target_names=target_names))if opts.print_cm: print(\"confusion matrix:\") print(metrics.confusion_matrix(y_test, pred))print() clf_descr = str(clf).split('(')[0] return clf_descr, score, train_time, test_timeresults = []for clf, name in ( (RidgeClassifier(tol=1e-2, solver=\"lsqr\"), \"Ridge Classifier\"), (Perceptron(n_iter=50), \"Perceptron\"), (PassiveAggressiveClassifier(n_iter=50), \"Passive-Aggressive\")): print('=' * 80) print(name) results.append(benchmark(clf)) print('=' * 80)print(\"Elastic-Net penalty\")results.append(benchmark(SGDClassifier(alpha=.0001, n_iter=50, penalty=\"elasticnet\")))print('=' * 80)print(\"NearestCentroid (aka Rocchio classifier)\")results.append(benchmark(NearestCentroid()))print('=' * 80)print(\"Naive Bayes\")results.append(benchmark(MultinomialNB(alpha=.01)))results.append(benchmark(BernoulliNB(alpha=.01)))print('=' * 80)print(\"LinearSVC with L1-based feature selection\")results.append(benchmark(Pipeline([ ('feature_selection', SelectFromModel(LinearSVC(penalty=\"l1\", dual=False, tol=1e-3))), ('classification', LinearSVC(penalty=\"l2\"))])))indices = np.arange(len(results))results = [[x[i] for x in results] for i in range(4)]clf_names, score, training_time, test_time = resultstraining_time = np.array(training_time) / np.max(training_time)test_time = np.array(test_time) / np.max(test_time)plt.figure(figsize=(12, 8))plt.title(\"Score\")plt.barh(indices, score, .2, label=\"score\", color='navy')plt.barh(indices + .3, training_time, .2, label=\"training time\", color='c')plt.barh(indices + .6, test_time, .2, label=\"test time\", color='darkorange')plt.yticks(())plt.legend(loc='best')plt.subplots_adjust(left=.25)plt.subplots_adjust(top=.95)plt.subplots_adjust(bottom=.05)for i, c in zip(indices, clf_names): plt.text(-.3, i, c)plt.show()" }, { "code": null, "e": 13819, "s": 13688, "text": "Classifier using Ridge regression achieved the best results so far. Therefore, we print out the precision and recall for each tag." }, { "code": null, "e": 14055, "s": 13819, "text": "model = RidgeClassifier(tol=1e-2, solver=\"lsqr\")model.fit(X_train_1, y_train)predicted = model.predict(X_test_1)from sklearn.metrics import classification_reportprint(classification_report(y_test, predicted, target_names=target_names))" }, { "code": null, "e": 14150, "s": 14055, "text": "We probably can achieve a better result by parameter tuning, but I leave it to you to do that." }, { "code": null, "e": 14236, "s": 14150, "text": "Source code can be found at Github. I look forward to hear any feedback or questions." }, { "code": null, "e": 14248, "s": 14236, "text": "References:" }, { "code": null, "e": 14261, "s": 14248, "text": "Scikit-Learn" } ]
C# | How to change the Input Encoding Scheme of the Console - GeeksforGeeks
28 Jan, 2019 Given the normal Console in C#, the task is to change the Input Encoding Scheme of the Console. Approach: This can be done using the InputEncoding property in the Console class of the System package in C#. Console.InputEncoding Property gets or sets the encoding the console uses to read input. Program 1: Getting the value of Input Encoding Scheme // C# program to illustrate the// Console.InputEncoding Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the Input Encoding Scheme Console.WriteLine("Current Input Encoding Scheme: {0}", Console.InputEncoding); }}} Output: Program 2: Setting the value of Input Encoding Scheme // C# program to illustrate the// Console.InputEncoding Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the Input Encoding Scheme Console.WriteLine("Current Input Encoding Scheme: {0}", Console.InputEncoding); // Set the Input Encoding Scheme to ASCII Console.InputEncoding = Encoding.ASCII; // Get the Input Encoding Scheme Console.WriteLine("Current Input Encoding Scheme: {0}", Console.InputEncoding); }}} Output: CSharp-Console-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# Partial Classes in C# Top 50 C# Interview Questions & Answers HashSet in C# with Examples Lambda Expressions in C# C# | Inheritance C# | .NET Framework (Basic Architecture and Component Stack) Hello World in C# Top 50 ASP.NET Interview Questions and Answers C# | List Class
[ { "code": null, "e": 23911, "s": 23883, "text": "\n28 Jan, 2019" }, { "code": null, "e": 24007, "s": 23911, "text": "Given the normal Console in C#, the task is to change the Input Encoding Scheme of the Console." }, { "code": null, "e": 24206, "s": 24007, "text": "Approach: This can be done using the InputEncoding property in the Console class of the System package in C#. Console.InputEncoding Property gets or sets the encoding the console uses to read input." }, { "code": null, "e": 24260, "s": 24206, "text": "Program 1: Getting the value of Input Encoding Scheme" }, { "code": "// C# program to illustrate the// Console.InputEncoding Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the Input Encoding Scheme Console.WriteLine(\"Current Input Encoding Scheme: {0}\", Console.InputEncoding); }}}", "e": 24686, "s": 24260, "text": null }, { "code": null, "e": 24694, "s": 24686, "text": "Output:" }, { "code": null, "e": 24748, "s": 24694, "text": "Program 2: Setting the value of Input Encoding Scheme" }, { "code": "// C# program to illustrate the// Console.InputEncoding Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the Input Encoding Scheme Console.WriteLine(\"Current Input Encoding Scheme: {0}\", Console.InputEncoding); // Set the Input Encoding Scheme to ASCII Console.InputEncoding = Encoding.ASCII; // Get the Input Encoding Scheme Console.WriteLine(\"Current Input Encoding Scheme: {0}\", Console.InputEncoding); }}}", "e": 25440, "s": 24748, "text": null }, { "code": null, "e": 25448, "s": 25440, "text": "Output:" }, { "code": null, "e": 25469, "s": 25448, "text": "CSharp-Console-Class" }, { "code": null, "e": 25472, "s": 25469, "text": "C#" }, { "code": null, "e": 25570, "s": 25472, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25579, "s": 25570, "text": "Comments" }, { "code": null, "e": 25592, "s": 25579, "text": "Old Comments" }, { "code": null, "e": 25615, "s": 25592, "text": "Extension Method in C#" }, { "code": null, "e": 25637, "s": 25615, "text": "Partial Classes in C#" }, { "code": null, "e": 25677, "s": 25637, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 25705, "s": 25677, "text": "HashSet in C# with Examples" }, { "code": null, "e": 25730, "s": 25705, "text": "Lambda Expressions in C#" }, { "code": null, "e": 25747, "s": 25730, "text": "C# | Inheritance" }, { "code": null, "e": 25808, "s": 25747, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 25826, "s": 25808, "text": "Hello World in C#" }, { "code": null, "e": 25873, "s": 25826, "text": "Top 50 ASP.NET Interview Questions and Answers" } ]
C Program for Recursive Bubble Sort
Bubble Sort is one of the simplest sorting algorithms used to sort data by comparing the adjacent elements. All the elements are compared in phases. The first phase places the largest value at the end, the second phase places the second largest element at the second last position and so on till the complete list is sorted. int arr[5]= { 5,4,2,1,3 }; int arr[5]= { 5,4,2,1,3 }; int i, j ; int i, j ; Traverse from index i=0 to i<array sizeTraverse from index j=0 to array size - i - 1If arr[i]>arr[j] swap arr[i] with arr[j] Traverse from index i=0 to i<array size Traverse from index j=0 to array size - i - 1 Traverse from index j=0 to array size - i - 1 If arr[i]>arr[j] swap arr[i] with arr[j] If arr[i]>arr[j] swap arr[i] with arr[j] End End If array length is 1 then return If array length is 1 then return Traverse array once and fix largest element at the end Traverse array once and fix largest element at the end Recursively perform step 2 for rest of the array except last element Recursively perform step 2 for rest of the array except last element Input − Arr[] = { 5,7,2,3,1,4 }; length=6 Output − Sorted array: 1 2 3 4 5 7 Explanation − First Pass 5 7 2 3 1 4 → swap → 5 2 7 3 1 4 5 2 7 3 1 4 → swap → 5 2 3 7 1 4 5 2 3 7 1 4 → swap → 5 2 3 1 7 4 5 2 3 1 7 4 → swap → 5 2 3 1 4 7 Second Pass 5 2 3 1 4 7 → swap → 2 5 3 1 4 7 2 5 3 1 4 7 → swap → 2 3 5 1 4 7 2 3 5 1 4 7 → swap → 2 3 1 5 4 7 2 3 1 5 4 7 → swap → 2 3 1 4 5 7 Third Pass 2 3 1 4 5 7 → swap → 2 1 3 4 5 7 2 1 3 4 5 7 no swap Fourth Pass 2 1 3 4 5 7 → swap → 1 2 3 4 5 7 1 2 3 4 5 7 no swap in further iterations Input − Arr[] = { 1, 2, 3, 3, 2 }; Output − Sorted array: 1 2 2 3 3 Explanation − First Pass 1 2 3 3 2 → swap → 1 2 3 2 3 1 2 3 2 3 → swap → 1 2 2 3 3 1 2 2 3 3 no swap in further iterations Second Pass 1 2 2 3 3 no swap in further iterations In the recursive approach of Bubble sort, the base case is array length = 1. Otherwise traverse the array using single for loop and swap elements accordingly. Take input array Arr[] and length as number of elements in it. Take input array Arr[] and length as number of elements in it. Function recurbublSort(int arr[], int len) takes the array and its length and sorts the array recursively using bubble sort. Function recurbublSort(int arr[], int len) takes the array and its length and sorts the array recursively using bubble sort. Take a variable temp. Take a variable temp. If array length is 1 then return void. If array length is 1 then return void. Else traverse the array using single for loop and for each element arr[i]>arr[i+1], swap those elements. Else traverse the array using single for loop and for each element arr[i]>arr[i+1], swap those elements. Set temp=arr[i], arr[i]=arr[i+1] and arr[i+1]=temp. Set temp=arr[i], arr[i]=arr[i+1] and arr[i+1]=temp. Now decrement length by 1 as the previous loop placed the largest element at the last position. Now decrement length by 1 as the previous loop placed the largest element at the last position. Do a recursive call to recurbublSort(arr,len). Do a recursive call to recurbublSort(arr,len). At the end of all calls, when len becomes 1 we will come out of recursion and the array will be sorted. At the end of all calls, when len becomes 1 we will come out of recursion and the array will be sorted. Print the sorted array inside main. Print the sorted array inside main. #include <stdio.h> void recurbublSort(int arr[], int len){ int temp; if (len == 1){ return; } for (int i=0; i<len-1; i++){ if (arr[i] > arr[i+1]){ temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } len=len-1; recurbublSort(arr, len); } int main(){ int Arr[] = {21, 34, 20, 31, 78, 43, 66}; int length = sizeof(Arr)/sizeof(Arr[0]); recurbublSort(Arr, length); printf("Sorted array : "); for(int i=0;i<length;i++){ printf("%d ",Arr[i]); } return 0; } If we run the above code it will generate the following Output Sorted array: 20 21 31 34 43 66 78
[ { "code": null, "e": 1387, "s": 1062, "text": "Bubble Sort is one of the simplest sorting algorithms used to sort data by comparing the adjacent elements. All the elements are compared in phases. The first phase places the largest value at the end, the second phase places the second largest element at the second last position and so on till the complete list is sorted." }, { "code": null, "e": 1414, "s": 1387, "text": "int arr[5]= { 5,4,2,1,3 };" }, { "code": null, "e": 1441, "s": 1414, "text": "int arr[5]= { 5,4,2,1,3 };" }, { "code": null, "e": 1452, "s": 1441, "text": "int i, j ;" }, { "code": null, "e": 1463, "s": 1452, "text": "int i, j ;" }, { "code": null, "e": 1588, "s": 1463, "text": "Traverse from index i=0 to i<array sizeTraverse from index j=0 to array size - i - 1If arr[i]>arr[j] swap arr[i] with arr[j]" }, { "code": null, "e": 1628, "s": 1588, "text": "Traverse from index i=0 to i<array size" }, { "code": null, "e": 1674, "s": 1628, "text": "Traverse from index j=0 to array size - i - 1" }, { "code": null, "e": 1720, "s": 1674, "text": "Traverse from index j=0 to array size - i - 1" }, { "code": null, "e": 1761, "s": 1720, "text": "If arr[i]>arr[j] swap arr[i] with arr[j]" }, { "code": null, "e": 1802, "s": 1761, "text": "If arr[i]>arr[j] swap arr[i] with arr[j]" }, { "code": null, "e": 1806, "s": 1802, "text": "End" }, { "code": null, "e": 1810, "s": 1806, "text": "End" }, { "code": null, "e": 1843, "s": 1810, "text": "If array length is 1 then return" }, { "code": null, "e": 1876, "s": 1843, "text": "If array length is 1 then return" }, { "code": null, "e": 1931, "s": 1876, "text": "Traverse array once and fix largest element at the end" }, { "code": null, "e": 1986, "s": 1931, "text": "Traverse array once and fix largest element at the end" }, { "code": null, "e": 2055, "s": 1986, "text": "Recursively perform step 2 for rest of the array except last element" }, { "code": null, "e": 2124, "s": 2055, "text": "Recursively perform step 2 for rest of the array except last element" }, { "code": null, "e": 2166, "s": 2124, "text": "Input − Arr[] = { 5,7,2,3,1,4 }; length=6" }, { "code": null, "e": 2201, "s": 2166, "text": "Output − Sorted array: 1 2 3 4 5 7" }, { "code": null, "e": 2215, "s": 2201, "text": "Explanation −" }, { "code": null, "e": 2653, "s": 2215, "text": "First Pass\n5 7 2 3 1 4 → swap → 5 2 7 3 1 4\n5 2 7 3 1 4 → swap → 5 2 3 7 1 4\n5 2 3 7 1 4 → swap → 5 2 3 1 7 4\n5 2 3 1 7 4 → swap → 5 2 3 1 4 7\nSecond Pass\n5 2 3 1 4 7 → swap → 2 5 3 1 4 7\n2 5 3 1 4 7 → swap → 2 3 5 1 4 7\n2 3 5 1 4 7 → swap → 2 3 1 5 4 7\n2 3 1 5 4 7 → swap → 2 3 1 4 5 7\nThird Pass\n2 3 1 4 5 7 → swap → 2 1 3 4 5 7\n2 1 3 4 5 7 no swap\nFourth Pass\n2 1 3 4 5 7 → swap → 1 2 3 4 5 7\n1 2 3 4 5 7 no swap in further iterations" }, { "code": null, "e": 2688, "s": 2653, "text": "Input − Arr[] = { 1, 2, 3, 3, 2 };" }, { "code": null, "e": 2721, "s": 2688, "text": "Output − Sorted array: 1 2 2 3 3" }, { "code": null, "e": 2735, "s": 2721, "text": "Explanation −" }, { "code": null, "e": 2896, "s": 2735, "text": "First Pass\n1 2 3 3 2 → swap → 1 2 3 2 3\n1 2 3 2 3 → swap → 1 2 2 3 3\n1 2 2 3 3 no swap in further iterations\nSecond Pass\n1 2 2 3 3 no swap in further iterations" }, { "code": null, "e": 3055, "s": 2896, "text": "In the recursive approach of Bubble sort, the base case is array length = 1. Otherwise traverse the array using single for loop and swap elements accordingly." }, { "code": null, "e": 3118, "s": 3055, "text": "Take input array Arr[] and length as number of elements in it." }, { "code": null, "e": 3181, "s": 3118, "text": "Take input array Arr[] and length as number of elements in it." }, { "code": null, "e": 3306, "s": 3181, "text": "Function recurbublSort(int arr[], int len) takes the array and its length and sorts the array recursively using bubble sort." }, { "code": null, "e": 3431, "s": 3306, "text": "Function recurbublSort(int arr[], int len) takes the array and its length and sorts the array recursively using bubble sort." }, { "code": null, "e": 3453, "s": 3431, "text": "Take a variable temp." }, { "code": null, "e": 3475, "s": 3453, "text": "Take a variable temp." }, { "code": null, "e": 3514, "s": 3475, "text": "If array length is 1 then return void." }, { "code": null, "e": 3553, "s": 3514, "text": "If array length is 1 then return void." }, { "code": null, "e": 3658, "s": 3553, "text": "Else traverse the array using single for loop and for each element arr[i]>arr[i+1], swap those elements." }, { "code": null, "e": 3763, "s": 3658, "text": "Else traverse the array using single for loop and for each element arr[i]>arr[i+1], swap those elements." }, { "code": null, "e": 3815, "s": 3763, "text": "Set temp=arr[i], arr[i]=arr[i+1] and arr[i+1]=temp." }, { "code": null, "e": 3867, "s": 3815, "text": "Set temp=arr[i], arr[i]=arr[i+1] and arr[i+1]=temp." }, { "code": null, "e": 3963, "s": 3867, "text": "Now decrement length by 1 as the previous loop placed the largest element at the last position." }, { "code": null, "e": 4059, "s": 3963, "text": "Now decrement length by 1 as the previous loop placed the largest element at the last position." }, { "code": null, "e": 4106, "s": 4059, "text": "Do a recursive call to recurbublSort(arr,len)." }, { "code": null, "e": 4153, "s": 4106, "text": "Do a recursive call to recurbublSort(arr,len)." }, { "code": null, "e": 4257, "s": 4153, "text": "At the end of all calls, when len becomes 1 we will come out of recursion and the array will be sorted." }, { "code": null, "e": 4361, "s": 4257, "text": "At the end of all calls, when len becomes 1 we will come out of recursion and the array will be sorted." }, { "code": null, "e": 4397, "s": 4361, "text": "Print the sorted array inside main." }, { "code": null, "e": 4433, "s": 4397, "text": "Print the sorted array inside main." }, { "code": null, "e": 4977, "s": 4433, "text": "#include <stdio.h>\nvoid recurbublSort(int arr[], int len){\n int temp;\n\n if (len == 1){\n return;\n }\n for (int i=0; i<len-1; i++){\n if (arr[i] > arr[i+1]){\n temp=arr[i];\n arr[i]=arr[i+1];\n arr[i+1]=temp;\n }\n }\n len=len-1;\n recurbublSort(arr, len);\n}\nint main(){\n int Arr[] = {21, 34, 20, 31, 78, 43, 66};\n int length = sizeof(Arr)/sizeof(Arr[0]);\n\n recurbublSort(Arr, length);\n\n printf(\"Sorted array : \");\n for(int i=0;i<length;i++){\n printf(\"%d \",Arr[i]);\n }\n\n return 0;\n}" }, { "code": null, "e": 5040, "s": 4977, "text": "If we run the above code it will generate the following Output" }, { "code": null, "e": 5075, "s": 5040, "text": "Sorted array: 20 21 31 34 43 66 78" } ]
Calculate time required to type a word using given single-row keyboard - GeeksforGeeks
13 Jan, 2022 Given a string keyboardLayout of size 26 representing the sequence of characters present in a single row of a keyboard and a string word, the task is to calculate the total time taken to type the word, starting from the 0th key, if moving to adjacent keys requires unit time. Examples: Input: keyboardLayout = “abcdefghijklmnopqrstuvwxyz”, word = “dog”Output: 22Explanation:Pressing the key ‘d’ requires 3 units of time ( i.e. ‘a’ -> ‘b’ -> ‘c’ -> ‘d’)Pressing the key ‘o’ requires 11 units of time ( i.e. ‘d’ -> ‘e’ -> ‘f’ -> ‘g’ -> ‘h’ -> ‘i’ -> ‘j’ -> ‘k’ -> ‘l’ -> ‘m’ -> ‘n’ -> ‘o’)Pressing the key ‘g’ requires 8 units of time ( i.e. ‘o’ -> ‘n’ -> ‘m’ -> ‘l’ -> ‘k’ -> ‘j’ -> ‘i’ -> ‘h’ -> ‘g’)Therefore, the total time taken = 3 + 11 + 8 = 22. Input: keyboardLayout = “abcdefghijklmnopqrstuvwxyz”, word = “abcdefghijklmnopqrstuvwxyz”Output: 25 Approach: Follow the steps below to solve the problem: Initialize a vector, say pos, to store the position of all the characters. Initialize two variables, say last, to store the last updated index, and result, to store the total time taken to type the word. Iterate over the characters of the string word:Initialize two variables, say destination, to store the index of the next character required to be typed, and distance, to store the distance of that index from the current index.Add the value of distance to result.Update the last to destination. Initialize two variables, say destination, to store the index of the next character required to be typed, and distance, to store the distance of that index from the current index. Add the value of distance to result. Update the last to destination. After completing the above operations, print the value of result. 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 calculate time// taken to type the given wordint timeTakenToType(string& keyboardLayout, string& word){ // Stores position of characters vector<int> pos(26); // Iterate over the range [0, 26] for (int i = 0; i < 26; ++i) { // Set position of each character char ch = keyboardLayout[i]; pos[ch - 'a'] = i; } // Store the last index int last = 0; // Stores the total time taken int result = 0; // Iterate over the characters of word for (int i = 0; i < (int)word.size(); ++i) { char ch = word[i]; // Stores index of the next character int destination = pos[ch - 'a']; // Stores the distance of current // character from the next character int distance = abs(destination - last); // Update the result result += distance; // Update last position last = destination; } // Print the result cout << result;} // Driver Codeint main(){ // Given keyboard layout string keyboardLayout = "acdbefghijlkmnopqrtsuwvxyz"; // Given word string word = "dog"; // Function call to find the minimum // time required to type the word timeTakenToType(keyboardLayout, word); return 0;} // Java program for the above approach import java.io.*; class GFG { // Function to calculate time // taken to type the given word static void timeTakenToType(String keyboardLayout, String word) { // Stores position of characters int[] pos = new int[26]; // Iterate over the range [0, 26] for (int i = 0; i < 26; i++) { // Set position of each character char ch = keyboardLayout.charAt(i); pos[ch - 'a'] = i; } // Store the last index int last = 0; // Stores the total time taken int result = 0; // Iterate over the characters of word for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); // Stores index of the next character int destination = pos[ch - 'a']; // Stores the distance of current // character from the next character int distance = Math.abs(destination - last); // Update the result result += distance; // Update last position last = destination; } System.out.println(result); } // Driver Code public static void main(String[] args) { // Given keyboard layout String keyboardLayout = "acdbefghijlkmnopqrtsuwvxyz"; // Given word String word = "dog"; // Function call to find the minimum // time required to type the word timeTakenToType(keyboardLayout, word); }} // This code is contributed by aadityapburujwale. # Python3 program for the above approach # Function to calculate time# taken to type the given worddef timeTakenToType(keyboardLayout, word): # Stores position of characters pos = [0]*(26) # Iterate over the range [0, 26] for i in range(26): # Set position of each character ch = keyboardLayout[i] pos[ord(ch) - ord('a')] = i # Store the last index last = 0 # Stores the total time taken result = 0 # Iterate over the characters of word for i in range(len(word)): ch = word[i] # Stores index of the next character destination = pos[ord(ch) - ord('a')] # Stores the distance of current # character from the next character distance = abs(destination - last) # Update the result result += distance # Update last position last = destination # Print result print (result) # Driver Codeif __name__ == '__main__': # Given keyboard layout keyboardLayout = "acdbefghijlkmnopqrtsuwvxyz" # Given word word = "dog" # Function call to find the minimum # time required to type the word timeTakenToType(keyboardLayout, word) # This code is contributed by mohit kumar 29. // C# program for the above approachusing System;public class GFG { // Function to calculate time // taken to type the given word static void timeTakenToType(String keyboardLayout, String word) { // Stores position of characters int[] pos = new int[26]; // Iterate over the range [0, 26] for (int i = 0; i < 26; i++) { // Set position of each character char ch = keyboardLayout[i]; pos[ch - 'a'] = i; } // Store the last index int last = 0; // Stores the total time taken int result = 0; // Iterate over the characters of word for (int i = 0; i < word.Length; i++) { char ch = word[i]; // Stores index of the next character int destination = pos[ch - 'a']; // Stores the distance of current // character from the next character int distance = Math.Abs(destination - last); // Update the result result += distance; // Update last position last = destination; } Console.WriteLine(result); } // Driver Code public static void Main(String[] args) { // Given keyboard layout String keyboardLayout = "acdbefghijlkmnopqrtsuwvxyz"; // Given word String word = "dog"; // Function call to find the minimum // time required to type the word timeTakenToType(keyboardLayout, word); }} // This code is contributed by shikhasingrajput <script> // Javascript program for the above approach // Function to calculate time// taken to type the given wordfunction timeTakenToType(keyboardLayout, word){ // Stores position of characters var pos = Array(26).fill(0); // Iterate over the range [0, 26] for(var i = 0; i < 26; ++i) { // Set position of each character var ch = keyboardLayout[i]; pos[ch.charCodeAt(0) - 'a'.charCodeAt(0)] = i; } // Store the last index var last = 0; // Stores the total time taken var result = 0; // Iterate over the characters of word for(var i = 0; i < word.length; ++i) { var ch = word[i]; // Stores index of the next character var destination = pos[ch.charCodeAt(0) - 'a'.charCodeAt(0)]; // Stores the distance of current // character from the next character var distance = Math.abs(destination - last); // Update the result result += distance; // Update last position last = destination; } // Print the result document.write(result);} // Driver Code // Given keyboard layoutvar keyboardLayout = "acdbefghijlkmnopqrtsuwvxyz"; // Given wordvar word = "dog"; // Function call to find the minimum// time required to type the wordtimeTakenToType(keyboardLayout, word); // This code is contributed by rutvik_56 </script> 22 Time Complexity: O(N), where N is the size of the string word.Auxiliary Space: O(1) mohit kumar 29 aadityapburujwale shikhasingrajput rutvik_56 anikaseth98 koulick_sadhu khushboogoyal499 cpp-map Hash Strings Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Rearrange an array such that arr[i] = i Quadratic Probing in Hashing Hashing in Java Advantages of BST over Hash Table Load Factor and Rehashing Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 C++ Data Types Write a program to print all permutations of a given string
[ { "code": null, "e": 25052, "s": 25024, "text": "\n13 Jan, 2022" }, { "code": null, "e": 25328, "s": 25052, "text": "Given a string keyboardLayout of size 26 representing the sequence of characters present in a single row of a keyboard and a string word, the task is to calculate the total time taken to type the word, starting from the 0th key, if moving to adjacent keys requires unit time." }, { "code": null, "e": 25338, "s": 25328, "text": "Examples:" }, { "code": null, "e": 25803, "s": 25338, "text": "Input: keyboardLayout = “abcdefghijklmnopqrstuvwxyz”, word = “dog”Output: 22Explanation:Pressing the key ‘d’ requires 3 units of time ( i.e. ‘a’ -> ‘b’ -> ‘c’ -> ‘d’)Pressing the key ‘o’ requires 11 units of time ( i.e. ‘d’ -> ‘e’ -> ‘f’ -> ‘g’ -> ‘h’ -> ‘i’ -> ‘j’ -> ‘k’ -> ‘l’ -> ‘m’ -> ‘n’ -> ‘o’)Pressing the key ‘g’ requires 8 units of time ( i.e. ‘o’ -> ‘n’ -> ‘m’ -> ‘l’ -> ‘k’ -> ‘j’ -> ‘i’ -> ‘h’ -> ‘g’)Therefore, the total time taken = 3 + 11 + 8 = 22." }, { "code": null, "e": 25903, "s": 25803, "text": "Input: keyboardLayout = “abcdefghijklmnopqrstuvwxyz”, word = “abcdefghijklmnopqrstuvwxyz”Output: 25" }, { "code": null, "e": 25958, "s": 25903, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 26033, "s": 25958, "text": "Initialize a vector, say pos, to store the position of all the characters." }, { "code": null, "e": 26162, "s": 26033, "text": "Initialize two variables, say last, to store the last updated index, and result, to store the total time taken to type the word." }, { "code": null, "e": 26456, "s": 26162, "text": "Iterate over the characters of the string word:Initialize two variables, say destination, to store the index of the next character required to be typed, and distance, to store the distance of that index from the current index.Add the value of distance to result.Update the last to destination." }, { "code": null, "e": 26636, "s": 26456, "text": "Initialize two variables, say destination, to store the index of the next character required to be typed, and distance, to store the distance of that index from the current index." }, { "code": null, "e": 26673, "s": 26636, "text": "Add the value of distance to result." }, { "code": null, "e": 26705, "s": 26673, "text": "Update the last to destination." }, { "code": null, "e": 26771, "s": 26705, "text": "After completing the above operations, print the value of result." }, { "code": null, "e": 26822, "s": 26771, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26826, "s": 26822, "text": "C++" }, { "code": null, "e": 26831, "s": 26826, "text": "Java" }, { "code": null, "e": 26839, "s": 26831, "text": "Python3" }, { "code": null, "e": 26842, "s": 26839, "text": "C#" }, { "code": null, "e": 26853, "s": 26842, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate time// taken to type the given wordint timeTakenToType(string& keyboardLayout, string& word){ // Stores position of characters vector<int> pos(26); // Iterate over the range [0, 26] for (int i = 0; i < 26; ++i) { // Set position of each character char ch = keyboardLayout[i]; pos[ch - 'a'] = i; } // Store the last index int last = 0; // Stores the total time taken int result = 0; // Iterate over the characters of word for (int i = 0; i < (int)word.size(); ++i) { char ch = word[i]; // Stores index of the next character int destination = pos[ch - 'a']; // Stores the distance of current // character from the next character int distance = abs(destination - last); // Update the result result += distance; // Update last position last = destination; } // Print the result cout << result;} // Driver Codeint main(){ // Given keyboard layout string keyboardLayout = \"acdbefghijlkmnopqrtsuwvxyz\"; // Given word string word = \"dog\"; // Function call to find the minimum // time required to type the word timeTakenToType(keyboardLayout, word); return 0;}", "e": 28209, "s": 26853, "text": null }, { "code": "// Java program for the above approach import java.io.*; class GFG { // Function to calculate time // taken to type the given word static void timeTakenToType(String keyboardLayout, String word) { // Stores position of characters int[] pos = new int[26]; // Iterate over the range [0, 26] for (int i = 0; i < 26; i++) { // Set position of each character char ch = keyboardLayout.charAt(i); pos[ch - 'a'] = i; } // Store the last index int last = 0; // Stores the total time taken int result = 0; // Iterate over the characters of word for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); // Stores index of the next character int destination = pos[ch - 'a']; // Stores the distance of current // character from the next character int distance = Math.abs(destination - last); // Update the result result += distance; // Update last position last = destination; } System.out.println(result); } // Driver Code public static void main(String[] args) { // Given keyboard layout String keyboardLayout = \"acdbefghijlkmnopqrtsuwvxyz\"; // Given word String word = \"dog\"; // Function call to find the minimum // time required to type the word timeTakenToType(keyboardLayout, word); }} // This code is contributed by aadityapburujwale.", "e": 29633, "s": 28209, "text": null }, { "code": "# Python3 program for the above approach # Function to calculate time# taken to type the given worddef timeTakenToType(keyboardLayout, word): # Stores position of characters pos = [0]*(26) # Iterate over the range [0, 26] for i in range(26): # Set position of each character ch = keyboardLayout[i] pos[ord(ch) - ord('a')] = i # Store the last index last = 0 # Stores the total time taken result = 0 # Iterate over the characters of word for i in range(len(word)): ch = word[i] # Stores index of the next character destination = pos[ord(ch) - ord('a')] # Stores the distance of current # character from the next character distance = abs(destination - last) # Update the result result += distance # Update last position last = destination # Print result print (result) # Driver Codeif __name__ == '__main__': # Given keyboard layout keyboardLayout = \"acdbefghijlkmnopqrtsuwvxyz\" # Given word word = \"dog\" # Function call to find the minimum # time required to type the word timeTakenToType(keyboardLayout, word) # This code is contributed by mohit kumar 29.", "e": 30865, "s": 29633, "text": null }, { "code": "// C# program for the above approachusing System;public class GFG { // Function to calculate time // taken to type the given word static void timeTakenToType(String keyboardLayout, String word) { // Stores position of characters int[] pos = new int[26]; // Iterate over the range [0, 26] for (int i = 0; i < 26; i++) { // Set position of each character char ch = keyboardLayout[i]; pos[ch - 'a'] = i; } // Store the last index int last = 0; // Stores the total time taken int result = 0; // Iterate over the characters of word for (int i = 0; i < word.Length; i++) { char ch = word[i]; // Stores index of the next character int destination = pos[ch - 'a']; // Stores the distance of current // character from the next character int distance = Math.Abs(destination - last); // Update the result result += distance; // Update last position last = destination; } Console.WriteLine(result); } // Driver Code public static void Main(String[] args) { // Given keyboard layout String keyboardLayout = \"acdbefghijlkmnopqrtsuwvxyz\"; // Given word String word = \"dog\"; // Function call to find the minimum // time required to type the word timeTakenToType(keyboardLayout, word); }} // This code is contributed by shikhasingrajput", "e": 32269, "s": 30865, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to calculate time// taken to type the given wordfunction timeTakenToType(keyboardLayout, word){ // Stores position of characters var pos = Array(26).fill(0); // Iterate over the range [0, 26] for(var i = 0; i < 26; ++i) { // Set position of each character var ch = keyboardLayout[i]; pos[ch.charCodeAt(0) - 'a'.charCodeAt(0)] = i; } // Store the last index var last = 0; // Stores the total time taken var result = 0; // Iterate over the characters of word for(var i = 0; i < word.length; ++i) { var ch = word[i]; // Stores index of the next character var destination = pos[ch.charCodeAt(0) - 'a'.charCodeAt(0)]; // Stores the distance of current // character from the next character var distance = Math.abs(destination - last); // Update the result result += distance; // Update last position last = destination; } // Print the result document.write(result);} // Driver Code // Given keyboard layoutvar keyboardLayout = \"acdbefghijlkmnopqrtsuwvxyz\"; // Given wordvar word = \"dog\"; // Function call to find the minimum// time required to type the wordtimeTakenToType(keyboardLayout, word); // This code is contributed by rutvik_56 </script>", "e": 33680, "s": 32269, "text": null }, { "code": null, "e": 33683, "s": 33680, "text": "22" }, { "code": null, "e": 33768, "s": 33683, "text": "Time Complexity: O(N), where N is the size of the string word.Auxiliary Space: O(1) " }, { "code": null, "e": 33785, "s": 33770, "text": "mohit kumar 29" }, { "code": null, "e": 33803, "s": 33785, "text": "aadityapburujwale" }, { "code": null, "e": 33820, "s": 33803, "text": "shikhasingrajput" }, { "code": null, "e": 33830, "s": 33820, "text": "rutvik_56" }, { "code": null, "e": 33842, "s": 33830, "text": "anikaseth98" }, { "code": null, "e": 33856, "s": 33842, "text": "koulick_sadhu" }, { "code": null, "e": 33873, "s": 33856, "text": "khushboogoyal499" }, { "code": null, "e": 33881, "s": 33873, "text": "cpp-map" }, { "code": null, "e": 33886, "s": 33881, "text": "Hash" }, { "code": null, "e": 33894, "s": 33886, "text": "Strings" }, { "code": null, "e": 33899, "s": 33894, "text": "Hash" }, { "code": null, "e": 33907, "s": 33899, "text": "Strings" }, { "code": null, "e": 34005, "s": 33907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34014, "s": 34005, "text": "Comments" }, { "code": null, "e": 34027, "s": 34014, "text": "Old Comments" }, { "code": null, "e": 34067, "s": 34027, "text": "Rearrange an array such that arr[i] = i" }, { "code": null, "e": 34096, "s": 34067, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 34112, "s": 34096, "text": "Hashing in Java" }, { "code": null, "e": 34146, "s": 34112, "text": "Advantages of BST over Hash Table" }, { "code": null, "e": 34172, "s": 34146, "text": "Load Factor and Rehashing" }, { "code": null, "e": 34197, "s": 34172, "text": "Reverse a string in Java" }, { "code": null, "e": 34243, "s": 34197, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 34277, "s": 34243, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 34292, "s": 34277, "text": "C++ Data Types" } ]
C - Derived and User Defined Data Types - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to learn about derived and user defined data types in C Language. Data types that are derived from fundamental data types are called derived data types. Derived data types do not create new data types. Instead, they add some functionality to the existing data types. Derived data types are derived from the primitive data types by adding some extra relationships with the various elements of the primary data types. The derived data type can be used to represent a single value or multiple values. Given below are the various derived data types used in C: Arrays: An array is an ordered sequence of finite data items of the same data type that share a common name. pointers: A pointer is a special type of variable used to hold the address of another variable. Functions: A function is a self-contained block of one or more statements with a name. Structures: A structure is a collection of different data type items stored in a contiguous memory allocation. Unions: A union is similar to a structure where the memory allocated to the largest data type is reused for other types in the group. Arrays: An array is an ordered sequence of finite data items of the same data type that share a common name. pointers: A pointer is a special type of variable used to hold the address of another variable. Functions: A function is a self-contained block of one or more statements with a name. Structures: A structure is a collection of different data type items stored in a contiguous memory allocation. Unions: A union is similar to a structure where the memory allocated to the largest data type is reused for other types in the group. In some situations, structures and unions can also be called the user-defines data types. A Structure is used to organize a group of related data items of different data types referring to a single entity. i.e., a single variable capable of holding data items of different data types. The data items in a structure are usually related like different kinds of information about a person or about a part or about an account, etc. Each data item in a structure is called a member, sometimes these members are also called fields. The keyword used to create a structure is a struct. The advantage of using a structure is that the accessibility of members becomes easier since all the members of a specific structure get the allocation of continuous memory and therefore it minimizes the memory access time. Generally, a structure can be declared as: struct tag_name { data_type1 svar_1; data_type2 svar_2; .... .... data_typen svar_n; }; The declaration begins with the keyword struct. The list of the declaration of its members must be enclosed in braces, the tag_name is an identifier that specifies the new structure name. The declaration of a structure does not reserve any storage space. But the definition of the structure creates structure variables. The structure variables can be defined as: struct tag_name svar_1, svar_2 ...svar_n; Lets us consider an example: struct sample { int a, b; float c, d; char e, f; }; struct sample v1, v2, v3; //structure definition A union is also a collection of different data types in C but that allows to store different data types in the same memory location. User can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose. A union is same as structures but the difference is that only one member can be accessed at a time because the memory is created only for one member which has the highest number of bytes in size. A union is declared by using the keyword union and members of the union can be accessed by using dot (.) operator. The declaration and definition of the union is: union tag_name { data_type1 uvar_1; data_type2 uvar_2; ...... data_typen uvar_n; }; union tag_name uvar_1, uvar_2,....uvar_n; Lets consider an example: union sample { int age; float price; char name; }; union sample s; In the above example 4 bytes of memory is allocated to the union variable s, the members can be accessed as s.number, s.price, s.name but only one member can be accessed at a time because the same memory is used for all the 3 members. The keyword typedef is used to create a new name (alias) for an existing data type. It does not create a new data type. The syntax of using typedef is as follows: typedef existing_type new_data_type; Consider the following example: #include <stdio.h> void main() { typedef int Tutorials; //statement-1 Tutorials a = 17; printf("Given value =%d\n", a); } In statement – 1, the keyword typedef is used to create Tutorials as the alias for the int data type. From this statement onwards, Tutorials will be the new name for int in this program and the variables declared as Tutorials type will also behave like int variables for all practical purposes. enum is a keyword used to create an enumerated data type. An enum (enumerated data type) is a special data type consisting of a set of named values called elements or members. It is mainly used to assign names to integral constants, which makes a program more readable. The format for creating an enum type is enum identifier (value1, value2, .... , valueN); Enumerated types allow us to create our own symbolic names for a list of related constants. For example, we could create an enumerated data type for true and false as enum Boolean { false, true }; If we do not explicitly assign values to enum names, the compiler assigns values starting from 0 by default. Here, false is assigned 0, and true is assigned 1 automatically. (The first field of the enum is replaced with the value 0 and the next field with 1 and so on.) Consider the following example using enum. #include <stdio.h> void main() { enum month {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; enum month birthday = JUL; printf("Birthday Month = %d", birthday); } The field name JAN is assigned the value 1. Hence, the next field name is automatically assigned the value 2 and so on. The above program will print the output as follows: Birthday Month = 7 void keyword is an empty data type that represents no value. It is used in functions and pointers. When used in functions, the void data type does not create any variable. It is used to represent the return type of a function. User cannot declare a variable by using void as void bad_variable; because it does not allocate any memory space for the void type variables. The void keyword can be used as the return type and parameter type in a function as given below: void main(void) { } It specifies that the main() function does not receive and return anything. Wiki – Data Type C Data Types Happy Learning 🙂 What are the Data types in C? C – Floating Point Data Types C – Integer Data Types – int, short int, long int and char PHP Data types Example Tutorials User defined Exceptions in Python User defined sorting with Java 8 Comparator What are different Python Data Types Types Of Inheritance in Java user defined exceptions in Java Python Set Data Structure in Depth Organization of data In Data Structures Python TypeCasting for Different Types Java variable types Example Java Class Example Tutorials What is Data Structures ? What are the Data types in C? C – Floating Point Data Types C – Integer Data Types – int, short int, long int and char PHP Data types Example Tutorials User defined Exceptions in Python User defined sorting with Java 8 Comparator What are different Python Data Types Types Of Inheritance in Java user defined exceptions in Java Python Set Data Structure in Depth Organization of data In Data Structures Python TypeCasting for Different Types Java variable types Example Java Class Example Tutorials What is Data Structures ? Δ C – Introduction C – Features C – Variables & Keywords C – Program Structure C – Comment Lines & Tokens C – Number System C – Local and Global Variables C – Scope & Lifetime of Variables C – Data Types C – Integer Data Types C – Floating Data Types C – Derived, Defined Data Types C – Type Conversions C – Arithmetic Operators C – Bitwise Operators C – Logical Operators C – Comma and sizeof Operators C – Operator Precedence and Associativity C – Relational Operators C Flow Control – if, if-else, nested if-else, if-else-if C – Switch Case C Iterative – for, while, dowhile loops C Unconditional – break, continue, goto statements C – Expressions and Statements C – Header Files & Preprocessor Directives C – One Dimensional Arrays C – Multi Dimensional Arrays C – Pointers Basics C – Pointers with Arrays C – Functions C – How to Pass Arrays to Functions C – Categories of Functions C – User defined Functions C – Formal and Actual Arguments C – Recursion functions C – Structures Part -1 C – Structures Part -2 C – Unions C – File Handling C – File Operations C – Dynamic Memory Allocation C Program – Fibonacci Series C Program – Prime or Not C Program – Factorial of Number C Program – Even or Odd C Program – Sum of digits till Single Digit C Program – Sum of digits C Program – Reverse of a number C Program – Armstrong Numbers C Program – Print prime Numbers C Program – GCD of two Numbers C Program – Number Palindrome or Not C Program – Find Largest and Smallest number in an Array C Program – Add elements of an Array C Program – Addition of Matrices C Program – Multiplication of Matrices C Program – Reverse of an Array C Program – Bubble Sort C Program – Add and Sub without using + –
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 495, "s": 398, "text": "In this tutorial, we are going to learn about derived and user defined data types in C Language." }, { "code": null, "e": 582, "s": 495, "text": "Data types that are derived from fundamental data types are called derived data types." }, { "code": null, "e": 696, "s": 582, "text": "Derived data types do not create new data types. Instead, they add some functionality to the existing data types." }, { "code": null, "e": 927, "s": 696, "text": "Derived data types are derived from the primitive data types by adding some extra relationships with the various elements of the primary data types. The derived data type can be used to represent a single value or multiple values." }, { "code": null, "e": 985, "s": 927, "text": "Given below are the various derived data types used in C:" }, { "code": null, "e": 1524, "s": 985, "text": "\nArrays: An array is an ordered sequence of finite data items of the same data type that share a common name.\npointers: A pointer is a special type of variable used to hold the address of another variable.\nFunctions: A function is a self-contained block of one or more statements with a name.\nStructures: A structure is a collection of different data type items stored in a contiguous memory allocation.\nUnions: A union is similar to a structure where the memory allocated to the largest data type is reused for other types in the group.\n" }, { "code": null, "e": 1633, "s": 1524, "text": "Arrays: An array is an ordered sequence of finite data items of the same data type that share a common name." }, { "code": null, "e": 1729, "s": 1633, "text": "pointers: A pointer is a special type of variable used to hold the address of another variable." }, { "code": null, "e": 1816, "s": 1729, "text": "Functions: A function is a self-contained block of one or more statements with a name." }, { "code": null, "e": 1927, "s": 1816, "text": "Structures: A structure is a collection of different data type items stored in a contiguous memory allocation." }, { "code": null, "e": 2061, "s": 1927, "text": "Unions: A union is similar to a structure where the memory allocated to the largest data type is reused for other types in the group." }, { "code": null, "e": 2151, "s": 2061, "text": "In some situations, structures and unions can also be called the user-defines data types." }, { "code": null, "e": 2346, "s": 2151, "text": "A Structure is used to organize a group of related data items of different data types referring to a single entity. i.e., a single variable capable of holding data items of different data types." }, { "code": null, "e": 2587, "s": 2346, "text": "The data items in a structure are usually related like different kinds of information about a person or about a part or about an account, etc. Each data item in a structure is called a member, sometimes these members are also called fields." }, { "code": null, "e": 2863, "s": 2587, "text": "The keyword used to create a structure is a struct. The advantage of using a structure is that the accessibility of members becomes easier since all the members of a specific structure get the allocation of continuous memory and therefore it minimizes the memory access time." }, { "code": null, "e": 2906, "s": 2863, "text": "Generally, a structure can be declared as:" }, { "code": null, "e": 3004, "s": 2906, "text": "struct tag_name {\n data_type1 svar_1;\n data_type2 svar_2;\n ....\n ....\n data_typen svar_n;\n};" }, { "code": null, "e": 3192, "s": 3004, "text": "The declaration begins with the keyword struct. The list of the declaration of its members must be enclosed in braces, the tag_name is an identifier that specifies the new structure name." }, { "code": null, "e": 3324, "s": 3192, "text": "The declaration of a structure does not reserve any storage space. But the definition of the structure creates structure variables." }, { "code": null, "e": 3367, "s": 3324, "text": "The structure variables can be defined as:" }, { "code": null, "e": 3409, "s": 3367, "text": "struct tag_name svar_1, svar_2 ...svar_n;" }, { "code": null, "e": 3438, "s": 3409, "text": "Lets us consider an example:" }, { "code": null, "e": 3547, "s": 3438, "text": "struct sample { \n int a, b;\n float c, d;\n char e, f;\n}; \nstruct sample v1, v2, v3; //structure definition" }, { "code": null, "e": 3680, "s": 3547, "text": "A union is also a collection of different data types in C but that allows to store different data types in the same memory location." }, { "code": null, "e": 3782, "s": 3680, "text": "User can define a union with many members, but only one member can contain a value at any given time." }, { "code": null, "e": 3870, "s": 3782, "text": "Unions provide an efficient way of using the same memory location for multiple-purpose." }, { "code": null, "e": 4066, "s": 3870, "text": "A union is same as structures but the difference is that only one member can be accessed at a time because the memory is created only for one member which has the highest number of bytes in size." }, { "code": null, "e": 4181, "s": 4066, "text": "A union is declared by using the keyword union and members of the union can be accessed by using dot (.) operator." }, { "code": null, "e": 4229, "s": 4181, "text": "The declaration and definition of the union is:" }, { "code": null, "e": 4364, "s": 4229, "text": "union tag_name {\n data_type1 uvar_1; \n data_type2 uvar_2;\n ......\n data_typen uvar_n;\n};\nunion tag_name uvar_1, uvar_2,....uvar_n;" }, { "code": null, "e": 4390, "s": 4364, "text": "Lets consider an example:" }, { "code": null, "e": 4464, "s": 4390, "text": "union sample {\n int age;\n float price;\n char name;\n};\nunion sample s;\n" }, { "code": null, "e": 4699, "s": 4464, "text": "In the above example 4 bytes of memory is allocated to the union variable s, the members can be accessed as s.number, s.price, s.name but only one member can be accessed at a time because the same memory is used for all the 3 members." }, { "code": null, "e": 4862, "s": 4699, "text": "The keyword typedef is used to create a new name (alias) for an existing data type. It does not create a new data type. The syntax of using typedef is as follows:" }, { "code": null, "e": 4901, "s": 4862, "text": "typedef existing_type new_data_type;" }, { "code": null, "e": 4933, "s": 4901, "text": "Consider the following example:" }, { "code": null, "e": 5070, "s": 4933, "text": "#include <stdio.h>\nvoid main() {\n typedef int Tutorials; //statement-1\n Tutorials a = 17;\n printf(\"Given value =%d\\n\", a);\n}" }, { "code": null, "e": 5365, "s": 5070, "text": "In statement – 1, the keyword typedef is used to create Tutorials as the alias for the int data type. From this statement onwards, Tutorials will be the new name for int in this program and the variables declared as Tutorials type will also behave like int variables for all practical purposes." }, { "code": null, "e": 5423, "s": 5365, "text": "enum is a keyword used to create an enumerated data type." }, { "code": null, "e": 5635, "s": 5423, "text": "An enum (enumerated data type) is a special data type consisting of a set of named values called elements or members. It is mainly used to assign names to integral constants, which makes a program more readable." }, { "code": null, "e": 5676, "s": 5635, "text": "The format for creating an enum type is" }, { "code": null, "e": 5725, "s": 5676, "text": "enum identifier (value1, value2, .... , valueN);" }, { "code": null, "e": 5817, "s": 5725, "text": "Enumerated types allow us to create our own symbolic names for a list of related constants." }, { "code": null, "e": 5892, "s": 5817, "text": "For example, we could create an enumerated data type for true and false as" }, { "code": null, "e": 5932, "s": 5892, "text": "enum Boolean {\n false,\n true\n};" }, { "code": null, "e": 6041, "s": 5932, "text": "If we do not explicitly assign values to enum names, the compiler assigns values starting from 0 by default." }, { "code": null, "e": 6202, "s": 6041, "text": "Here, false is assigned 0, and true is assigned 1 automatically. (The first field of the enum is replaced with the value 0 and the next field with 1 and so on.)" }, { "code": null, "e": 6245, "s": 6202, "text": "Consider the following example using enum." }, { "code": null, "e": 6433, "s": 6245, "text": "#include <stdio.h>\n void main() { \n enum month {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; \n enum month birthday = JUL; \n printf(\"Birthday Month = %d\", birthday); \n}" }, { "code": null, "e": 6553, "s": 6433, "text": "The field name JAN is assigned the value 1. Hence, the next field name is automatically assigned the value 2 and so on." }, { "code": null, "e": 6605, "s": 6553, "text": "The above program will print the output as follows:" }, { "code": null, "e": 6624, "s": 6605, "text": "Birthday Month = 7" }, { "code": null, "e": 6723, "s": 6624, "text": "void keyword is an empty data type that represents no value. It is used in functions and pointers." }, { "code": null, "e": 6899, "s": 6723, "text": "When used in functions, the void data type does not create any variable. It is used to represent the return type of a function. User cannot declare a variable by using void as" }, { "code": null, "e": 6918, "s": 6899, "text": "void bad_variable;" }, { "code": null, "e": 6993, "s": 6918, "text": "because it does not allocate any memory space for the void type variables." }, { "code": null, "e": 7090, "s": 6993, "text": "The void keyword can be used as the return type and parameter type in a function as given below:" }, { "code": null, "e": 7110, "s": 7090, "text": "void main(void) { }" }, { "code": null, "e": 7186, "s": 7110, "text": "It specifies that the main() function does not receive and return anything." }, { "code": null, "e": 7203, "s": 7186, "text": "Wiki – Data Type" }, { "code": null, "e": 7216, "s": 7203, "text": "C Data Types" }, { "code": null, "e": 7233, "s": 7216, "text": "Happy Learning 🙂" }, { "code": null, "e": 7760, "s": 7233, "text": "\nWhat are the Data types in C?\nC – Floating Point Data Types\nC – Integer Data Types – int, short int, long int and char\nPHP Data types Example Tutorials\nUser defined Exceptions in Python\nUser defined sorting with Java 8 Comparator\nWhat are different Python Data Types\nTypes Of Inheritance in Java\nuser defined exceptions in Java\nPython Set Data Structure in Depth\nOrganization of data In Data Structures\nPython TypeCasting for Different Types\nJava variable types Example\nJava Class Example Tutorials\nWhat is Data Structures ?\n" }, { "code": null, "e": 7790, "s": 7760, "text": "What are the Data types in C?" }, { "code": null, "e": 7820, "s": 7790, "text": "C – Floating Point Data Types" }, { "code": null, "e": 7879, "s": 7820, "text": "C – Integer Data Types – int, short int, long int and char" }, { "code": null, "e": 7912, "s": 7879, "text": "PHP Data types Example Tutorials" }, { "code": null, "e": 7946, "s": 7912, "text": "User defined Exceptions in Python" }, { "code": null, "e": 7990, "s": 7946, "text": "User defined sorting with Java 8 Comparator" }, { "code": null, "e": 8027, "s": 7990, "text": "What are different Python Data Types" }, { "code": null, "e": 8056, "s": 8027, "text": "Types Of Inheritance in Java" }, { "code": null, "e": 8088, "s": 8056, "text": "user defined exceptions in Java" }, { "code": null, "e": 8123, "s": 8088, "text": "Python Set Data Structure in Depth" }, { "code": null, "e": 8163, "s": 8123, "text": "Organization of data In Data Structures" }, { "code": null, "e": 8202, "s": 8163, "text": "Python TypeCasting for Different Types" }, { "code": null, "e": 8230, "s": 8202, "text": "Java variable types Example" }, { "code": null, "e": 8259, "s": 8230, "text": "Java Class Example Tutorials" }, { "code": null, "e": 8285, "s": 8259, "text": "What is Data Structures ?" }, { "code": null, "e": 8291, "s": 8289, "text": "Δ" }, { "code": null, "e": 8309, "s": 8291, "text": " C – Introduction" }, { "code": null, "e": 8323, "s": 8309, "text": " C – Features" }, { "code": null, "e": 8349, "s": 8323, "text": " C – Variables & Keywords" }, { "code": null, "e": 8372, "s": 8349, "text": " C – Program Structure" }, { "code": null, "e": 8401, "s": 8372, "text": " C – Comment Lines & Tokens" }, { "code": null, "e": 8420, "s": 8401, "text": " C – Number System" }, { "code": null, "e": 8452, "s": 8420, "text": " C – Local and Global Variables" }, { "code": null, "e": 8487, "s": 8452, "text": " C – Scope & Lifetime of Variables" }, { "code": null, "e": 8503, "s": 8487, "text": " C – Data Types" }, { "code": null, "e": 8527, "s": 8503, "text": " C – Integer Data Types" }, { "code": null, "e": 8552, "s": 8527, "text": " C – Floating Data Types" }, { "code": null, "e": 8585, "s": 8552, "text": " C – Derived, Defined Data Types" }, { "code": null, "e": 8607, "s": 8585, "text": " C – Type Conversions" }, { "code": null, "e": 8633, "s": 8607, "text": " C – Arithmetic Operators" }, { "code": null, "e": 8656, "s": 8633, "text": " C – Bitwise Operators" }, { "code": null, "e": 8679, "s": 8656, "text": " C – Logical Operators" }, { "code": null, "e": 8712, "s": 8679, "text": " C – Comma and sizeof Operators" }, { "code": null, "e": 8755, "s": 8712, "text": " C – Operator Precedence and Associativity" }, { "code": null, "e": 8781, "s": 8755, "text": " C – Relational Operators" }, { "code": null, "e": 8839, "s": 8781, "text": " C Flow Control – if, if-else, nested if-else, if-else-if" }, { "code": null, "e": 8856, "s": 8839, "text": " C – Switch Case" }, { "code": null, "e": 8897, "s": 8856, "text": " C Iterative – for, while, dowhile loops" }, { "code": null, "e": 8949, "s": 8897, "text": " C Unconditional – break, continue, goto statements" }, { "code": null, "e": 8981, "s": 8949, "text": " C – Expressions and Statements" }, { "code": null, "e": 9025, "s": 8981, "text": " C – Header Files & Preprocessor Directives" }, { "code": null, "e": 9053, "s": 9025, "text": " C – One Dimensional Arrays" }, { "code": null, "e": 9083, "s": 9053, "text": " C – Multi Dimensional Arrays" }, { "code": null, "e": 9104, "s": 9083, "text": " C – Pointers Basics" }, { "code": null, "e": 9130, "s": 9104, "text": " C – Pointers with Arrays" }, { "code": null, "e": 9145, "s": 9130, "text": " C – Functions" }, { "code": null, "e": 9182, "s": 9145, "text": " C – How to Pass Arrays to Functions" }, { "code": null, "e": 9211, "s": 9182, "text": " C – Categories of Functions" }, { "code": null, "e": 9239, "s": 9211, "text": " C – User defined Functions" }, { "code": null, "e": 9272, "s": 9239, "text": " C – Formal and Actual Arguments" }, { "code": null, "e": 9297, "s": 9272, "text": " C – Recursion functions" }, { "code": null, "e": 9321, "s": 9297, "text": " C – Structures Part -1" }, { "code": null, "e": 9345, "s": 9321, "text": " C – Structures Part -2" }, { "code": null, "e": 9357, "s": 9345, "text": " C – Unions" }, { "code": null, "e": 9376, "s": 9357, "text": " C – File Handling" }, { "code": null, "e": 9397, "s": 9376, "text": " C – File Operations" }, { "code": null, "e": 9428, "s": 9397, "text": " C – Dynamic Memory Allocation" }, { "code": null, "e": 9458, "s": 9428, "text": " C Program – Fibonacci Series" }, { "code": null, "e": 9484, "s": 9458, "text": " C Program – Prime or Not" }, { "code": null, "e": 9517, "s": 9484, "text": " C Program – Factorial of Number" }, { "code": null, "e": 9542, "s": 9517, "text": " C Program – Even or Odd" }, { "code": null, "e": 9587, "s": 9542, "text": " C Program – Sum of digits till Single Digit" }, { "code": null, "e": 9614, "s": 9587, "text": " C Program – Sum of digits" }, { "code": null, "e": 9647, "s": 9614, "text": " C Program – Reverse of a number" }, { "code": null, "e": 9678, "s": 9647, "text": " C Program – Armstrong Numbers" }, { "code": null, "e": 9711, "s": 9678, "text": " C Program – Print prime Numbers" }, { "code": null, "e": 9743, "s": 9711, "text": " C Program – GCD of two Numbers" }, { "code": null, "e": 9781, "s": 9743, "text": " C Program – Number Palindrome or Not" }, { "code": null, "e": 9839, "s": 9781, "text": " C Program – Find Largest and Smallest number in an Array" }, { "code": null, "e": 9877, "s": 9839, "text": " C Program – Add elements of an Array" }, { "code": null, "e": 9911, "s": 9877, "text": " C Program – Addition of Matrices" }, { "code": null, "e": 9951, "s": 9911, "text": " C Program – Multiplication of Matrices" }, { "code": null, "e": 9984, "s": 9951, "text": " C Program – Reverse of an Array" }, { "code": null, "e": 10009, "s": 9984, "text": " C Program – Bubble Sort" } ]
Height & Distance - Solved Examples
Q 1 - From a point 375 meters away from the foot of a tower, the top of the tower is observed at an angle of elevation of 45°, then the height (in meters) of the tower is? A - 375 B - 450 C - 225 D - 250 Answer - A Explanation From the right angled triangle Tan(45°)= X/375 => X = 375 m Q 2 - The angle of elevation of a tower at a point 90 m from it is cot-1(4/5).Then the height of the tower is A - 45 B - 90 C - 112.5 D - 150 Answer - C Explanation Let cot-1(4/5) = x => cotx = 4/5 => tan(x) = 5/4 From the right angled triangle Tan(x) = h/90 => h = 5/4*90 =112.5 m Q 3 - On the level ground, the angle of elevation of the top of a tower is 30°.on moving 20 meters nearer, the angle of elevation is 45°.Then the height of the tower is A - 10 B - √3 C - 10√3 D - 20√3 Answer - C Explanation Let h be the height of tower From figure. 20 =h ( cot30 - cot60) 20 =h (√3-1/√3) => 20√3 = h (3-1) => h=10√3. Q 4 - The angles of elevation of the tops of two vertical towers as seen from the middle point of the lines joining the foot of the towers are 45° & 60°.The ratio of the height of the towers is A - √3:2 B - √3:1 C - 2:√3 D - 2:1 Answer - B Explanation Tan(60)=h1/AB => h1=√3AB Tan(45)=h1/BC => h2=BC h1/ h2=√3/1 => h1:h2=√3:1 Q 5 - The heights of two towers are 90 meters and 45 meters. The line joining their tops make an angle 450 with the horizontal then the distance between the two towers is A - 22.5 m B - 45 m C - 60 m D - 30 m Answer - B Explanation Let the distance between the towers be X From the right angled triangle CFD Tan(45)= (90-45)/X => x=45 meters Q 6 - From a point P on a level ground, the angle of elevation of the top tower is 60°. If the tower is 180 m high, the distance of point P from the foot of the tower is A - 60√3 B - 40√3 C - 30√3 D - 20√3 Answer - A Explanation From ∠APB = 60° and AB = 180 m. AB/AP= tan 60° =√3 AP=AB/√3 =180/√3=60√3 Q 7 - The Top of a 25 meter high tower makes an angle of elevation of 450 with the bottom of an electric pole and angle of elevation of 30 degree with the top of pole. Find the height of the electric pole. A - 25√3 B - 25((√3-1)/√3) C - 25/√3 D - 25((1-√3)/√3) Answer - B Explanation Let AB be the tower and CD be the electric pole. From the figure CA = DE => 25/(Tan(45))=(25-h)/(Tan(30)) => 25 Tan(30) = 25-h => h=25-25Tan(30) =25(1- Tan(30)) =25((√3-1)/√3) Q 8 - An observer 1.4 m tall is 10√3 away from a tower. The angle of elevation from his eye to the top of the tower is 60°. The heights of the tower is A - 12.4 m B - 6.2 m C - 11.4√3 m D - 11.4 m Answer - D Explanation Let AB be the observer and CD be the tower. Then, CE = AB = 1.4 m, BE = AC = 10v3 m. DE/BE=Tan (30) =1/√3 DE=10√3/√3=10 CD=CE+DE=1.4+10=11.4 m Q 9 - A man is watching form the top of the tower a boat speeding away from the tower. The boat makes the angle of depression of 60° with the man's eye when at a distance of 75 meters from the tower. After 10 seconds the angle of depression becomes 45°. What is the approximate speed of the boat, assuming that it is running in still water? A - 54 kmph B - 64 kmph C - 24 kmph D - 19.8 kmph Answer - D Explanation Let AB be the tower and C and D be the positions of the boat. Distance travelled by boat = CD From the figure 75tan(60)=(75+CD)tan(45) =>75√3 = 75+CD =>CD =55 m Speed = distance/time=55/10 =5.5 m/sec=19.8 kmph Q 10 - The horizontal distance between two towers is 90 m. The angular depression of the top of the first as seen from the top of the second which is 180 m high is 450.Then the height of the first is A - 90√3 m B - 45 m C - 90 m D - 150 m Answer - C Explanation =>(180-h)/90 = Tan(45) => h =90 m 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 4064, "s": 3892, "text": "Q 1 - From a point 375 meters away from the foot of a tower, the top of the tower is observed at an angle of elevation of 45°, then the height (in meters) of the tower is?" }, { "code": null, "e": 4072, "s": 4064, "text": "A - 375" }, { "code": null, "e": 4080, "s": 4072, "text": "B - 450" }, { "code": null, "e": 4088, "s": 4080, "text": "C - 225" }, { "code": null, "e": 4096, "s": 4088, "text": "D - 250" }, { "code": null, "e": 4107, "s": 4096, "text": "Answer - A" }, { "code": null, "e": 4119, "s": 4107, "text": "Explanation" }, { "code": null, "e": 4181, "s": 4119, "text": "From the right angled triangle\nTan(45°)= X/375\n=> X = 375 m\n" }, { "code": null, "e": 4291, "s": 4181, "text": "Q 2 - The angle of elevation of a tower at a point 90 m from it is cot-1(4/5).Then the height of the tower is" }, { "code": null, "e": 4298, "s": 4291, "text": "A - 45" }, { "code": null, "e": 4306, "s": 4298, "text": "B - 90" }, { "code": null, "e": 4316, "s": 4306, "text": "C - 112.5" }, { "code": null, "e": 4324, "s": 4316, "text": "D - 150" }, { "code": null, "e": 4335, "s": 4324, "text": "Answer - C" }, { "code": null, "e": 4347, "s": 4335, "text": "Explanation" }, { "code": null, "e": 4475, "s": 4347, "text": "Let cot-1(4/5) = x \n=> cotx = 4/5 \n=> tan(x) = 5/4 \nFrom the right angled triangle\nTan(x) = h/90 \n=> h = 5/4*90 =112.5 m\n" }, { "code": null, "e": 4644, "s": 4475, "text": "Q 3 - On the level ground, the angle of elevation of the top of a tower is 30°.on moving 20 meters nearer, the angle of elevation is 45°.Then the height of the tower is" }, { "code": null, "e": 4651, "s": 4644, "text": "A - 10" }, { "code": null, "e": 4658, "s": 4651, "text": "B - √3" }, { "code": null, "e": 4667, "s": 4658, "text": "C - 10√3" }, { "code": null, "e": 4676, "s": 4667, "text": "D - 20√3" }, { "code": null, "e": 4687, "s": 4676, "text": "Answer - C" }, { "code": null, "e": 4699, "s": 4687, "text": "Explanation" }, { "code": null, "e": 4814, "s": 4699, "text": "Let h be the height of tower\nFrom figure.\n20 =h ( cot30 - cot60)\t\n20 =h (√3-1/√3) \n=> 20√3 = h (3-1) \n=> h=10√3.\n" }, { "code": null, "e": 5010, "s": 4814, "text": "Q 4 - The angles of elevation of the tops of two vertical towers as seen from the middle point of the lines joining the foot of the towers are 45° & 60°.The ratio of the height of the towers is" }, { "code": null, "e": 5019, "s": 5010, "text": "A - √3:2" }, { "code": null, "e": 5028, "s": 5019, "text": "B - √3:1" }, { "code": null, "e": 5037, "s": 5028, "text": "C - 2:√3" }, { "code": null, "e": 5045, "s": 5037, "text": "D - 2:1" }, { "code": null, "e": 5056, "s": 5045, "text": "Answer - B" }, { "code": null, "e": 5068, "s": 5056, "text": "Explanation" }, { "code": null, "e": 5143, "s": 5068, "text": "Tan(60)=h1/AB\n=> h1=√3AB\nTan(45)=h1/BC\n=> h2=BC\nh1/ h2=√3/1\n=> h1:h2=√3:1\n" }, { "code": null, "e": 5314, "s": 5143, "text": "Q 5 - The heights of two towers are 90 meters and 45 meters. The line joining their tops make an angle 450 with the horizontal then the distance between the two towers is" }, { "code": null, "e": 5325, "s": 5314, "text": "A - 22.5 m" }, { "code": null, "e": 5334, "s": 5325, "text": "B - 45 m" }, { "code": null, "e": 5343, "s": 5334, "text": "C - 60 m" }, { "code": null, "e": 5352, "s": 5343, "text": "D - 30 m" }, { "code": null, "e": 5363, "s": 5352, "text": "Answer - B" }, { "code": null, "e": 5375, "s": 5363, "text": "Explanation" }, { "code": null, "e": 5492, "s": 5375, "text": "Let the distance between the towers be X \nFrom the right angled triangle CFD \nTan(45)= (90-45)/X \n=> x=45 meters\n" }, { "code": null, "e": 5663, "s": 5492, "text": "Q 6 - From a point P on a level ground, the angle of elevation of the top tower is 60°. If the tower is 180 m high, the distance of point P from the foot of the tower is" }, { "code": null, "e": 5672, "s": 5663, "text": "A - 60√3" }, { "code": null, "e": 5681, "s": 5672, "text": "B - 40√3" }, { "code": null, "e": 5690, "s": 5681, "text": "C - 30√3" }, { "code": null, "e": 5699, "s": 5690, "text": "D - 20√3" }, { "code": null, "e": 5710, "s": 5699, "text": "Answer - A" }, { "code": null, "e": 5722, "s": 5710, "text": "Explanation" }, { "code": null, "e": 5796, "s": 5722, "text": "From ∠APB = 60° and AB = 180 m.\nAB/AP= tan 60° =√3\nAP=AB/√3 =180/√3=60√3\n" }, { "code": null, "e": 6003, "s": 5796, "text": "Q 7 - The Top of a 25 meter high tower makes an angle of elevation of 450 with the bottom of an electric pole and angle of elevation of 30 degree with the top of pole. Find the height of the electric pole." }, { "code": null, "e": 6012, "s": 6003, "text": "A - 25√3" }, { "code": null, "e": 6030, "s": 6012, "text": "B - 25((√3-1)/√3)" }, { "code": null, "e": 6040, "s": 6030, "text": "C - 25/√3" }, { "code": null, "e": 6058, "s": 6040, "text": "D - 25((1-√3)/√3)" }, { "code": null, "e": 6069, "s": 6058, "text": "Answer - B" }, { "code": null, "e": 6081, "s": 6069, "text": "Explanation" }, { "code": null, "e": 6261, "s": 6081, "text": "Let AB be the tower and CD be the electric pole. \nFrom the figure CA = DE\n=> 25/(Tan(45))=(25-h)/(Tan(30))\n=> 25 Tan(30) = 25-h\n=> h=25-25Tan(30)\n=25(1- Tan(30)) \n=25((√3-1)/√3)\n" }, { "code": null, "e": 6414, "s": 6261, "text": "Q 8 - An observer 1.4 m tall is 10√3 away from a tower. The angle of elevation from his eye to the top of the tower is 60°. The heights of the tower is" }, { "code": null, "e": 6425, "s": 6414, "text": "A - 12.4 m" }, { "code": null, "e": 6435, "s": 6425, "text": "B - 6.2 m" }, { "code": null, "e": 6448, "s": 6435, "text": "C - 11.4√3 m" }, { "code": null, "e": 6459, "s": 6448, "text": "D - 11.4 m" }, { "code": null, "e": 6470, "s": 6459, "text": "Answer - D" }, { "code": null, "e": 6482, "s": 6470, "text": "Explanation" }, { "code": null, "e": 6627, "s": 6482, "text": "Let AB be the observer and CD be the tower.\nThen, CE = AB = 1.4 m,\n BE = AC = 10v3 m.\nDE/BE=Tan (30) =1/√3\nDE=10√3/√3=10\nCD=CE+DE=1.4+10=11.4 m\n" }, { "code": null, "e": 6969, "s": 6627, "text": "Q 9 - A man is watching form the top of the tower a boat speeding away from the tower. The boat makes the angle of depression of 60° with the man's eye when at a distance of 75 meters from the tower. After 10 seconds the angle of depression becomes 45°. What is the approximate speed of the boat, assuming that it is running in still water?" }, { "code": null, "e": 6981, "s": 6969, "text": "A - 54 kmph" }, { "code": null, "e": 6993, "s": 6981, "text": "B - 64 kmph" }, { "code": null, "e": 7005, "s": 6993, "text": "C - 24 kmph" }, { "code": null, "e": 7019, "s": 7005, "text": "D - 19.8 kmph" }, { "code": null, "e": 7030, "s": 7019, "text": "Answer - D" }, { "code": null, "e": 7042, "s": 7030, "text": "Explanation" }, { "code": null, "e": 7253, "s": 7042, "text": "Let AB be the tower and C and D be the positions of the boat.\nDistance travelled by boat = CD\nFrom the figure 75tan(60)=(75+CD)tan(45)\n=>75√3 = 75+CD\n=>CD =55 m\nSpeed = distance/time=55/10\n=5.5 m/sec=19.8 kmph\n" }, { "code": null, "e": 7454, "s": 7253, "text": "Q 10 - The horizontal distance between two towers is 90 m. The angular depression of the top of the first as seen from the top of the second which is 180 m high is 450.Then the height of the first is" }, { "code": null, "e": 7465, "s": 7454, "text": "A - 90√3 m" }, { "code": null, "e": 7474, "s": 7465, "text": "B - 45 m" }, { "code": null, "e": 7483, "s": 7474, "text": "C - 90 m" }, { "code": null, "e": 7493, "s": 7483, "text": "D - 150 m" }, { "code": null, "e": 7504, "s": 7493, "text": "Answer - C" }, { "code": null, "e": 7516, "s": 7504, "text": "Explanation" }, { "code": null, "e": 7552, "s": 7516, "text": "=>(180-h)/90 = Tan(45)\n=> h =90 m\t\n" }, { "code": null, "e": 7588, "s": 7552, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 7606, "s": 7588, "text": " Programming Line" }, { "code": null, "e": 7613, "s": 7606, "text": " Print" }, { "code": null, "e": 7624, "s": 7613, "text": " Add Notes" } ]
Deep Learning with Keras - Preparing Data
Before we feed the data to our network, it must be converted into the format required by the network. This is called preparing data for the network. It generally consists of converting a multi-dimensional input to a single-dimension vector and normalizing the data points. The images in our dataset consist of 28 x 28 pixels. This must be converted into a single dimensional vector of size 28 * 28 = 784 for feeding it into our network. We do so by calling the reshape method on the vector. X_train = X_train.reshape(60000, 784) X_test = X_test.reshape(10000, 784) Now, our training vector will consist of 60000 data points, each consisting of a single dimension vector of size 784. Similarly, our test vector will consist of 10000 data points of a single-dimension vector of size 784. The data that the input vector contains currently has a discrete value between 0 and 255 - the gray scale levels. Normalizing these pixel values between 0 and 1 helps in speeding up the training. As we are going to use stochastic gradient descent, normalizing data will also help in reducing the chance of getting stuck in local optima. To normalize the data, we represent it as float type and divide it by 255 as shown in the following code snippet − X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 Let us now look at how the normalized data looks like. To view the normalized data, we will call the histogram function as shown here − plot.hist(X_train[0]) plot.title("Digit: {}".format(y_train[0])) Here, we plot the histogram of the first element of the X_train vector. We also print the digit represented by this data point. The output of running the above code is shown here − You will notice a thick density of points having value close to zero. These are the black dot points in the image, which obviously is the major portion of the image. The rest of the gray scale points, which are close to white color, represent the digit. You may check out the distribution of pixels for another digit. The code below prints the histogram of a digit at index of 2 in the training dataset. plot.hist(X_train[2]) plot.title("Digit: {}".format(y_train[2]) The output of running the above code is shown below − Comparing the above two figures, you will notice that the distribution of the white pixels in two images differ indicating a representation of a different digit - “5” and “4” in the above two pictures. Next, we will examine the distribution of data in our full training dataset. Before we train our machine learning model on our dataset, we should know the distribution of unique digits in our dataset. Our images represent 10 distinct digits ranging from 0 to 9. We would like to know the number of digits 0, 1, etc., in our dataset. We can get this information by using the unique method of Numpy. Use the following command to print the number of unique values and the number of occurrences of each one print(np.unique(y_train, return_counts=True)) When you run the above command, you will see the following output − (array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint8), array([5923, 6742, 5958, 6131, 5842, 5421, 5918, 6265, 5851, 5949])) It shows that there are 10 distinct values — 0 through 9. There are 5923 occurrences of digit 0, 6742 occurrences of digit 1, and so on. The screenshot of the output is shown here − As a final step in data preparation, we need to encode our data. We have ten categories in our dataset. We will thus encode our output in these ten categories using one-hot encoding. We use to_categorial method of Numpy utilities to perform encoding. After the output data is encoded, each data point would be converted into a single dimensional vector of size 10. For example, digit 5 will now be represented as [0,0,0,0,0,1,0,0,0,0]. Encode the data using the following piece of code − n_classes = 10 Y_train = np_utils.to_categorical(y_train, n_classes) You may check out the result of encoding by printing the first 5 elements of the categorized Y_train vector. Use the following code to print the first 5 vectors − for i in range(5): print (Y_train[i]) You will see the following output − [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.] [1. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.] [0. 1. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 1.] The first element represents digit 5, the second represents digit 0, and so on. Finally, you will have to categorize the test data too, which is done using the following statement − Y_test = np_utils.to_categorical(y_test, n_classes) At this stage, your data is fully prepared for feeding into the network. Next, comes the most important part and that is training our network model. 87 Lectures 11 hours Abhilash Nelson 106 Lectures 13.5 hours Abhilash Nelson 28 Lectures 4 hours Abhilash Nelson 58 Lectures 8 hours Soumyadeep Dey 59 Lectures 2.5 hours Mike West 128 Lectures 5.5 hours TELCOMA Global Print Add Notes Bookmark this page
[ { "code": null, "e": 2232, "s": 1959, "text": "Before we feed the data to our network, it must be converted into the format required by the network. This is called preparing data for the network. It generally consists of converting a multi-dimensional input to a single-dimension vector and normalizing the data points." }, { "code": null, "e": 2450, "s": 2232, "text": "The images in our dataset consist of 28 x 28 pixels. This must be converted into a single dimensional vector of size 28 * 28 = 784 for feeding it into our network. We do so by calling the reshape method on the vector." }, { "code": null, "e": 2524, "s": 2450, "text": "X_train = X_train.reshape(60000, 784)\nX_test = X_test.reshape(10000, 784)" }, { "code": null, "e": 2745, "s": 2524, "text": "Now, our training vector will consist of 60000 data points, each consisting of a single dimension vector of size 784. Similarly, our test vector will consist of 10000 data points of a single-dimension vector of size 784." }, { "code": null, "e": 3082, "s": 2745, "text": "The data that the input vector contains currently has a discrete value between 0 and 255 - the gray scale levels. Normalizing these pixel values between 0 and 1 helps in speeding up the training. As we are going to use stochastic gradient descent, normalizing data will also help in reducing the chance of getting stuck in local optima." }, { "code": null, "e": 3197, "s": 3082, "text": "To normalize the data, we represent it as float type and divide it by 255 as shown in the following code snippet −" }, { "code": null, "e": 3296, "s": 3197, "text": "X_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\nX_train /= 255\nX_test /= 255" }, { "code": null, "e": 3351, "s": 3296, "text": "Let us now look at how the normalized data looks like." }, { "code": null, "e": 3432, "s": 3351, "text": "To view the normalized data, we will call the histogram function as shown here −" }, { "code": null, "e": 3497, "s": 3432, "text": "plot.hist(X_train[0])\nplot.title(\"Digit: {}\".format(y_train[0]))" }, { "code": null, "e": 3678, "s": 3497, "text": "Here, we plot the histogram of the first element of the X_train vector. We also print the digit represented by this data point. The output of running the above code is shown here −" }, { "code": null, "e": 4082, "s": 3678, "text": "You will notice a thick density of points having value close to zero. These are the black dot points in the image, which obviously is the major portion of the image. The rest of the gray scale points, which are close to white color, represent the digit. You may check out the distribution of pixels for another digit. The code below prints the histogram of a digit at index of 2 in the training dataset." }, { "code": null, "e": 4146, "s": 4082, "text": "plot.hist(X_train[2])\nplot.title(\"Digit: {}\".format(y_train[2])" }, { "code": null, "e": 4200, "s": 4146, "text": "The output of running the above code is shown below −" }, { "code": null, "e": 4402, "s": 4200, "text": "Comparing the above two figures, you will notice that the distribution of the white pixels in two images differ indicating a representation of a different digit - “5” and “4” in the above two pictures." }, { "code": null, "e": 4479, "s": 4402, "text": "Next, we will examine the distribution of data in our full training dataset." }, { "code": null, "e": 4800, "s": 4479, "text": "Before we train our machine learning model on our dataset, we should know the distribution of unique digits in our dataset. Our images represent 10 distinct digits ranging from 0 to 9. We would like to know the number of digits 0, 1, etc., in our dataset. We can get this information by using the unique method of Numpy." }, { "code": null, "e": 4905, "s": 4800, "text": "Use the following command to print the number of unique values and the number of occurrences of each one" }, { "code": null, "e": 4951, "s": 4905, "text": "print(np.unique(y_train, return_counts=True))" }, { "code": null, "e": 5019, "s": 4951, "text": "When you run the above command, you will see the following output −" }, { "code": null, "e": 5141, "s": 5019, "text": "(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint8), array([5923, 6742, 5958, 6131, 5842, 5421, 5918, 6265, 5851, 5949]))" }, { "code": null, "e": 5323, "s": 5141, "text": "It shows that there are 10 distinct values — 0 through 9. There are 5923 occurrences of digit 0, 6742 occurrences of digit 1, and so on. The screenshot of the output is shown here −" }, { "code": null, "e": 5388, "s": 5323, "text": "As a final step in data preparation, we need to encode our data." }, { "code": null, "e": 5759, "s": 5388, "text": "We have ten categories in our dataset. We will thus encode our output in these ten categories using one-hot encoding. We use to_categorial method of Numpy utilities to perform encoding. After the output data is encoded, each data point would be converted into a single dimensional vector of size 10. For example, digit 5 will now be represented as [0,0,0,0,0,1,0,0,0,0]." }, { "code": null, "e": 5811, "s": 5759, "text": "Encode the data using the following piece of code −" }, { "code": null, "e": 5880, "s": 5811, "text": "n_classes = 10\nY_train = np_utils.to_categorical(y_train, n_classes)" }, { "code": null, "e": 5989, "s": 5880, "text": "You may check out the result of encoding by printing the first 5 elements of the categorized Y_train vector." }, { "code": null, "e": 6043, "s": 5989, "text": "Use the following code to print the first 5 vectors −" }, { "code": null, "e": 6084, "s": 6043, "text": "for i in range(5):\n print (Y_train[i])" }, { "code": null, "e": 6120, "s": 6084, "text": "You will see the following output −" }, { "code": null, "e": 6281, "s": 6120, "text": "[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]\n[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]\n[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]\n[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n" }, { "code": null, "e": 6361, "s": 6281, "text": "The first element represents digit 5, the second represents digit 0, and so on." }, { "code": null, "e": 6463, "s": 6361, "text": "Finally, you will have to categorize the test data too, which is done using the following statement −" }, { "code": null, "e": 6515, "s": 6463, "text": "Y_test = np_utils.to_categorical(y_test, n_classes)" }, { "code": null, "e": 6588, "s": 6515, "text": "At this stage, your data is fully prepared for feeding into the network." }, { "code": null, "e": 6664, "s": 6588, "text": "Next, comes the most important part and that is training our network model." }, { "code": null, "e": 6698, "s": 6664, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 6715, "s": 6698, "text": " Abhilash Nelson" }, { "code": null, "e": 6752, "s": 6715, "text": "\n 106 Lectures \n 13.5 hours \n" }, { "code": null, "e": 6769, "s": 6752, "text": " Abhilash Nelson" }, { "code": null, "e": 6802, "s": 6769, "text": "\n 28 Lectures \n 4 hours \n" }, { "code": null, "e": 6819, "s": 6802, "text": " Abhilash Nelson" }, { "code": null, "e": 6852, "s": 6819, "text": "\n 58 Lectures \n 8 hours \n" }, { "code": null, "e": 6868, "s": 6852, "text": " Soumyadeep Dey" }, { "code": null, "e": 6903, "s": 6868, "text": "\n 59 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6914, "s": 6903, "text": " Mike West" }, { "code": null, "e": 6950, "s": 6914, "text": "\n 128 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6966, "s": 6950, "text": " TELCOMA Global" }, { "code": null, "e": 6973, "s": 6966, "text": " Print" }, { "code": null, "e": 6984, "s": 6973, "text": " Add Notes" } ]
Computer Programming - Variables
Variables are the names you give to computer memory locations which are used to store values in a computer program. For example, assume you want to store two values 10 and 20 in your program and at a later stage, you want to use these two values. Let's see how you will do it. Here are the following three simple steps − Create variables with appropriate names. Store your values in those two variables. Retrieve and use the stored values from the variables. Creating variables is also called declaring variables in C programming. Different programming languages have different ways of creating variables inside a program. For example, C programming has the following simple way of creating variables − #include <stdio.h> int main() { int a; int b; } The above program creates two variables to reserve two memory locations with names a and b. We created these variables using int keyword to specify variable data type which means we want to store integer values in these two variables. Similarly, you can create variables to store long, float, char or any other data type. For example − /* variable to store long value */ long a; /* variable to store float value */ float b; You can create variables of similar type by putting them in a single line but separated by comma as follows − #include <stdio.h> int main() { int a, b; } Listed below are the key points about variables that you need to keep in mind − A variable name can hold a single type of value. For example, if variable a has been defined int type, then it can store only integer. A variable name can hold a single type of value. For example, if variable a has been defined int type, then it can store only integer. C programming language requires a variable creation, i.e., declaration before its usage in your program. You cannot use a variable name in your program without creating it, though programming language like Python allows you to use a variable name without creating it. C programming language requires a variable creation, i.e., declaration before its usage in your program. You cannot use a variable name in your program without creating it, though programming language like Python allows you to use a variable name without creating it. You can use a variable name only once inside your program. For example, if a variable a has been defined to store an integer value, then you cannot define a again to store any other type of value. You can use a variable name only once inside your program. For example, if a variable a has been defined to store an integer value, then you cannot define a again to store any other type of value. There are programming languages like Python, PHP, Perl, etc., which do not want you to specify data type at the time of creating variables. So you can store integer, float, or long without specifying their data type. There are programming languages like Python, PHP, Perl, etc., which do not want you to specify data type at the time of creating variables. So you can store integer, float, or long without specifying their data type. You can give any name to a variable like age, sex, salary, year1990 or anything else you like to give, but most of the programming languages allow to use only limited characters in their variables names. For now, we will suggest to use only a....z, A....Z, 0....9 in your variable names and start their names using alphabets only instead of digits. You can give any name to a variable like age, sex, salary, year1990 or anything else you like to give, but most of the programming languages allow to use only limited characters in their variables names. For now, we will suggest to use only a....z, A....Z, 0....9 in your variable names and start their names using alphabets only instead of digits. Almost none of the programming languages allow to start their variable names with a digit, so 1990year will not be a valid variable name whereas year1990 or ye1990ar are valid variable names. Almost none of the programming languages allow to start their variable names with a digit, so 1990year will not be a valid variable name whereas year1990 or ye1990ar are valid variable names. Every programming language provides more rules related to variables and you will learn them when you will go in further detail of that programming language. You have seen how we created variables in the previous section. Now, let's store some values in those variables − #include <stdio.h> int main() { int a; int b; a = 10; b = 20; } The above program has two additional statements where we are storing 10 in variable a and 20 is being stored in variable b. Almost all the programming languages have similar way of storing values in variable where we keep variable name in the left hand side of an equal sign = and whatever value we want to store in the variable, we keep that value in the right hand side. Now, we have completed two steps, first we created two variables and then we stored required values in those variables. Now variable a has value 10 and variable b has value 20. In other words we can say, when above program is executed, the memory location named a will hold 10 and memory location b will hold 20. If we do not use the stored values in the variables, then there is no point in creating variables and storing values in them. We know that the above program has two variables a and b and they store the values 10 and 20, respectively. So let's try to print the values stored in these two variables. Following is a C program, which prints the values stored in its variables − #include <stdio.h> int main() { int a; int b; a = 10; b = 20; printf( "Value of a = %d\n", a ); printf( "Value of b = %d\n", b ); } When the above program is executed, it produces the following result − Value of a = 10 Value of b = 20 You must have seen printf() function in the previous chapter where we had used it to print "Hello, World!". This time, we are using it to print the values of variables. We are making use of %d, which will be replaced with the values of the given variable in printf() statements. We can print both the values using a single printf() statement as follows − #include <stdio.h> int main() { int a; int b; a = 10; b = 20; printf( "Value of a = %d and value of b = %d\n", a, b ); } When the above program is executed, it produces the following result − Value of a = 10 and value of b = 20 If you want to use float variable in C programming, then you will have to use %f instead of %d, and if you want to print a character value, then you will have to use %c. Similarly, different data types can be printed using different % and characters. Following is the equivalent program written in Java programming language. This program will create two variables a and b and very similar to C programming, it will assign 10 and 20 in these variables and finally print the values of the two variables in two ways − public class DemoJava { public static void main(String []args) { int a; int b; a = 10; b = 20; System.out.println("Value of a = " + a); System.out.println("Value of b = " + b); System.out.println("Value of a = " + a + " and value of b = " + b); } } When the above program is executed, it produces the following result − Value of a = 10 Value of b = 20 Value of a = 10 and value of b = 20 Following is the equivalent program written in Python. This program will create two variables a and b and at the same time, assign 10 and 20 in those variables. Python does not want you to specify the data type at the time of variable creation and there is no need to create variables in advance. a = 10 b = 20 print "Value of a = ", a print "Value of b = ", b print "Value of a = ", a, " and value of b = ", b When the above program is executed, it produces the following result − Value of a = 10 Value of b = 20 Value of a = 10 and value of b = 20 You can use the following syntax in C and Java programming to declare variables and assign values at the same time − #include <stdio.h> int main() { int a = 10; int b = 20; printf( "Value of a = %d and value of b = %d\n", a, b ); } When the above program is executed, it produces the following result − Value of a = 10 and value of b = 20 107 Lectures 13.5 hours Arnab Chakraborty 106 Lectures 8 hours Arnab Chakraborty 99 Lectures 6 hours Arnab Chakraborty 46 Lectures 2.5 hours Shweta 70 Lectures 9 hours Abhilash Nelson 52 Lectures 7 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2256, "s": 2140, "text": "Variables are the names you give to computer memory locations which are used to store values in a computer program." }, { "code": null, "e": 2461, "s": 2256, "text": "For example, assume you want to store two values 10 and 20 in your program and at a later stage, you want to use these two values. Let's see how you will do it. Here are the following three simple steps −" }, { "code": null, "e": 2502, "s": 2461, "text": "Create variables with appropriate names." }, { "code": null, "e": 2544, "s": 2502, "text": "Store your values in those two variables." }, { "code": null, "e": 2599, "s": 2544, "text": "Retrieve and use the stored values from the variables." }, { "code": null, "e": 2843, "s": 2599, "text": "Creating variables is also called declaring variables in C programming. Different programming languages have different ways of creating variables inside a program. For example, C programming has the following simple way of creating variables −" }, { "code": null, "e": 2898, "s": 2843, "text": "#include <stdio.h>\n\nint main() {\n int a;\n int b;\n}" }, { "code": null, "e": 3234, "s": 2898, "text": "The above program creates two variables to reserve two memory locations with names a and b. We created these variables using int keyword to specify variable data type which means we want to store integer values in these two variables. Similarly, you can create variables to store long, float, char or any other data type. For example −" }, { "code": null, "e": 3323, "s": 3234, "text": "/* variable to store long value */\nlong a;\n\n/* variable to store float value */\nfloat b;" }, { "code": null, "e": 3433, "s": 3323, "text": "You can create variables of similar type by putting them in a single line but separated by comma as follows −" }, { "code": null, "e": 3481, "s": 3433, "text": "#include <stdio.h>\n\nint main() {\n int a, b;\n}" }, { "code": null, "e": 3561, "s": 3481, "text": "Listed below are the key points about variables that you need to keep in mind −" }, { "code": null, "e": 3696, "s": 3561, "text": "A variable name can hold a single type of value. For example, if variable a has been defined int type, then it can store only integer." }, { "code": null, "e": 3831, "s": 3696, "text": "A variable name can hold a single type of value. For example, if variable a has been defined int type, then it can store only integer." }, { "code": null, "e": 4099, "s": 3831, "text": "C programming language requires a variable creation, i.e., declaration before its usage in your program. You cannot use a variable name in your program without creating it, though programming language like Python allows you to use a variable name without creating it." }, { "code": null, "e": 4367, "s": 4099, "text": "C programming language requires a variable creation, i.e., declaration before its usage in your program. You cannot use a variable name in your program without creating it, though programming language like Python allows you to use a variable name without creating it." }, { "code": null, "e": 4564, "s": 4367, "text": "You can use a variable name only once inside your program. For example, if a variable a has been defined to store an integer value, then you cannot define a again to store any other type of value." }, { "code": null, "e": 4761, "s": 4564, "text": "You can use a variable name only once inside your program. For example, if a variable a has been defined to store an integer value, then you cannot define a again to store any other type of value." }, { "code": null, "e": 4978, "s": 4761, "text": "There are programming languages like Python, PHP, Perl, etc., which do not want you to specify data type at the time of creating variables. So you can store integer, float, or long without specifying their data type." }, { "code": null, "e": 5195, "s": 4978, "text": "There are programming languages like Python, PHP, Perl, etc., which do not want you to specify data type at the time of creating variables. So you can store integer, float, or long without specifying their data type." }, { "code": null, "e": 5544, "s": 5195, "text": "You can give any name to a variable like age, sex, salary, year1990 or anything else you like to give, but most of the programming languages allow to use only limited characters in their variables names. For now, we will suggest to use only a....z, A....Z, 0....9 in your variable names and start their names using alphabets only instead of digits." }, { "code": null, "e": 5893, "s": 5544, "text": "You can give any name to a variable like age, sex, salary, year1990 or anything else you like to give, but most of the programming languages allow to use only limited characters in their variables names. For now, we will suggest to use only a....z, A....Z, 0....9 in your variable names and start their names using alphabets only instead of digits." }, { "code": null, "e": 6085, "s": 5893, "text": "Almost none of the programming languages allow to start their variable names with a digit, so 1990year will not be a valid variable name whereas year1990 or ye1990ar are valid variable names." }, { "code": null, "e": 6277, "s": 6085, "text": "Almost none of the programming languages allow to start their variable names with a digit, so 1990year will not be a valid variable name whereas year1990 or ye1990ar are valid variable names." }, { "code": null, "e": 6434, "s": 6277, "text": "Every programming language provides more rules related to variables and you will learn them when you will go in further detail of that programming language." }, { "code": null, "e": 6548, "s": 6434, "text": "You have seen how we created variables in the previous section. Now, let's store some values in those variables −" }, { "code": null, "e": 6629, "s": 6548, "text": "#include <stdio.h>\n\nint main() {\n int a;\n int b;\n \n a = 10;\n b = 20;\n}" }, { "code": null, "e": 7002, "s": 6629, "text": "The above program has two additional statements where we are storing 10 in variable a and 20 is being stored in variable b. Almost all the programming languages have similar way of storing values in variable where we keep variable name in the left hand side of an equal sign = and whatever value we want to store in the variable, we keep that value in the right hand side." }, { "code": null, "e": 7315, "s": 7002, "text": "Now, we have completed two steps, first we created two variables and then we stored required values in those variables. Now variable a has value 10 and variable b has value 20. In other words we can say, when above program is executed, the memory location named a will hold 10 and memory location b will hold 20." }, { "code": null, "e": 7689, "s": 7315, "text": "If we do not use the stored values in the variables, then there is no point in creating variables and storing values in them. We know that the above program has two variables a and b and they store the values 10 and 20, respectively. So let's try to print the values stored in these two variables. Following is a C program, which prints the values stored in its variables −" }, { "code": null, "e": 7848, "s": 7689, "text": "#include <stdio.h>\n\nint main() {\n int a;\n int b;\n \n a = 10;\n b = 20;\n \n printf( \"Value of a = %d\\n\", a );\n printf( \"Value of b = %d\\n\", b );\n}" }, { "code": null, "e": 7919, "s": 7848, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 7952, "s": 7919, "text": "Value of a = 10\nValue of b = 20\n" }, { "code": null, "e": 8307, "s": 7952, "text": "You must have seen printf() function in the previous chapter where we had used it to print \"Hello, World!\". This time, we are using it to print the values of variables. We are making use of %d, which will be replaced with the values of the given variable in printf() statements. We can print both the values using a single printf() statement as follows −" }, { "code": null, "e": 8452, "s": 8307, "text": "#include <stdio.h>\n\nint main() {\n int a;\n int b;\n \n a = 10;\n b = 20;\n \n printf( \"Value of a = %d and value of b = %d\\n\", a, b );\n}" }, { "code": null, "e": 8523, "s": 8452, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 8560, "s": 8523, "text": "Value of a = 10 and value of b = 20\n" }, { "code": null, "e": 8811, "s": 8560, "text": "If you want to use float variable in C programming, then you will have to use %f instead of %d, and if you want to print a character value, then you will have to use %c. Similarly, different data types can be printed using different % and characters." }, { "code": null, "e": 9075, "s": 8811, "text": "Following is the equivalent program written in Java programming language. This program will create two variables a and b and very similar to C programming, it will assign 10 and 20 in these variables and finally print the values of the two variables in two ways −" }, { "code": null, "e": 9385, "s": 9075, "text": "public class DemoJava {\n public static void main(String []args) {\n int a;\n int b;\n \n a = 10;\n b = 20;\n \n System.out.println(\"Value of a = \" + a);\n System.out.println(\"Value of b = \" + b);\n System.out.println(\"Value of a = \" + a + \" and value of b = \" + b); \n }\n}" }, { "code": null, "e": 9456, "s": 9385, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 9525, "s": 9456, "text": "Value of a = 10\nValue of b = 20\nValue of a = 10 and value of b = 20\n" }, { "code": null, "e": 9686, "s": 9525, "text": "Following is the equivalent program written in Python. This program will create two variables a and b and at the same time, assign 10 and 20 in those variables." }, { "code": null, "e": 9822, "s": 9686, "text": "Python does not want you to specify the data type at the time of variable creation and there is no need to create variables in advance." }, { "code": null, "e": 9940, "s": 9822, "text": "a = 10\nb = 20\n \nprint \"Value of a = \", a\nprint \"Value of b = \", b\nprint \"Value of a = \", a, \" and value of b = \", b" }, { "code": null, "e": 10011, "s": 9940, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 10085, "s": 10011, "text": "Value of a = 10\nValue of b = 20\nValue of a = 10 and value of b = 20\n" }, { "code": null, "e": 10202, "s": 10085, "text": "You can use the following syntax in C and Java programming to declare variables and assign values at the same time −" }, { "code": null, "e": 10331, "s": 10202, "text": "#include <stdio.h>\n\nint main() {\n int a = 10;\n int b = 20;\n \n printf( \"Value of a = %d and value of b = %d\\n\", a, b );\n}" }, { "code": null, "e": 10402, "s": 10331, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 10439, "s": 10402, "text": "Value of a = 10 and value of b = 20\n" }, { "code": null, "e": 10476, "s": 10439, "text": "\n 107 Lectures \n 13.5 hours \n" }, { "code": null, "e": 10495, "s": 10476, "text": " Arnab Chakraborty" }, { "code": null, "e": 10529, "s": 10495, "text": "\n 106 Lectures \n 8 hours \n" }, { "code": null, "e": 10548, "s": 10529, "text": " Arnab Chakraborty" }, { "code": null, "e": 10581, "s": 10548, "text": "\n 99 Lectures \n 6 hours \n" }, { "code": null, "e": 10600, "s": 10581, "text": " Arnab Chakraborty" }, { "code": null, "e": 10635, "s": 10600, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10643, "s": 10635, "text": " Shweta" }, { "code": null, "e": 10676, "s": 10643, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 10693, "s": 10676, "text": " Abhilash Nelson" }, { "code": null, "e": 10726, "s": 10693, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 10748, "s": 10726, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 10755, "s": 10748, "text": " Print" }, { "code": null, "e": 10766, "s": 10755, "text": " Add Notes" } ]
MySQL query to select top 10 records?
To select top 10 records, use LIMIT in MySQL. Let us first create a table − mysql> create table DemoTable -> ( -> PageNumber text -> ); Query OK, 0 rows affected (2.50 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('Page-1'); Query OK, 1 row affected (0.46 sec) mysql> insert into DemoTable values('Page-2'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Page-3'); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable values('Page-4'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('Page-5'); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable values('Page-6'); Query OK, 1 row affected (1.12 sec) mysql> insert into DemoTable values('Page-7'); Query OK, 1 row affected (1.21 sec) mysql> insert into DemoTable values('Page-8'); Query OK, 1 row affected (1.15 sec) mysql> insert into DemoTable values('Page-9'); Query OK, 1 row affected (0.89 sec) mysql> insert into DemoTable values('Page-10'); Query OK, 1 row affected (1.20 sec) mysql> insert into DemoTable values('Page-11'); Query OK, 1 row affected (0.86 sec) mysql> insert into DemoTable values('Page-12'); Query OK, 1 row affected (0.39 sec) mysql> insert into DemoTable values('Page-13'); Query OK, 1 row affected (0.39 sec) mysql> insert into DemoTable values('Page-14'); Query OK, 1 row affected (0.47 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +------------+ | PageNumber | +------------+ | Page-1 | | Page-2 | | Page-3 | | Page-4 | | Page-5 | | Page-6 | | Page-7 | | Page-8 | | Page-9 | | Page-10 | | Page-11 | | Page-12 | | Page-13 | | Page-14 | +------------+ 14 rows in set (0.00 sec) Following is the query to select top 10 records − mysql> select *from DemoTable limit 0,10; This will produce the following output − +------------+ | PageNumber | +------------+ | Page-1 | | Page-2 | | Page-3 | | Page-4 | | Page-5 | | Page-6 | | Page-7 | | Page-8 | | Page-9 | | Page-10 | +------------+ 10 rows in set (0.00 sec)
[ { "code": null, "e": 1138, "s": 1062, "text": "To select top 10 records, use LIMIT in MySQL. Let us first create a table −" }, { "code": null, "e": 1235, "s": 1138, "text": "mysql> create table DemoTable\n-> (\n-> PageNumber text\n-> );\nQuery OK, 0 rows affected (2.50 sec)" }, { "code": null, "e": 1291, "s": 1235, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2471, "s": 1291, "text": "mysql> insert into DemoTable values('Page-1');\nQuery OK, 1 row affected (0.46 sec)\n\nmysql> insert into DemoTable values('Page-2');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into DemoTable values('Page-3');\nQuery OK, 1 row affected (0.27 sec)\n\nmysql> insert into DemoTable values('Page-4');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DemoTable values('Page-5');\nQuery OK, 1 row affected (0.27 sec)\n\nmysql> insert into DemoTable values('Page-6');\nQuery OK, 1 row affected (1.12 sec)\n\nmysql> insert into DemoTable values('Page-7');\nQuery OK, 1 row affected (1.21 sec)\n\nmysql> insert into DemoTable values('Page-8');\nQuery OK, 1 row affected (1.15 sec)\n\nmysql> insert into DemoTable values('Page-9');\nQuery OK, 1 row affected (0.89 sec)\n\nmysql> insert into DemoTable values('Page-10');\nQuery OK, 1 row affected (1.20 sec)\n\nmysql> insert into DemoTable values('Page-11');\nQuery OK, 1 row affected (0.86 sec)\n\nmysql> insert into DemoTable values('Page-12');\nQuery OK, 1 row affected (0.39 sec)\n\nmysql> insert into DemoTable values('Page-13');\nQuery OK, 1 row affected (0.39 sec)\n\nmysql> insert into DemoTable values('Page-14');\nQuery OK, 1 row affected (0.47 sec)" }, { "code": null, "e": 2531, "s": 2471, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2562, "s": 2531, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2603, "s": 2562, "text": "This will produce the following output −" }, { "code": null, "e": 2899, "s": 2603, "text": "+------------+\n| PageNumber |\n+------------+\n| Page-1 |\n| Page-2 |\n| Page-3 |\n| Page-4 |\n| Page-5 |\n| Page-6 |\n| Page-7 |\n| Page-8 |\n| Page-9 |\n| Page-10 |\n| Page-11 |\n| Page-12 |\n| Page-13 |\n| Page-14 |\n+------------+\n14 rows in set (0.00 sec)" }, { "code": null, "e": 2949, "s": 2899, "text": "Following is the query to select top 10 records −" }, { "code": null, "e": 2991, "s": 2949, "text": "mysql> select *from DemoTable limit 0,10;" }, { "code": null, "e": 3032, "s": 2991, "text": "This will produce the following output −" }, { "code": null, "e": 3268, "s": 3032, "text": "+------------+\n| PageNumber |\n+------------+\n| Page-1 |\n| Page-2 |\n| Page-3 |\n| Page-4 |\n| Page-5 |\n| Page-6 |\n| Page-7 |\n| Page-8 |\n| Page-9 |\n| Page-10 |\n+------------+\n10 rows in set (0.00 sec)" } ]
Interacting With Ethereum Smart Contract Using Web3js - GeeksforGeeks
14 Oct, 2020 Ethereum is a cryptocurrency platform in the market just like Bitcoin. It is an open-source & decentralized blockchain featuring working on smart contracts. It has its own cryptocurrency known as ether. The smart contracts in Ethereum are written in solidity. TestRPC The Ethereum TestRPC is like a manual emulator for blockchain. It provides blockchain interaction without running on an actual Ethereum node. It also provides all the features required for testing of your blockchain. It is based on Node.js. Web3.js Web3.js is an Ethereum-based JavaScript API that allows us to interact with a local or remote Ethereum node using different servers such as HTTP. It interacts with the Ethereum blockchain and can retrieve data from the blockchain as required by the developer. This article describes how to interact with your Ethereum smart contract using Web3.js and TestRPC. It is recommended that you go through on How to Work on Remix-IDE before proceeding further. Before we proceed to the steps, install TestRPC and Web3JS as follows – Step 1: Open the console or command line and run the following commands to check if node and npm are installed. $ node -v $ npm -v If the above command goes unrecognized then download them from Nodejs.org for windows or using the following commands (for macOS). The npm package is installed along with the node. $ brew install node To update these packages use the following commands- $ brew upgrade node Step 2: Now install ethereumjs-testrpc using the following command- $ npm install -g etherumjs-testrpc Step 3: Now you can start the server using the following command $ testrpc Step 1: Open console or command line and move to the folder which contains the JavaScript for your page as follows- $ cd desktop/myproject Step 2: Now, run the npm init command to create a package.json file, which will store project dependencies: $ npm init Step 3: After completing the above installation run the following command for the installation of web3.js- $ npm install ethereum/web3.js0.20.0 –save After the installation of TestRPC and Web3.js create a smart contract which you want to connect with Web3.js. Step 1: Open Remix-IDE. Step 2: Create a sample smart contract as shown below or create any other smart contract. Solidity pragma solidity ^0.4.26; // Creating a contractcontract GFG{ // Defining a function to // print a messagefunction get_output() public pure returns (string) { return ("Hi, your contract ran successfully");}} Step 3: Compile your code and move to the Deploy section. Step 4: Select the environment as Web3 Provider and enter the TestRPC server http://localhost:8545, Make sure TestRPC is running on your system. Step 5: Now using the following code, connect your webpage code to your smart contract. Javascript <script>if (typeof web3 !== 'undefined'){web3 = new Web3(web3.currentProvider);} else{ // Set the provider you want from Web3.providersweb3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));} // Set the 1st account for transactionsweb3.eth.defaultAccount = web3.eth.accounts[0]; // Set the ABIvar yourContract = web3.eth.contract('PASTE ABI HERE!'); // Set the contrcat addressvar contract_name = yourContract.at('PASTE CONTRACT ADDRESS HERE');</script> This code comes directly from the Web3.js Github page. NOTE: 1. Variable names can be changes according to requirements. 2. You need to paste contract address and ABI as asked above in the code. 3. You will get the contract address when you deploy your smart contract. 4. You will get ABI when you compile your smart contract in compilation details. 5. You can use all your contract functions from here onwards. 6. The TestRPC command which we ran provides us 10 accounts, here we are using the first one. Output: The output can be customized as you want to display it on your webpage but in the Remix-IDE the output will look like this after deploying the smart contract This is how your smart contract is interacted with using web3.js. Keep exploring more about Ethereum Blockchain BlockChain Solidity Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Mathematical Operations in Solidity Solidity - Inheritance Dynamic Arrays and its Operations in Solidity Build a To-do List Web Application Powered by Blockchain Solidity - Break and Continue Statements Solidity - View and Pure Functions Solidity - Error Handling What are Events in Solidity? Solidity - Libraries Solidity - Abstract Contract
[ { "code": null, "e": 23999, "s": 23971, "text": "\n14 Oct, 2020" }, { "code": null, "e": 24260, "s": 23999, "text": "Ethereum is a cryptocurrency platform in the market just like Bitcoin. It is an open-source & decentralized blockchain featuring working on smart contracts. It has its own cryptocurrency known as ether. The smart contracts in Ethereum are written in solidity. " }, { "code": null, "e": 24510, "s": 24260, "text": "TestRPC The Ethereum TestRPC is like a manual emulator for blockchain. It provides blockchain interaction without running on an actual Ethereum node. It also provides all the features required for testing of your blockchain. It is based on Node.js. " }, { "code": null, "e": 24779, "s": 24510, "text": "Web3.js Web3.js is an Ethereum-based JavaScript API that allows us to interact with a local or remote Ethereum node using different servers such as HTTP. It interacts with the Ethereum blockchain and can retrieve data from the blockchain as required by the developer. " }, { "code": null, "e": 24972, "s": 24779, "text": "This article describes how to interact with your Ethereum smart contract using Web3.js and TestRPC. It is recommended that you go through on How to Work on Remix-IDE before proceeding further." }, { "code": null, "e": 25044, "s": 24972, "text": "Before we proceed to the steps, install TestRPC and Web3JS as follows –" }, { "code": null, "e": 25156, "s": 25044, "text": "Step 1: Open the console or command line and run the following commands to check if node and npm are installed." }, { "code": null, "e": 25176, "s": 25156, "text": "$ node -v\n$ npm -v\n" }, { "code": null, "e": 25359, "s": 25176, "text": "If the above command goes unrecognized then download them from Nodejs.org for windows or using the following commands (for macOS). The npm package is installed along with the node. " }, { "code": null, "e": 25380, "s": 25359, "text": "$ brew install node\n" }, { "code": null, "e": 25433, "s": 25380, "text": "To update these packages use the following commands-" }, { "code": null, "e": 25454, "s": 25433, "text": "$ brew upgrade node\n" }, { "code": null, "e": 25522, "s": 25454, "text": "Step 2: Now install ethereumjs-testrpc using the following command-" }, { "code": null, "e": 25558, "s": 25522, "text": "$ npm install -g etherumjs-testrpc\n" }, { "code": null, "e": 25625, "s": 25558, "text": "Step 3: Now you can start the server using the following command " }, { "code": null, "e": 25636, "s": 25625, "text": "$ testrpc\n" }, { "code": null, "e": 25752, "s": 25636, "text": "Step 1: Open console or command line and move to the folder which contains the JavaScript for your page as follows-" }, { "code": null, "e": 25776, "s": 25752, "text": "$ cd desktop/myproject\n" }, { "code": null, "e": 25886, "s": 25776, "text": "Step 2: Now, run the npm init command to create a package.json file, which will store project dependencies: " }, { "code": null, "e": 25898, "s": 25886, "text": "$ npm init\n" }, { "code": null, "e": 26005, "s": 25898, "text": "Step 3: After completing the above installation run the following command for the installation of web3.js-" }, { "code": null, "e": 26049, "s": 26005, "text": "$ npm install ethereum/web3.js0.20.0 –save\n" }, { "code": null, "e": 26159, "s": 26049, "text": "After the installation of TestRPC and Web3.js create a smart contract which you want to connect with Web3.js." }, { "code": null, "e": 26183, "s": 26159, "text": "Step 1: Open Remix-IDE." }, { "code": null, "e": 26289, "s": 26183, "text": "Step 2: Create a sample smart contract as shown below or create any other smart contract. " }, { "code": null, "e": 26298, "s": 26289, "text": "Solidity" }, { "code": "pragma solidity ^0.4.26; // Creating a contractcontract GFG{ // Defining a function to // print a messagefunction get_output() public pure returns (string) { return (\"Hi, your contract ran successfully\");}}", "e": 26508, "s": 26298, "text": null }, { "code": null, "e": 26567, "s": 26508, "text": " Step 3: Compile your code and move to the Deploy section." }, { "code": null, "e": 26713, "s": 26567, "text": "Step 4: Select the environment as Web3 Provider and enter the TestRPC server http://localhost:8545, Make sure TestRPC is running on your system. " }, { "code": null, "e": 26801, "s": 26713, "text": "Step 5: Now using the following code, connect your webpage code to your smart contract." }, { "code": null, "e": 26812, "s": 26801, "text": "Javascript" }, { "code": "<script>if (typeof web3 !== 'undefined'){web3 = new Web3(web3.currentProvider);} else{ // Set the provider you want from Web3.providersweb3 = new Web3(new Web3.providers.HttpProvider(\"http://localhost:8545\"));} // Set the 1st account for transactionsweb3.eth.defaultAccount = web3.eth.accounts[0]; // Set the ABIvar yourContract = web3.eth.contract('PASTE ABI HERE!'); // Set the contrcat addressvar contract_name = yourContract.at('PASTE CONTRACT ADDRESS HERE');</script>", "e": 27292, "s": 26812, "text": null }, { "code": null, "e": 27347, "s": 27292, "text": "This code comes directly from the Web3.js Github page." }, { "code": null, "e": 27813, "s": 27347, "text": "NOTE:\n\n 1. Variable names can be changes according to requirements.\n 2. You need to paste contract address and ABI as asked above in the code. \n 3. You will get the contract address when you deploy your smart contract.\n 4. You will get ABI when you compile your smart contract in compilation details.\n 5. You can use all your contract functions from here onwards.\n 6. The TestRPC command which we ran provides us 10 accounts, here we are using the first one.\n" }, { "code": null, "e": 27979, "s": 27813, "text": "Output: The output can be customized as you want to display it on your webpage but in the Remix-IDE the output will look like this after deploying the smart contract" }, { "code": null, "e": 28092, "s": 27979, "text": "This is how your smart contract is interacted with using web3.js. Keep exploring more about Ethereum Blockchain " }, { "code": null, "e": 28103, "s": 28092, "text": "BlockChain" }, { "code": null, "e": 28112, "s": 28103, "text": "Solidity" }, { "code": null, "e": 28210, "s": 28112, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28219, "s": 28210, "text": "Comments" }, { "code": null, "e": 28232, "s": 28219, "text": "Old Comments" }, { "code": null, "e": 28268, "s": 28232, "text": "Mathematical Operations in Solidity" }, { "code": null, "e": 28291, "s": 28268, "text": "Solidity - Inheritance" }, { "code": null, "e": 28337, "s": 28291, "text": "Dynamic Arrays and its Operations in Solidity" }, { "code": null, "e": 28394, "s": 28337, "text": "Build a To-do List Web Application Powered by Blockchain" }, { "code": null, "e": 28435, "s": 28394, "text": "Solidity - Break and Continue Statements" }, { "code": null, "e": 28470, "s": 28435, "text": "Solidity - View and Pure Functions" }, { "code": null, "e": 28496, "s": 28470, "text": "Solidity - Error Handling" }, { "code": null, "e": 28525, "s": 28496, "text": "What are Events in Solidity?" }, { "code": null, "e": 28546, "s": 28525, "text": "Solidity - Libraries" } ]
I used Machine Learning to Organize Dating Profiles | Marco Santos | Towards Data Science
After swiping endlessly through hundreds of dating profiles and not matching with a single one, one might start to wonder how these profiles are even showing up on their phone. All of these profiles are not the type they are looking for. They have been swiping for hours or even days and have not found any success. They might start asking: “Why are these dating apps showing me people that I know I won’t match with?” The dating algorithms used to show dating profiles might seem broken to plenty of people who are tired of swiping left when they should be matching. Every dating site and app probably utilize their own secret dating algorithm meant to optimize matches among their users. But sometimes it feels like it is just showing random users to one another with no explanation. How can we learn more about and also combat this issue? By using a little something called Machine Learning. We could use machine learning to expedite the matchmaking process among users within dating apps. With machine learning, profiles can potentially be clustered together with other similar profiles. This will reduce the number of profiles that are not compatible with one another. From these clusters, users can find other users more like them. The machine learning clustering process has been covered in the article below: towardsdatascience.com Take a moment to read it if you want to know how we were able to achieve clustered groups of dating profiles. Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks! Using the data from the article above, we were able to successfully obtain the clustered dating profiles in a convenient Pandas DataFrame. In this DataFrame we have one profile for each row and at the end, we can see the clustered group they belong to after applying Hierarchical Agglomerative Clustering to the dataset. Each profile belongs to a specific cluster number or group. However, these groups could use some refinement. With the clustered profile data, we can further refine the results by sorting each profile based on how similar they are to one another. This process might be quicker and easier than you may think. Let’s break the code down to simple steps starting with random, which is used throughout the code simply to choose which cluster and user to select. This is done so that our code can be applicable to any user from the dataset. Once we have our randomly selected cluster, we can narrow down the entire dataset to just include those rows with the selected cluster. With our selected clustered group narrowed down, the next step involves vectorizing the bios in that group. The vectorizer we are using for this is the same one we used to create our initial clustered DataFrame — CountVectorizer(). (The vectorizer variable was instantiated previously when we vectorized the first dataset, which can be observed in the article above). # Fitting the vectorizer to the Bioscluster_x = vectorizer.fit_transform(group['Bios'])# Creating a new DF that contains the vectorized wordscluster_v = pd.DataFrame(cluster_x.toarray(), index=group.index, columns=vectorizer.get_feature_names()) By vectorizing the Bios, we are creating a binary matrix that includes the words in each bio. Afterwards, we will join this vectorized DataFrame to the selected group/cluster DataFrame. # Joining the vector DF and the original DFgroup = group.join(cluster_v)# Dropping the Bios because it is no longer neededgroup.drop('Bios', axis=1, inplace=True) After joining the two DataFrame together, we are left with vectorized bios and the categorical columns: From here we can begin to find users that are most similar with one another. Once we have created a DataFrame filled binary values and numbers, we can begin to find the correlations among the dating profiles. Every dating profile has a unique index number from which we can use for reference. In the beginning, we had a total of 6600 dating profiles. After clustering and narrowing down the DataFrame to the selected cluster, the number of dating profiles can range from 100 to 1000. Throughout the entire process, the index number for the dating profiles remained the same. Now, we can use each index number for reference to every dating profile. With each index number representing a unique dating profile, we can find similar or correlated users to each profile. This is achieved by running one line of code to create a correlation matrix. corr_group = group.T.corr() The first thing we needed to do was to transpose the DataFrame in order to have the columns and indices switch. This is done so that the correlation method we use applied to the indices and not the columns. Once we have transposed the DF we can apply the .corr() method which will create a correlation matrix among the indices. This correlation matrix contains numerical values which were calculated using the Pearson Correlation method. Values closer to 1 are positively correlated with each other which is why you will see 1.0000 for indices correlated with their own index. From here you can see where we are going when it comes to finding similar users when using this correlation matrix. Now that we have a correlation matrix containing correlation scores for every index/dating profile, we can begin sorting the profiles based on their similarity. random_user = random.choice(corr_group.index)print("Top 10 most similar users to User #", random_user, '\n')top_10_sim = corr_group[[random_user]].sort_values(by= [random_user],axis=0, ascending=False)[1:11]print(top_10_sim)print("\nThe most similar user to User #", random_user, "is User #", top_10_sim.index[0]) The first line in the code block above selects a random dating profile or user from the correlation matrix. From there, we can select the column with the selected user and sort the users within the column so that it will only return the top 10 most correlated users (excluding the selected index itself). Success! — When we run the code above, we are given a list of users sorted by their respective correlation scores. We can see the top 10 most similar users to our randomly selected user. This can be run again with another cluster group and another profile or user. If this were a dating app, the user would be able to see the top 10 most similar users to themselves. This would hopefully reduce swiping time, frustration, and increase matches among the users of our hypothetical dating app. The hypothetical dating app’s algorithm would implement unsupervised machine learning clustering to create groups of dating profiles. Within those groups, the algorithm would sort the profiles based on their correlation score. Finally, it would be able to present users with dating profiles most similar to themselves. A potential next step would be trying to incorporate new data to our machine learning matchmaker. Maybe have a new user input their own custom data and see how they would match with these fake dating profiles.
[ { "code": null, "e": 513, "s": 172, "text": "After swiping endlessly through hundreds of dating profiles and not matching with a single one, one might start to wonder how these profiles are even showing up on their phone. All of these profiles are not the type they are looking for. They have been swiping for hours or even days and have not found any success. They might start asking:" }, { "code": null, "e": 591, "s": 513, "text": "“Why are these dating apps showing me people that I know I won’t match with?”" }, { "code": null, "e": 1067, "s": 591, "text": "The dating algorithms used to show dating profiles might seem broken to plenty of people who are tired of swiping left when they should be matching. Every dating site and app probably utilize their own secret dating algorithm meant to optimize matches among their users. But sometimes it feels like it is just showing random users to one another with no explanation. How can we learn more about and also combat this issue? By using a little something called Machine Learning." }, { "code": null, "e": 1489, "s": 1067, "text": "We could use machine learning to expedite the matchmaking process among users within dating apps. With machine learning, profiles can potentially be clustered together with other similar profiles. This will reduce the number of profiles that are not compatible with one another. From these clusters, users can find other users more like them. The machine learning clustering process has been covered in the article below:" }, { "code": null, "e": 1512, "s": 1489, "text": "towardsdatascience.com" }, { "code": null, "e": 1622, "s": 1512, "text": "Take a moment to read it if you want to know how we were able to achieve clustered groups of dating profiles." }, { "code": null, "e": 1787, "s": 1622, "text": "Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks!" }, { "code": null, "e": 1926, "s": 1787, "text": "Using the data from the article above, we were able to successfully obtain the clustered dating profiles in a convenient Pandas DataFrame." }, { "code": null, "e": 2217, "s": 1926, "text": "In this DataFrame we have one profile for each row and at the end, we can see the clustered group they belong to after applying Hierarchical Agglomerative Clustering to the dataset. Each profile belongs to a specific cluster number or group. However, these groups could use some refinement." }, { "code": null, "e": 2415, "s": 2217, "text": "With the clustered profile data, we can further refine the results by sorting each profile based on how similar they are to one another. This process might be quicker and easier than you may think." }, { "code": null, "e": 2778, "s": 2415, "text": "Let’s break the code down to simple steps starting with random, which is used throughout the code simply to choose which cluster and user to select. This is done so that our code can be applicable to any user from the dataset. Once we have our randomly selected cluster, we can narrow down the entire dataset to just include those rows with the selected cluster." }, { "code": null, "e": 3146, "s": 2778, "text": "With our selected clustered group narrowed down, the next step involves vectorizing the bios in that group. The vectorizer we are using for this is the same one we used to create our initial clustered DataFrame — CountVectorizer(). (The vectorizer variable was instantiated previously when we vectorized the first dataset, which can be observed in the article above)." }, { "code": null, "e": 3444, "s": 3146, "text": "# Fitting the vectorizer to the Bioscluster_x = vectorizer.fit_transform(group['Bios'])# Creating a new DF that contains the vectorized wordscluster_v = pd.DataFrame(cluster_x.toarray(), index=group.index, columns=vectorizer.get_feature_names())" }, { "code": null, "e": 3538, "s": 3444, "text": "By vectorizing the Bios, we are creating a binary matrix that includes the words in each bio." }, { "code": null, "e": 3630, "s": 3538, "text": "Afterwards, we will join this vectorized DataFrame to the selected group/cluster DataFrame." }, { "code": null, "e": 3793, "s": 3630, "text": "# Joining the vector DF and the original DFgroup = group.join(cluster_v)# Dropping the Bios because it is no longer neededgroup.drop('Bios', axis=1, inplace=True)" }, { "code": null, "e": 3897, "s": 3793, "text": "After joining the two DataFrame together, we are left with vectorized bios and the categorical columns:" }, { "code": null, "e": 3974, "s": 3897, "text": "From here we can begin to find users that are most similar with one another." }, { "code": null, "e": 4190, "s": 3974, "text": "Once we have created a DataFrame filled binary values and numbers, we can begin to find the correlations among the dating profiles. Every dating profile has a unique index number from which we can use for reference." }, { "code": null, "e": 4545, "s": 4190, "text": "In the beginning, we had a total of 6600 dating profiles. After clustering and narrowing down the DataFrame to the selected cluster, the number of dating profiles can range from 100 to 1000. Throughout the entire process, the index number for the dating profiles remained the same. Now, we can use each index number for reference to every dating profile." }, { "code": null, "e": 4740, "s": 4545, "text": "With each index number representing a unique dating profile, we can find similar or correlated users to each profile. This is achieved by running one line of code to create a correlation matrix." }, { "code": null, "e": 4768, "s": 4740, "text": "corr_group = group.T.corr()" }, { "code": null, "e": 5096, "s": 4768, "text": "The first thing we needed to do was to transpose the DataFrame in order to have the columns and indices switch. This is done so that the correlation method we use applied to the indices and not the columns. Once we have transposed the DF we can apply the .corr() method which will create a correlation matrix among the indices." }, { "code": null, "e": 5345, "s": 5096, "text": "This correlation matrix contains numerical values which were calculated using the Pearson Correlation method. Values closer to 1 are positively correlated with each other which is why you will see 1.0000 for indices correlated with their own index." }, { "code": null, "e": 5461, "s": 5345, "text": "From here you can see where we are going when it comes to finding similar users when using this correlation matrix." }, { "code": null, "e": 5622, "s": 5461, "text": "Now that we have a correlation matrix containing correlation scores for every index/dating profile, we can begin sorting the profiles based on their similarity." }, { "code": null, "e": 5948, "s": 5622, "text": "random_user = random.choice(corr_group.index)print(\"Top 10 most similar users to User #\", random_user, '\\n')top_10_sim = corr_group[[random_user]].sort_values(by= [random_user],axis=0, ascending=False)[1:11]print(top_10_sim)print(\"\\nThe most similar user to User #\", random_user, \"is User #\", top_10_sim.index[0])" }, { "code": null, "e": 6253, "s": 5948, "text": "The first line in the code block above selects a random dating profile or user from the correlation matrix. From there, we can select the column with the selected user and sort the users within the column so that it will only return the top 10 most correlated users (excluding the selected index itself)." }, { "code": null, "e": 6518, "s": 6253, "text": "Success! — When we run the code above, we are given a list of users sorted by their respective correlation scores. We can see the top 10 most similar users to our randomly selected user. This can be run again with another cluster group and another profile or user." }, { "code": null, "e": 7063, "s": 6518, "text": "If this were a dating app, the user would be able to see the top 10 most similar users to themselves. This would hopefully reduce swiping time, frustration, and increase matches among the users of our hypothetical dating app. The hypothetical dating app’s algorithm would implement unsupervised machine learning clustering to create groups of dating profiles. Within those groups, the algorithm would sort the profiles based on their correlation score. Finally, it would be able to present users with dating profiles most similar to themselves." } ]
Are Python Exceptions runtime errors?
All python exceptions are not runtime errors, some are syntax errors as well. If you run the given code, you get the following output. File "C:/Users/TutorialsPoint1/~.py", line 4 else: ^ SyntaxError: invalid syntax We see that it is syntax error and not a runtime error. Errors or inaccuracies in a program are often called as bugs. The process of finding and removing errors is called debugging. Errors can be categorized into three major groups: Syntax errors 2. Runtime errors and 3. Logical errors Syntax errors 2. Runtime errors and 3. Logical errors Syntax errors Python will find these kinds of errors when it tries to parse your program, and exit with an error message without running anything. Syntax errors are like spelling or grammar mistakes in a language like English. Runtime errors If a program is free of syntax errors, it will be run by the Python interpreter. However, the program may exit if it encounters a runtime error – a problem that went undetected when the program was parsed, but is only revealed when the code is executed. Some examples of Python Runtime errors − division by zero performing an operation on incompatible types using an identifier which has not been defined accessing a list element, dictionary value or object attribute which doesn’t exist trying to access a file which doesn’t exist
[ { "code": null, "e": 1140, "s": 1062, "text": "All python exceptions are not runtime errors, some are syntax errors as well." }, { "code": null, "e": 1197, "s": 1140, "text": "If you run the given code, you get the following output." }, { "code": null, "e": 1278, "s": 1197, "text": "File \"C:/Users/TutorialsPoint1/~.py\", line 4\nelse:\n^\nSyntaxError: invalid syntax" }, { "code": null, "e": 1334, "s": 1278, "text": "We see that it is syntax error and not a runtime error." }, { "code": null, "e": 1511, "s": 1334, "text": "Errors or inaccuracies in a program are often called as bugs. The process of finding and removing errors is called debugging. Errors can be categorized into three major groups:" }, { "code": null, "e": 1565, "s": 1511, "text": "Syntax errors 2. Runtime errors and 3. Logical errors" }, { "code": null, "e": 1619, "s": 1565, "text": "Syntax errors 2. Runtime errors and 3. Logical errors" }, { "code": null, "e": 1633, "s": 1619, "text": "Syntax errors" }, { "code": null, "e": 1846, "s": 1633, "text": "Python will find these kinds of errors when it tries to parse your program, and exit with an error message without running anything. Syntax errors are like spelling or grammar mistakes in a language like English." }, { "code": null, "e": 1861, "s": 1846, "text": "Runtime errors" }, { "code": null, "e": 2115, "s": 1861, "text": "If a program is free of syntax errors, it will be run by the Python interpreter. However, the program may exit if it encounters a runtime error – a problem that went undetected when the program was parsed, but is only revealed when the code is executed." }, { "code": null, "e": 2156, "s": 2115, "text": "Some examples of Python Runtime errors −" }, { "code": null, "e": 2175, "s": 2158, "text": "division by zero" }, { "code": null, "e": 2221, "s": 2175, "text": "performing an operation on incompatible types" }, { "code": null, "e": 2268, "s": 2221, "text": "using an identifier which has not been defined" }, { "code": null, "e": 2351, "s": 2268, "text": "accessing a list element, dictionary value or object attribute which doesn’t exist" }, { "code": null, "e": 2395, "s": 2351, "text": "trying to access a file which doesn’t exist" } ]
The power of linear programming, a real life case study | by Tristan Bilot | Towards Data Science
Linear programming is a powerful tool widely used to solve optimization problems, but this method remains relatively unknown from the point of view of developers. In this article, I’m going to explain the fundamental principals of linear programming and then apply these principals to a concrete daily life problem. Linear programming consists to apply mathematical models to linear problems in order to maximize or minimize an objective function respecting some constraints. So it can used to solve any problems that can be represented as a linear function with some parameters and constraints. For instance, the famous knapsack and traveling salesman problems are optimization problems that can be solved using linear programming. Basically, the goal of the algorithm will be to determine the optimal values for all the parameters of a function f in order to get the best fit for our problem. Hopefully, we already have algorithms to solve this (eg: simplex algorithm) and as developers we even can use solvers that are specially optimized to solve these kind of problems. Most programming languages offers libraries with easy-to-use solvers. The hard part is not use the algorithm which will solve our problem but to find a way to translate our initial problem in a function with parameters and constraints. After some theory, let’s apply linear programming to a real life case study. Let’s pretend that we are a famous e-commerce platform which want to introduce relay points in a city for the shipping of its products. The only data we have is the position (coordinates) of all the clients of the company in that city. Our goal is to optimally place some relay points based on the position of the clients. In other words, we want to minimize the distance between each relay point and each client in the city. First of all, let’s convert this specification in a usable mathematical expression. We know that in the case of coordinates in a city, we can use the Manhattan distance to approximate the distance of two points. This distance between two points A and B can be written like the sum of the distance between each coordinate as absolute values: So now that we know how to compute the distance between two points, let’s generalize it for for the clients and all the relay points: Where p is the number of relay points we want to place, l the total number of clients in the city, (xi, yi) the p coordinates of the wanted relay points, (al, bl) the m coordinates of all the clients in the city. As we want to minimize this expression, we add a minimization function min() which means that we want to find the optimal (xi, yi) pairs for which the result of the expression will approach the minimum: The next step is to define the good constraints regarding our equation. The constraints will be written as inequations like suggested by the slack form. These constraints will avoid the solving infeasibility of the equation by giving some rules to respect. In our case, the only rules we want to respect for the given variables is the absolute value used in the calculus of the distance. In linear programming, we cannot use an absolute function directly on the equation to minimize, so a way to deal with absolute values is through constraints. Based on the following rule, we can transform an absolute value as a pair of inequalities: When applying these rules on the Manhattan distance between two clients (A1 and A2) and one single relay point (x, y), we get: Where: It is important to note that we will need to write the constraints for each pair of coordinates received in input. Hopefully we are going to automate the generation of the inequations for each points in the next part. For ease of purpose, I chose Python to implement the solution. Well, now let’s forget the maths for an instant and think about the implementation. We have the equation to minimize, we have all the constraints to apply, now what? As said at the beginning, we generally use solvers to solve linear programs, so no exception here, let’s use a solver in Python: scipy.optimize.linprog(C, A_ub, b_ub, A_eq, b_eq) Where C is our equation, A_ub is the left hand side of the inequations, b_ub the right hand side of the inequations, and respectively the same for A_eq and b_eq but with the equations. Why only 4 variables to define all the constraints? Because the constraints will be represented as huge matrices of coefficients. Each column of a matrix represents a variable and each line an (in)equation. For instance, 2x1 + 3x2 ≥ 100 and 4x1 + 6x2 ≥ 0 are transformed as: A_ub = [[-2, -3], [-4, -6]] ; b_ub = [-100, 0] In the slack form, inequations should use ≤ so we inverse the inequalities. For each pair of coordinates, the number of constraints (rows) will constantly remain 5, as see in the step 2. But the number of variables (columns) will grow with the number of clients/relays. As an example, these are the variables used for 1 relay (x, y) and 2 clients (a1, b1), (a2, b2): We’ll use this example during the following next steps. 1 var x >= 0;2 var y >= 0;3 var a1 >= 0;4 var b1 >= 0;5 var a2 >= 0;6 var b2 >= 0;7 var d1 >= 0;8 var d2 >= 0;9 var dx1 >= 0;10 var dy1 >= 0;11 var dx2 >= 0;12 var dy2 >= 0; If we consider all theses variables as a vector, we can define the first parameter C, the equation: C = [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0] As we are looking to minimize d1+d2, we are telling that the column which designed d1 and d2 should be activated with the coefficient preceding d1 and d2 (1 here). As referred to the list of variables above, the indexes 6 and 7 are effectively d1 and d2. Then, let’s compute the left hand side on the inequation matrix representing the constraints defined at the step 2: A_ub = [[0, 0, 0, 0, 0, 0, -1, 0, 1, 1, 0, 0],[1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 0, 0], [-1, 0, 1, 0, 0, 0, 0, 0, -1, 0, 0, 0], [0, 1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 0], [0, -1, 0, 1, 0, 0, 0, 0, 0, -1, 0, 0], [0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 1, 1], [1, 0, 0, 0, -1, 0, 0, 0, 0, 0, -1, 0], [-1, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1, 0], [0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, -1], [0, -1, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1]] Referring to the vector C, we have to replace the variables by their indexes in the vector. In the above example, I transformed the inequalities in the form x1+x2≤0 in order to always have only a 0 on the right hand side. This is an implementation detail but I found it useful in my case because b_ub will thus be a vector of zeros. Note that A_ub has 10 rows because there are only 2 clients for one relay point, 2*5 constraints = 10. Now, the easy part, the right hand side of the inequations should be a vector of zeros as said above: b_ub = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] To be honest, the hardest part is behind us ;), we’ll now fill the equation matrix. Basically, the inequation was for constraints, now the equation matrix represents the given data, in our case this data is the list of clients’ coordinates. So the left hand side of the matrix enumerates at each row a coordinate (ai, bi) for all the clients, and then define the value in the right hand side. A_eq = [[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]] As expected, a diagonal appears in the matrix at the position of all the clients coordinates (a1, b1), (a2, b2). b_eq = [10.0, 20.0, 15.0, 45.0] These values are examples of clients’ coordinates. It’s time to start coding! (finally) In order to compute the 5 previous matrices/vectors, it is preferable to split that in 5 methods: 1 for the equation, 2 for the inequations rhs/lhs and 2 for the equations rhs/lhs. The following methods take two parameters: M: the list of pairs of coordinates (ai, bi) of the clients. p: the number of relay points to place. Finally, call the solver using all the above methods. Let’s test with the example given previously: Input: M = [(10, 20.), (15, 45.)] p = 1Output: [(12, 28)] Given only two points for one relay, there is an infinite number of optimal solutions on the straight line between the two points (eg: (13, 44) is also an optimal solution in this case), but it returns a point around at the middle of the two clients’ coordinates, which is a coherent solution. What if we use this current implementation on multiple clients? The algorithm will return always the best approximation which is one point. But if we set p > 1 we need to place more than one relay. So we need to find out a solution to divide the population M of clients in some groups on which apply the linear program. Different approaches can be used, however, I’ll show an example using the k-means clustering algorithm which allows to divide our population of clients in p clusters based on their coordinates (the nearest clients will be together in the cluster). Input: M=[(0, 50.), (100, 25.), (100, 40.), (50, 85.)] p=3Output: [[(0, 50)], [(100, 25), (100, 40)], [50, 85]] In the above example, we divide the population M in three sub-arrays containing the nearest points. Using Python, it can be done using numpy and scipy like so: Finally, by joining all the pieces, let’s write the solve(M, p) method. Now enjoy the algorithm on big datasets :) Input: n = 10000 M = [(float(random.randrange(0, n)), float(random.randrange(0, n))) for i in range(1000)] p = 5Output: [(3521, 8323), (1923, 5113), (2545, 1486), (7495, 2267), (7600, 7528)] Based on randomly generated coordinates, it could be interesting to simulate the algorithm on a city map. We can observe that the repartition of the relays is pretty well distributed. It’s now free to you to use your own implementation. Thank you for reading, do not hesitate to reach me for further questions or for mistakes made in this article, it will be a joy to debate about that! You can also leave a clap if you learned something in this article :) Full source code of the project: my GitHub repo.
[ { "code": null, "e": 335, "s": 172, "text": "Linear programming is a powerful tool widely used to solve optimization problems, but this method remains relatively unknown from the point of view of developers." }, { "code": null, "e": 488, "s": 335, "text": "In this article, I’m going to explain the fundamental principals of linear programming and then apply these principals to a concrete daily life problem." }, { "code": null, "e": 905, "s": 488, "text": "Linear programming consists to apply mathematical models to linear problems in order to maximize or minimize an objective function respecting some constraints. So it can used to solve any problems that can be represented as a linear function with some parameters and constraints. For instance, the famous knapsack and traveling salesman problems are optimization problems that can be solved using linear programming." }, { "code": null, "e": 1317, "s": 905, "text": "Basically, the goal of the algorithm will be to determine the optimal values for all the parameters of a function f in order to get the best fit for our problem. Hopefully, we already have algorithms to solve this (eg: simplex algorithm) and as developers we even can use solvers that are specially optimized to solve these kind of problems. Most programming languages offers libraries with easy-to-use solvers." }, { "code": null, "e": 1483, "s": 1317, "text": "The hard part is not use the algorithm which will solve our problem but to find a way to translate our initial problem in a function with parameters and constraints." }, { "code": null, "e": 1560, "s": 1483, "text": "After some theory, let’s apply linear programming to a real life case study." }, { "code": null, "e": 1986, "s": 1560, "text": "Let’s pretend that we are a famous e-commerce platform which want to introduce relay points in a city for the shipping of its products. The only data we have is the position (coordinates) of all the clients of the company in that city. Our goal is to optimally place some relay points based on the position of the clients. In other words, we want to minimize the distance between each relay point and each client in the city." }, { "code": null, "e": 2198, "s": 1986, "text": "First of all, let’s convert this specification in a usable mathematical expression. We know that in the case of coordinates in a city, we can use the Manhattan distance to approximate the distance of two points." }, { "code": null, "e": 2327, "s": 2198, "text": "This distance between two points A and B can be written like the sum of the distance between each coordinate as absolute values:" }, { "code": null, "e": 2461, "s": 2327, "text": "So now that we know how to compute the distance between two points, let’s generalize it for for the clients and all the relay points:" }, { "code": null, "e": 2674, "s": 2461, "text": "Where p is the number of relay points we want to place, l the total number of clients in the city, (xi, yi) the p coordinates of the wanted relay points, (al, bl) the m coordinates of all the clients in the city." }, { "code": null, "e": 2877, "s": 2674, "text": "As we want to minimize this expression, we add a minimization function min() which means that we want to find the optimal (xi, yi) pairs for which the result of the expression will approach the minimum:" }, { "code": null, "e": 3514, "s": 2877, "text": "The next step is to define the good constraints regarding our equation. The constraints will be written as inequations like suggested by the slack form. These constraints will avoid the solving infeasibility of the equation by giving some rules to respect. In our case, the only rules we want to respect for the given variables is the absolute value used in the calculus of the distance. In linear programming, we cannot use an absolute function directly on the equation to minimize, so a way to deal with absolute values is through constraints. Based on the following rule, we can transform an absolute value as a pair of inequalities:" }, { "code": null, "e": 3641, "s": 3514, "text": "When applying these rules on the Manhattan distance between two clients (A1 and A2) and one single relay point (x, y), we get:" }, { "code": null, "e": 3648, "s": 3641, "text": "Where:" }, { "code": null, "e": 3866, "s": 3648, "text": "It is important to note that we will need to write the constraints for each pair of coordinates received in input. Hopefully we are going to automate the generation of the inequations for each points in the next part." }, { "code": null, "e": 3929, "s": 3866, "text": "For ease of purpose, I chose Python to implement the solution." }, { "code": null, "e": 4224, "s": 3929, "text": "Well, now let’s forget the maths for an instant and think about the implementation. We have the equation to minimize, we have all the constraints to apply, now what? As said at the beginning, we generally use solvers to solve linear programs, so no exception here, let’s use a solver in Python:" }, { "code": null, "e": 4274, "s": 4224, "text": "scipy.optimize.linprog(C, A_ub, b_ub, A_eq, b_eq)" }, { "code": null, "e": 4459, "s": 4274, "text": "Where C is our equation, A_ub is the left hand side of the inequations, b_ub the right hand side of the inequations, and respectively the same for A_eq and b_eq but with the equations." }, { "code": null, "e": 4666, "s": 4459, "text": "Why only 4 variables to define all the constraints? Because the constraints will be represented as huge matrices of coefficients. Each column of a matrix represents a variable and each line an (in)equation." }, { "code": null, "e": 4734, "s": 4666, "text": "For instance, 2x1 + 3x2 ≥ 100 and 4x1 + 6x2 ≥ 0 are transformed as:" }, { "code": null, "e": 4781, "s": 4734, "text": "A_ub = [[-2, -3], [-4, -6]] ; b_ub = [-100, 0]" }, { "code": null, "e": 4857, "s": 4781, "text": "In the slack form, inequations should use ≤ so we inverse the inequalities." }, { "code": null, "e": 5051, "s": 4857, "text": "For each pair of coordinates, the number of constraints (rows) will constantly remain 5, as see in the step 2. But the number of variables (columns) will grow with the number of clients/relays." }, { "code": null, "e": 5148, "s": 5051, "text": "As an example, these are the variables used for 1 relay (x, y) and 2 clients (a1, b1), (a2, b2):" }, { "code": null, "e": 5204, "s": 5148, "text": "We’ll use this example during the following next steps." }, { "code": null, "e": 5387, "s": 5204, "text": "1 var x >= 0;2 var y >= 0;3 var a1 >= 0;4 var b1 >= 0;5 var a2 >= 0;6 var b2 >= 0;7 var d1 >= 0;8 var d2 >= 0;9 var dx1 >= 0;10 var dy1 >= 0;11 var dx2 >= 0;12 var dy2 >= 0;" }, { "code": null, "e": 5487, "s": 5387, "text": "If we consider all theses variables as a vector, we can define the first parameter C, the equation:" }, { "code": null, "e": 5528, "s": 5487, "text": "C = [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0]" }, { "code": null, "e": 5783, "s": 5528, "text": "As we are looking to minimize d1+d2, we are telling that the column which designed d1 and d2 should be activated with the coefficient preceding d1 and d2 (1 here). As referred to the list of variables above, the indexes 6 and 7 are effectively d1 and d2." }, { "code": null, "e": 5899, "s": 5783, "text": "Then, let’s compute the left hand side on the inequation matrix representing the constraints defined at the step 2:" }, { "code": null, "e": 6304, "s": 5899, "text": "A_ub = [[0, 0, 0, 0, 0, 0, -1, 0, 1, 1, 0, 0],[1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 0, 0], [-1, 0, 1, 0, 0, 0, 0, 0, -1, 0, 0, 0], [0, 1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 0], [0, -1, 0, 1, 0, 0, 0, 0, 0, -1, 0, 0], [0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 1, 1], [1, 0, 0, 0, -1, 0, 0, 0, 0, 0, -1, 0], [-1, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1, 0], [0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, -1], [0, -1, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1]]" }, { "code": null, "e": 6637, "s": 6304, "text": "Referring to the vector C, we have to replace the variables by their indexes in the vector. In the above example, I transformed the inequalities in the form x1+x2≤0 in order to always have only a 0 on the right hand side. This is an implementation detail but I found it useful in my case because b_ub will thus be a vector of zeros." }, { "code": null, "e": 6740, "s": 6637, "text": "Note that A_ub has 10 rows because there are only 2 clients for one relay point, 2*5 constraints = 10." }, { "code": null, "e": 6842, "s": 6740, "text": "Now, the easy part, the right hand side of the inequations should be a vector of zeros as said above:" }, { "code": null, "e": 6880, "s": 6842, "text": "b_ub = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]" }, { "code": null, "e": 7273, "s": 6880, "text": "To be honest, the hardest part is behind us ;), we’ll now fill the equation matrix. Basically, the inequation was for constraints, now the equation matrix represents the given data, in our case this data is the list of clients’ coordinates. So the left hand side of the matrix enumerates at each row a coordinate (ai, bi) for all the clients, and then define the value in the right hand side." }, { "code": null, "e": 7431, "s": 7273, "text": "A_eq = [[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]]" }, { "code": null, "e": 7544, "s": 7431, "text": "As expected, a diagonal appears in the matrix at the position of all the clients coordinates (a1, b1), (a2, b2)." }, { "code": null, "e": 7576, "s": 7544, "text": "b_eq = [10.0, 20.0, 15.0, 45.0]" }, { "code": null, "e": 7627, "s": 7576, "text": "These values are examples of clients’ coordinates." }, { "code": null, "e": 7664, "s": 7627, "text": "It’s time to start coding! (finally)" }, { "code": null, "e": 7888, "s": 7664, "text": "In order to compute the 5 previous matrices/vectors, it is preferable to split that in 5 methods: 1 for the equation, 2 for the inequations rhs/lhs and 2 for the equations rhs/lhs. The following methods take two parameters:" }, { "code": null, "e": 7949, "s": 7888, "text": "M: the list of pairs of coordinates (ai, bi) of the clients." }, { "code": null, "e": 7989, "s": 7949, "text": "p: the number of relay points to place." }, { "code": null, "e": 8043, "s": 7989, "text": "Finally, call the solver using all the above methods." }, { "code": null, "e": 8089, "s": 8043, "text": "Let’s test with the example given previously:" }, { "code": null, "e": 8150, "s": 8089, "text": "Input: M = [(10, 20.), (15, 45.)] p = 1Output: [(12, 28)]" }, { "code": null, "e": 8444, "s": 8150, "text": "Given only two points for one relay, there is an infinite number of optimal solutions on the straight line between the two points (eg: (13, 44) is also an optimal solution in this case), but it returns a point around at the middle of the two clients’ coordinates, which is a coherent solution." }, { "code": null, "e": 9012, "s": 8444, "text": "What if we use this current implementation on multiple clients? The algorithm will return always the best approximation which is one point. But if we set p > 1 we need to place more than one relay. So we need to find out a solution to divide the population M of clients in some groups on which apply the linear program. Different approaches can be used, however, I’ll show an example using the k-means clustering algorithm which allows to divide our population of clients in p clusters based on their coordinates (the nearest clients will be together in the cluster)." }, { "code": null, "e": 9126, "s": 9012, "text": "Input: M=[(0, 50.), (100, 25.), (100, 40.), (50, 85.)] p=3Output: [[(0, 50)], [(100, 25), (100, 40)], [50, 85]]" }, { "code": null, "e": 9286, "s": 9126, "text": "In the above example, we divide the population M in three sub-arrays containing the nearest points. Using Python, it can be done using numpy and scipy like so:" }, { "code": null, "e": 9358, "s": 9286, "text": "Finally, by joining all the pieces, let’s write the solve(M, p) method." }, { "code": null, "e": 9401, "s": 9358, "text": "Now enjoy the algorithm on big datasets :)" }, { "code": null, "e": 9596, "s": 9401, "text": "Input: n = 10000 M = [(float(random.randrange(0, n)), float(random.randrange(0, n))) for i in range(1000)] p = 5Output: [(3521, 8323), (1923, 5113), (2545, 1486), (7495, 2267), (7600, 7528)]" }, { "code": null, "e": 9702, "s": 9596, "text": "Based on randomly generated coordinates, it could be interesting to simulate the algorithm on a city map." }, { "code": null, "e": 9833, "s": 9702, "text": "We can observe that the repartition of the relays is pretty well distributed. It’s now free to you to use your own implementation." }, { "code": null, "e": 9983, "s": 9833, "text": "Thank you for reading, do not hesitate to reach me for further questions or for mistakes made in this article, it will be a joy to debate about that!" }, { "code": null, "e": 10053, "s": 9983, "text": "You can also leave a clap if you learned something in this article :)" } ]
C# For Loop
When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop: for (statement 1; statement 2; statement 3) { // code block to be executed } Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block. Statement 3 is executed (every time) after the code block has been executed. The example below will print the numbers 0 to 4: for (int i = 0; i < 5; i++) { Console.WriteLine(i); } Try it Yourself » Statement 1 sets a variable before the loop starts (int i = 0). Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end. Statement 3 increases a value (i++) each time the code block in the loop has been executed. This example will only print even values between 0 and 10: for (int i = 0; i <= 10; i = i + 2) { Console.WriteLine(i); } Try it Yourself » There is also a foreach loop, which is used exclusively to loop through elements in an array: foreach (type variableName in arrayName) { // code block to be executed } The following example outputs all elements in the cars array, using a foreach loop: string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; foreach (string i in cars) { Console.WriteLine(i); } Try it Yourself » Note: Don't worry if you don't understand the example above. You will learn more about Arrays in the C# Arrays chapter. Use a for loop to print "Yes" 5 times: (int i = 0; i < 5; ) { Console.WriteLine("Yes"); } Start the Exercise 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": 122, "s": 0, "text": "When you know exactly how many times you want to loop through a block of \ncode, use the for loop instead of a while loop:" }, { "code": null, "e": 203, "s": 122, "text": "for (statement 1; statement 2; statement 3) \n{\n // code block to be executed\n}\n" }, { "code": null, "e": 278, "s": 203, "text": "Statement 1 is executed (one time) before the execution of the code block." }, { "code": null, "e": 342, "s": 278, "text": "Statement 2 defines the condition for executing the code block." }, { "code": null, "e": 419, "s": 342, "text": "Statement 3 is executed (every time) after the code block has been executed." }, { "code": null, "e": 468, "s": 419, "text": "The example below will print the numbers 0 to 4:" }, { "code": null, "e": 526, "s": 468, "text": "for (int i = 0; i < 5; i++) \n{\n Console.WriteLine(i);\n}\n" }, { "code": null, "e": 546, "s": 526, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 610, "s": 546, "text": "Statement 1 sets a variable before the loop starts (int i = 0)." }, { "code": null, "e": 784, "s": 610, "text": "Statement 2 defines the condition for the loop to run (i must be less than \n5). If the condition is true, the loop will start over again, if it is false, \nthe loop will end." }, { "code": null, "e": 877, "s": 784, "text": "Statement 3 increases a value (i++) each time the code block in the loop has \nbeen executed." }, { "code": null, "e": 936, "s": 877, "text": "This example will only print even values between 0 and 10:" }, { "code": null, "e": 1002, "s": 936, "text": "for (int i = 0; i <= 10; i = i + 2) \n{\n Console.WriteLine(i);\n}\n" }, { "code": null, "e": 1022, "s": 1002, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1116, "s": 1022, "text": "There is also a foreach loop, which is used exclusively to loop through elements in an array:" }, { "code": null, "e": 1194, "s": 1116, "text": "foreach (type variableName in arrayName) \n{\n // code block to be executed\n}\n" }, { "code": null, "e": 1279, "s": 1194, "text": "The following example outputs all elements in the cars \narray, using a foreach loop:" }, { "code": null, "e": 1387, "s": 1279, "text": "string[] cars = {\"Volvo\", \"BMW\", \"Ford\", \"Mazda\"};\nforeach (string i in cars) \n{\n Console.WriteLine(i);\n}\n" }, { "code": null, "e": 1407, "s": 1387, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1527, "s": 1407, "text": "Note: Don't worry if you don't understand the example above. You will learn more about Arrays in the C# Arrays chapter." }, { "code": null, "e": 1566, "s": 1527, "text": "Use a for loop to print \"Yes\" 5 times:" }, { "code": null, "e": 1622, "s": 1566, "text": " (int i = 0; i < 5; ) \n{\n Console.WriteLine(\"Yes\");\n}\n" }, { "code": null, "e": 1641, "s": 1622, "text": "Start the Exercise" }, { "code": null, "e": 1674, "s": 1641, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1716, "s": 1674, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1823, "s": 1716, "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": 1842, "s": 1823, "text": "help@w3schools.com" } ]
Understanding and using k-Nearest Neighbours aka kNN for classification of digits | by Shubham Gupta | Towards Data Science
In machine learning and statistics, classification is a task of finding the class of a new observation using it’s features/variables. This classification is done using a classifier trained on the basis of training data. Training data is a set of many observations which are correctly labelled with the appropriate class names. Supervised learning involves training with correctly labelled observations hence classification is considered as supervised learning. Examples of classification: Labelling an email to ‘spam’ or ‘non-spam’ using email features like words, images and attachments of the email. Labelling a patient to ‘healthy’ or ‘ill’ using patient’s features like gender, age, weight, blood pressure and observed symptoms. There are many models which can be used for classification task in machine learning but we will be working with k-Nearest Neighbours as it is simple to use yet powerful. It is an algorithm which classifies a new data point based on it’s proximity to other data point groups. Higher the proximity of new data point from one group, higher is the likelihood of it getting classified into that group. Distance between data points is measured by distance metrics like euclidean distance, manhattan distance, minkowski distance, mahalanobis distance, tangential distance, cosine distance and many more. For data points X and Y with n features: Minkowski distance formula is: Minkowski distance when p = 1 is Manhattan distance, when p =2 is Euclidean distance and when p = ∞ is Chebychev distance. Minkowski distance is a generalised form of euclidean distance. Using distance metric we create a neighbourhood of n closest neighbours to the new data point. To get the class of new data point, we look at the class groups which have more data points in the created neighbourhood and the class groups which are closer to our new data point compared to other groups in the neighbourhood. Based on these two factors we determine the class of our new data point. Let’s try understand this better with an example. Example: Consider a task of classifying customers into two categories happy and unhappy. You may want to know which customers are unhappy beforehand so that you can prevent them from switching to a competitor service by offering them discounts. In the image, red represents customers who are unhappy and they have already switched to another competitor whereas blue represents customers happy with us and still using our service. Now, we have a new customer represented using green circle and we want to know if he is happy or unhappy with our service using kNN algorithm. If we use 3 neighbours and we are using equal weights for each data point, then we have 2 red points and 1 blue point in the neighbourhood and green point i.e. new data point is classified as red. If we use 5 neighbours and we are using equal weights for each data point, then we have 3 blue points and 2 red points in the neighbourhood and green point is classified as blue. If we use 5 neighbours and we are using euclidean distance to calculate weights for each data point, then we have 3 blue points and 2 red points in the neighbourhood. Euclidean distances between data points are denoted using lines. To calculate weights using euclidean distances we will take inverse of the distances so that closer points have higher weights. For each class we will take sum of calculated weights, and class with higher summed weight becomes predicted class. Sum of weights for red class: 1/3 + 1/4 = 0.5833 Sum of weights for blue class: 1/5 + 1/8 + 1/6 = 0.4912 Since red class has higher weight, our predicted class for new data point is red class. In machine learning, before we can use any algorithm, we need to choose the value of hyper-parameters for that model. In case of kNN, important hyper-parameters are: n_neighbors: Number of neighbours in a neighbourhood. weights: If set to uniform, all points in each neighbourhood have equal influence in predicting class i.e. predicted class is the class with highest number of points in the neighbourhood. If set to distance, closer neighbours will have greater influence than neighbours further away i.e. class with more points close to new data point becomes predicted class and to do this we take inverse of distance while calculating weights so that closer points have higher weights. metric: The distance metric to use if we have weights set to distance. Default value is minkowski which is one method to calculate distance between two data points. We can change the default value to use other distance metrics. p: It is power parameter for minkowski metric. If p=1, then distance metric is manhattan_distance. If p=2, then distance metric is euclidean_distance. We can experiment with higher values of p if we want to. # kNN hyper-parametrssklearn.neighbors.KNeighborsClassifier(n_neighbors, weights, metric, p) Trying out different hyper-parameter values with cross validation can help you choose the right hyper-parameters for your final model. We will be building a classifier to classify hand written digits into one of the class from 0 to 9. The data we will be using is obtained from MNIST database which is a set of 60,000 28×28 pixel black and white images of handwritten individual digits between 0 and 9. Importing libraries: # To load MNIST image datafrom sklearn.datasets import load_digits# kNN Classifierfrom sklearn.neighbors import KNeighborsClassifier# Confusion matrix to check model performancefrom sklearn.metrics import confusion_matrix# To split data into training and testing setfrom sklearn.model_selection import train_test_split# For plotting digitimport matplotlib.pyplot as plt Loading MNIST data of digits: digits = load_digits() Transforming data to use with kNN classifier: # Number of imagesn_samples = len(digits.images)# Changing shape from 28x28 pixel values to a sequence of valuesX = digits.images.reshape((n_samples, -1))# Getting the already known targets for each imagey = digits.target Creating our training and testing sets: # Splitting data to train and test setsX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) Creating and training model: # Creating modelclf = KNeighborsClassifier(n_neighbors=3)# Training modelclf.fit(X_train, y_train) Getting predictions for test data: # Predictions for test datapredicted = clf.predict(X_test) Comparing actual and predicted target values using confusion matrix: # Print confusion matrixconfusion_matrix(y_test, predicted) In the matrix, rows represent actual target values where first row is for 0 label, second for 1 label and so on. Similarly, columns represent predictions where first column is for 0 label, second is for 1 label and so on. Values along the diagonal of the matrix highlighted in yellow are the values which were predicted correctly. Consider the value highlighted in blue which is 4th column and 9th row. It is a mistake. Our model misclassified 3 as 8. Overall, our model did a good job in classifying the digits as misclassifications i.e. values other than diagonal are mostly zero or smaller than 2. Looking at first 10 images and predictions: # Zip image with predictionimage_with_prediction = list(zip(digits.images, clf.predict(X)))# for first 10 imagesfor pos, (image, prediction) in enumerate(image_with_prediction[:10]): plt.subplot(3, 4, pos+1) # Create 3x4 grid plt.axis('off') # no axis plt.imshow(image, cmap=plt.cm.gray_r) # show image in gray scale plt.title("Prediction: %i" % prediction) # set title to predicted valueplt.show() # show plot All the predictions look good except for the 6th image which looks more like 5 but our model thinks it it 9. When using kNN on your own problems ensure that distances for every feature is scaled according to importance of that feature. In case of house price problem, our features age and house price will have very different scales and you will have to scale down the house price feature to improve model performance. If your data has large number of dimension then you may want to reduce your features by using feature reduction and feature engineering techniques because data with higher dimension leads to less accuracy. kNN works well on MNIST dataset because it is a controlled dataset i.e. position of digits is uniform across all the images. Also, the pixel values across all images have similar colour gradients. When dealing with classification problems on images with lot of spatial information i.e. varying position of objects in image and varying colour gradients, you may want to use Convolutional Neural Networks which are built specifically for this kind of task. kNN can also be used as a regression algorithm i.e. instead of predicting discrete classes it can also be used to predict continuous numbers like house price. Hope this helped you understand kNN. Thanks for reading.
[ { "code": null, "e": 633, "s": 172, "text": "In machine learning and statistics, classification is a task of finding the class of a new observation using it’s features/variables. This classification is done using a classifier trained on the basis of training data. Training data is a set of many observations which are correctly labelled with the appropriate class names. Supervised learning involves training with correctly labelled observations hence classification is considered as supervised learning." }, { "code": null, "e": 661, "s": 633, "text": "Examples of classification:" }, { "code": null, "e": 774, "s": 661, "text": "Labelling an email to ‘spam’ or ‘non-spam’ using email features like words, images and attachments of the email." }, { "code": null, "e": 905, "s": 774, "text": "Labelling a patient to ‘healthy’ or ‘ill’ using patient’s features like gender, age, weight, blood pressure and observed symptoms." }, { "code": null, "e": 1075, "s": 905, "text": "There are many models which can be used for classification task in machine learning but we will be working with k-Nearest Neighbours as it is simple to use yet powerful." }, { "code": null, "e": 1302, "s": 1075, "text": "It is an algorithm which classifies a new data point based on it’s proximity to other data point groups. Higher the proximity of new data point from one group, higher is the likelihood of it getting classified into that group." }, { "code": null, "e": 1502, "s": 1302, "text": "Distance between data points is measured by distance metrics like euclidean distance, manhattan distance, minkowski distance, mahalanobis distance, tangential distance, cosine distance and many more." }, { "code": null, "e": 1543, "s": 1502, "text": "For data points X and Y with n features:" }, { "code": null, "e": 1574, "s": 1543, "text": "Minkowski distance formula is:" }, { "code": null, "e": 1761, "s": 1574, "text": "Minkowski distance when p = 1 is Manhattan distance, when p =2 is Euclidean distance and when p = ∞ is Chebychev distance. Minkowski distance is a generalised form of euclidean distance." }, { "code": null, "e": 1856, "s": 1761, "text": "Using distance metric we create a neighbourhood of n closest neighbours to the new data point." }, { "code": null, "e": 2157, "s": 1856, "text": "To get the class of new data point, we look at the class groups which have more data points in the created neighbourhood and the class groups which are closer to our new data point compared to other groups in the neighbourhood. Based on these two factors we determine the class of our new data point." }, { "code": null, "e": 2207, "s": 2157, "text": "Let’s try understand this better with an example." }, { "code": null, "e": 2216, "s": 2207, "text": "Example:" }, { "code": null, "e": 2452, "s": 2216, "text": "Consider a task of classifying customers into two categories happy and unhappy. You may want to know which customers are unhappy beforehand so that you can prevent them from switching to a competitor service by offering them discounts." }, { "code": null, "e": 2637, "s": 2452, "text": "In the image, red represents customers who are unhappy and they have already switched to another competitor whereas blue represents customers happy with us and still using our service." }, { "code": null, "e": 2780, "s": 2637, "text": "Now, we have a new customer represented using green circle and we want to know if he is happy or unhappy with our service using kNN algorithm." }, { "code": null, "e": 2977, "s": 2780, "text": "If we use 3 neighbours and we are using equal weights for each data point, then we have 2 red points and 1 blue point in the neighbourhood and green point i.e. new data point is classified as red." }, { "code": null, "e": 3156, "s": 2977, "text": "If we use 5 neighbours and we are using equal weights for each data point, then we have 3 blue points and 2 red points in the neighbourhood and green point is classified as blue." }, { "code": null, "e": 3388, "s": 3156, "text": "If we use 5 neighbours and we are using euclidean distance to calculate weights for each data point, then we have 3 blue points and 2 red points in the neighbourhood. Euclidean distances between data points are denoted using lines." }, { "code": null, "e": 3632, "s": 3388, "text": "To calculate weights using euclidean distances we will take inverse of the distances so that closer points have higher weights. For each class we will take sum of calculated weights, and class with higher summed weight becomes predicted class." }, { "code": null, "e": 3662, "s": 3632, "text": "Sum of weights for red class:" }, { "code": null, "e": 3681, "s": 3662, "text": "1/3 + 1/4 = 0.5833" }, { "code": null, "e": 3712, "s": 3681, "text": "Sum of weights for blue class:" }, { "code": null, "e": 3737, "s": 3712, "text": "1/5 + 1/8 + 1/6 = 0.4912" }, { "code": null, "e": 3825, "s": 3737, "text": "Since red class has higher weight, our predicted class for new data point is red class." }, { "code": null, "e": 3991, "s": 3825, "text": "In machine learning, before we can use any algorithm, we need to choose the value of hyper-parameters for that model. In case of kNN, important hyper-parameters are:" }, { "code": null, "e": 4045, "s": 3991, "text": "n_neighbors: Number of neighbours in a neighbourhood." }, { "code": null, "e": 4516, "s": 4045, "text": "weights: If set to uniform, all points in each neighbourhood have equal influence in predicting class i.e. predicted class is the class with highest number of points in the neighbourhood. If set to distance, closer neighbours will have greater influence than neighbours further away i.e. class with more points close to new data point becomes predicted class and to do this we take inverse of distance while calculating weights so that closer points have higher weights." }, { "code": null, "e": 4744, "s": 4516, "text": "metric: The distance metric to use if we have weights set to distance. Default value is minkowski which is one method to calculate distance between two data points. We can change the default value to use other distance metrics." }, { "code": null, "e": 4952, "s": 4744, "text": "p: It is power parameter for minkowski metric. If p=1, then distance metric is manhattan_distance. If p=2, then distance metric is euclidean_distance. We can experiment with higher values of p if we want to." }, { "code": null, "e": 5045, "s": 4952, "text": "# kNN hyper-parametrssklearn.neighbors.KNeighborsClassifier(n_neighbors, weights, metric, p)" }, { "code": null, "e": 5180, "s": 5045, "text": "Trying out different hyper-parameter values with cross validation can help you choose the right hyper-parameters for your final model." }, { "code": null, "e": 5448, "s": 5180, "text": "We will be building a classifier to classify hand written digits into one of the class from 0 to 9. The data we will be using is obtained from MNIST database which is a set of 60,000 28×28 pixel black and white images of handwritten individual digits between 0 and 9." }, { "code": null, "e": 5469, "s": 5448, "text": "Importing libraries:" }, { "code": null, "e": 5839, "s": 5469, "text": "# To load MNIST image datafrom sklearn.datasets import load_digits# kNN Classifierfrom sklearn.neighbors import KNeighborsClassifier# Confusion matrix to check model performancefrom sklearn.metrics import confusion_matrix# To split data into training and testing setfrom sklearn.model_selection import train_test_split# For plotting digitimport matplotlib.pyplot as plt" }, { "code": null, "e": 5869, "s": 5839, "text": "Loading MNIST data of digits:" }, { "code": null, "e": 5892, "s": 5869, "text": "digits = load_digits()" }, { "code": null, "e": 5938, "s": 5892, "text": "Transforming data to use with kNN classifier:" }, { "code": null, "e": 6160, "s": 5938, "text": "# Number of imagesn_samples = len(digits.images)# Changing shape from 28x28 pixel values to a sequence of valuesX = digits.images.reshape((n_samples, -1))# Getting the already known targets for each imagey = digits.target" }, { "code": null, "e": 6200, "s": 6160, "text": "Creating our training and testing sets:" }, { "code": null, "e": 6313, "s": 6200, "text": "# Splitting data to train and test setsX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)" }, { "code": null, "e": 6342, "s": 6313, "text": "Creating and training model:" }, { "code": null, "e": 6441, "s": 6342, "text": "# Creating modelclf = KNeighborsClassifier(n_neighbors=3)# Training modelclf.fit(X_train, y_train)" }, { "code": null, "e": 6476, "s": 6441, "text": "Getting predictions for test data:" }, { "code": null, "e": 6535, "s": 6476, "text": "# Predictions for test datapredicted = clf.predict(X_test)" }, { "code": null, "e": 6604, "s": 6535, "text": "Comparing actual and predicted target values using confusion matrix:" }, { "code": null, "e": 6664, "s": 6604, "text": "# Print confusion matrixconfusion_matrix(y_test, predicted)" }, { "code": null, "e": 6886, "s": 6664, "text": "In the matrix, rows represent actual target values where first row is for 0 label, second for 1 label and so on. Similarly, columns represent predictions where first column is for 0 label, second is for 1 label and so on." }, { "code": null, "e": 6995, "s": 6886, "text": "Values along the diagonal of the matrix highlighted in yellow are the values which were predicted correctly." }, { "code": null, "e": 7116, "s": 6995, "text": "Consider the value highlighted in blue which is 4th column and 9th row. It is a mistake. Our model misclassified 3 as 8." }, { "code": null, "e": 7265, "s": 7116, "text": "Overall, our model did a good job in classifying the digits as misclassifications i.e. values other than diagonal are mostly zero or smaller than 2." }, { "code": null, "e": 7309, "s": 7265, "text": "Looking at first 10 images and predictions:" }, { "code": null, "e": 7732, "s": 7309, "text": "# Zip image with predictionimage_with_prediction = list(zip(digits.images, clf.predict(X)))# for first 10 imagesfor pos, (image, prediction) in enumerate(image_with_prediction[:10]): plt.subplot(3, 4, pos+1) # Create 3x4 grid plt.axis('off') # no axis plt.imshow(image, cmap=plt.cm.gray_r) # show image in gray scale plt.title(\"Prediction: %i\" % prediction) # set title to predicted valueplt.show() # show plot" }, { "code": null, "e": 7841, "s": 7732, "text": "All the predictions look good except for the 6th image which looks more like 5 but our model thinks it it 9." }, { "code": null, "e": 8151, "s": 7841, "text": "When using kNN on your own problems ensure that distances for every feature is scaled according to importance of that feature. In case of house price problem, our features age and house price will have very different scales and you will have to scale down the house price feature to improve model performance." }, { "code": null, "e": 8357, "s": 8151, "text": "If your data has large number of dimension then you may want to reduce your features by using feature reduction and feature engineering techniques because data with higher dimension leads to less accuracy." }, { "code": null, "e": 8812, "s": 8357, "text": "kNN works well on MNIST dataset because it is a controlled dataset i.e. position of digits is uniform across all the images. Also, the pixel values across all images have similar colour gradients. When dealing with classification problems on images with lot of spatial information i.e. varying position of objects in image and varying colour gradients, you may want to use Convolutional Neural Networks which are built specifically for this kind of task." }, { "code": null, "e": 8971, "s": 8812, "text": "kNN can also be used as a regression algorithm i.e. instead of predicting discrete classes it can also be used to predict continuous numbers like house price." }, { "code": null, "e": 9008, "s": 8971, "text": "Hope this helped you understand kNN." } ]
Microsoft Azure - Using C# in CosmoDB - GeeksforGeeks
01 Jun, 2021 In this article, we will look into how to use C# notebooks in Azure Cosmos DB. When you are creating an application that uses Azure Cosmos DB, it is useful to experiment with code that uses that Cosmos DB. In Azure Cosmos DB, you can use C# notebooks that enable you to write the C# code that interacts with Cosmos DB. To do so follow the below steps: Step 1: In the Azure portal we have an already existing Cosmos DB. We’ve populated it with data by using the Start with Sample button. Step 2: To use notebooks, we first need to enable them and complete the setup. This creates a notebook workspace in the Cosmos DB. Step 3: Now let’s try it by creating a new notebook by clicking on the New Notebook menu. This is the new notebook. It has a new cell that can run code. You can also create cells that display text. Step 4: The sample data contains Person data, and the below image is a representation of that. The above code is of C# and we can run it with the below-highlighted button. Step 5: Make sure that the language setting is set to CSharp. Step 6: Now let’s add another code cell, and here we paste the below code. This code connects to the Cosmos DB and executes a query against it using the Cosmos DB .NET SDK. C# using System.Linq.Expressions; // namespace for Azure Cosmos DB .NET V3 SOKusing Microsoft.Azure.Cosmos;using System.Collections; // Initialize a new instance of cosmosClient using // the built-in account endpoint and key parameters Cosmosclient cosmosClient = new CosmosClient (Cosmos.Endpoint, Cosmos.Key);Microsoft.Azure.Cosmos.Database database = await cosmosClient.CreateDatabaseIfNotExistsAsync("SampleDB");Container container = await database.CreateContainerIfNotExistsAsync("Persons", "/firstname", 400); QueryDefinition queryDefinition = new QueryDefinition("SELECT * FROM c"); FeedIterator<Person> queryResultSetIterator = container.GetItemQueryIterator<Person>(queryDefinition); List<Person> personEvents = new List<Person(); while (queryResultSetIterator.HasMoreResults){ FeedResponse<Person> currentResultSet = await queryResultSetIterator.ReadNextAsync();foreach (Person personEvent in currentResultSet){personEvents.Add(personEvent);}} personEvents It then puts the query results in a list of person objects and outputs by simply adding it to the last line of code. It also triggers the notebook to start the data visualization feature. Also, note that we don’t have to insert the actual endpoint and key. These are already known by the system. Step 7: Now let’s run this. This results in a table with the data. We can also switch to other views of the data. The workspace also contains a gallery. This gallery contains example notebooks that you can browse and download to your workspace to play with and learn from. The Azure Cosmos DB .NET SDK enables you to manage your Azure Cosmos DB and interact with its data. You can use the SDK in intelligent notebooks within Azure Cosmos DB that enable you to run code at descriptive texts and visualize data. azure-cosmosdb Cloud-Computing Microsoft Azure Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Microsoft Azure - KQL Query to Get the VM Computer Properties Microsoft Azure - Query System Event Log Data Using Azure KQL Microsoft Azure - Rebooting an Application Gateway Microsoft Azure - Graph Query to Get Properties of Azure VM Resource Microsoft Azure - Enabling Logs for Troubleshooting the Azure Firewall Rules Microsoft Azure - Enable IIS Logs for Monitoring Microsoft Azure - Using the Azure Activity Log Microsoft Azure - Deploy a Static Web App Microsoft Azure - Using Deployment Slots For Web App Microsoft Azure - Using Cost Recommendations on Azure Advisor
[ { "code": null, "e": 25385, "s": 25357, "text": "\n01 Jun, 2021" }, { "code": null, "e": 25705, "s": 25385, "text": "In this article, we will look into how to use C# notebooks in Azure Cosmos DB. When you are creating an application that uses Azure Cosmos DB, it is useful to experiment with code that uses that Cosmos DB. In Azure Cosmos DB, you can use C# notebooks that enable you to write the C# code that interacts with Cosmos DB. " }, { "code": null, "e": 25738, "s": 25705, "text": "To do so follow the below steps:" }, { "code": null, "e": 25873, "s": 25738, "text": "Step 1: In the Azure portal we have an already existing Cosmos DB. We’ve populated it with data by using the Start with Sample button." }, { "code": null, "e": 25953, "s": 25873, "text": "Step 2: To use notebooks, we first need to enable them and complete the setup. " }, { "code": null, "e": 26006, "s": 25953, "text": "This creates a notebook workspace in the Cosmos DB. " }, { "code": null, "e": 26097, "s": 26006, "text": "Step 3: Now let’s try it by creating a new notebook by clicking on the New Notebook menu. " }, { "code": null, "e": 26206, "s": 26097, "text": "This is the new notebook. It has a new cell that can run code. You can also create cells that display text. " }, { "code": null, "e": 26302, "s": 26206, "text": "Step 4: The sample data contains Person data, and the below image is a representation of that. " }, { "code": null, "e": 26380, "s": 26302, "text": "The above code is of C# and we can run it with the below-highlighted button. " }, { "code": null, "e": 26443, "s": 26380, "text": "Step 5: Make sure that the language setting is set to CSharp. " }, { "code": null, "e": 26616, "s": 26443, "text": "Step 6: Now let’s add another code cell, and here we paste the below code. This code connects to the Cosmos DB and executes a query against it using the Cosmos DB .NET SDK." }, { "code": null, "e": 26619, "s": 26616, "text": "C#" }, { "code": "using System.Linq.Expressions; // namespace for Azure Cosmos DB .NET V3 SOKusing Microsoft.Azure.Cosmos;using System.Collections; // Initialize a new instance of cosmosClient using // the built-in account endpoint and key parameters Cosmosclient cosmosClient = new CosmosClient (Cosmos.Endpoint, Cosmos.Key);Microsoft.Azure.Cosmos.Database database = await cosmosClient.CreateDatabaseIfNotExistsAsync(\"SampleDB\");Container container = await database.CreateContainerIfNotExistsAsync(\"Persons\", \"/firstname\", 400); QueryDefinition queryDefinition = new QueryDefinition(\"SELECT * FROM c\"); FeedIterator<Person> queryResultSetIterator = container.GetItemQueryIterator<Person>(queryDefinition); List<Person> personEvents = new List<Person(); while (queryResultSetIterator.HasMoreResults){ FeedResponse<Person> currentResultSet = await queryResultSetIterator.ReadNextAsync();foreach (Person personEvent in currentResultSet){personEvents.Add(personEvent);}} personEvents", "e": 27727, "s": 26619, "text": null }, { "code": null, "e": 28024, "s": 27727, "text": "It then puts the query results in a list of person objects and outputs by simply adding it to the last line of code. It also triggers the notebook to start the data visualization feature. Also, note that we don’t have to insert the actual endpoint and key. These are already known by the system. " }, { "code": null, "e": 28092, "s": 28024, "text": "Step 7: Now let’s run this. This results in a table with the data. " }, { "code": null, "e": 28298, "s": 28092, "text": "We can also switch to other views of the data. The workspace also contains a gallery. This gallery contains example notebooks that you can browse and download to your workspace to play with and learn from." }, { "code": null, "e": 28536, "s": 28298, "text": "The Azure Cosmos DB .NET SDK enables you to manage your Azure Cosmos DB and interact with its data. You can use the SDK in intelligent notebooks within Azure Cosmos DB that enable you to run code at descriptive texts and visualize data. " }, { "code": null, "e": 28551, "s": 28536, "text": "azure-cosmosdb" }, { "code": null, "e": 28567, "s": 28551, "text": "Cloud-Computing" }, { "code": null, "e": 28583, "s": 28567, "text": "Microsoft Azure" }, { "code": null, "e": 28681, "s": 28583, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28690, "s": 28681, "text": "Comments" }, { "code": null, "e": 28703, "s": 28690, "text": "Old Comments" }, { "code": null, "e": 28765, "s": 28703, "text": "Microsoft Azure - KQL Query to Get the VM Computer Properties" }, { "code": null, "e": 28827, "s": 28765, "text": "Microsoft Azure - Query System Event Log Data Using Azure KQL" }, { "code": null, "e": 28878, "s": 28827, "text": "Microsoft Azure - Rebooting an Application Gateway" }, { "code": null, "e": 28947, "s": 28878, "text": "Microsoft Azure - Graph Query to Get Properties of Azure VM Resource" }, { "code": null, "e": 29024, "s": 28947, "text": "Microsoft Azure - Enabling Logs for Troubleshooting the Azure Firewall Rules" }, { "code": null, "e": 29073, "s": 29024, "text": "Microsoft Azure - Enable IIS Logs for Monitoring" }, { "code": null, "e": 29120, "s": 29073, "text": "Microsoft Azure - Using the Azure Activity Log" }, { "code": null, "e": 29162, "s": 29120, "text": "Microsoft Azure - Deploy a Static Web App" }, { "code": null, "e": 29215, "s": 29162, "text": "Microsoft Azure - Using Deployment Slots For Web App" } ]
Entity Framework - Multiple DbContext
In this chapter, we will be learning how to migrate changes into the database when there are multiple DbContext classes in the application. Multiple DbContext was first introduced in Entity Framework 6.0. Multiple context classes may belong to a single database or two different databases. In our example, we will define two Context classes for the same database. In the following code, there are two DbContext classes for Student and Teacher. public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } } public class MyStudentContext : DbContext { public MyStudentContext() : base("UniContextDB") {} public virtual DbSet<Student> Students { get; set; } } public class Teacher { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime HireDate { get; set; } } public class MyTeacherContext : DbContext { public MyTeacherContext() : base("UniContextDB") {} public virtual DbSet<Teacher> Teachers { get; set; } } As you can see in the above code, there are two models called “Student” and “Teacher”. Each one is associated with a particular corresponding context class, i.e., Student is associated with MyStudentContext and Teacher is associated with MyTeacherContext. Here is the basic rule to migrate changes in database, when there are multiple Context classes within the same project. enable-migrations -ContextTypeName <DbContext-Name-with-Namespaces> MigrationsDirectory:<Migrations-Directory-Name> enable-migrations -ContextTypeName <DbContext-Name-with-Namespaces> MigrationsDirectory:<Migrations-Directory-Name> Add-Migration -configuration <DbContext-Migrations-Configuration-Class-withNamespaces> <Migrations-Name> Add-Migration -configuration <DbContext-Migrations-Configuration-Class-withNamespaces> <Migrations-Name> Update-Database -configuration <DbContext-Migrations-Configuration-Class-withNamespaces> -Verbose Update-Database -configuration <DbContext-Migrations-Configuration-Class-withNamespaces> -Verbose Let’s enable migration for MyStudentContext by executing the following command in Package Manager Console. PM→ enable-migrations -ContextTypeName:EFCodeFirstDemo.MyStudentContext Once it is executed, we will add the model in the migration history and for that, we have to fire add-migration command in the same console. PM→ add-migration -configuration EFCodeFirstDemo.Migrations.Configuration Initial Let us now add some data into Students and Teachers tables in the database. static void Main(string[] args) { using (var context = new MyStudentContext()) { //// Create and save a new Students Console.WriteLine("Adding new students"); var student = new Student { FirstMidName = "Alain", LastName = "Bomer", EnrollmentDate = DateTime.Parse(DateTime.Today.ToString()) //Age = 24 }; context.Students.Add(student); var student1 = new Student { FirstMidName = "Mark", LastName = "Upston", EnrollmentDate = DateTime.Parse(DateTime.Today.ToString()) //Age = 30 }; context.Students.Add(student1); context.SaveChanges(); // Display all Students from the database var students = (from s in context.Students orderby s.FirstMidName select s).ToList<Student>(); Console.WriteLine("Retrieve all Students from the database:"); foreach (var stdnt in students) { string name = stdnt.FirstMidName + " " + stdnt.LastName; Console.WriteLine("ID: {0}, Name: {1}", stdnt.ID, name); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } using (var context = new MyTeacherContext()) { //// Create and save a new Teachers Console.WriteLine("Adding new teachers"); var student = new Teacher { FirstMidName = "Alain", LastName = "Bomer", HireDate = DateTime.Parse(DateTime.Today.ToString()) //Age = 24 }; context.Teachers.Add(student); var student1 = new Teacher { FirstMidName = "Mark", LastName = "Upston", HireDate = DateTime.Parse(DateTime.Today.ToString()) //Age = 30 }; context.Teachers.Add(student1); context.SaveChanges(); // Display all Teachers from the database var teachers = (from t in context.Teachers orderby t.FirstMidName select t).ToList<Teacher>(); Console.WriteLine("Retrieve all teachers from the database:"); foreach (var teacher in teachers) { string name = teacher.FirstMidName + " " + teacher.LastName; Console.WriteLine("ID: {0}, Name: {1}", teacher.ID, name); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } } When the above code is executed, you will see that two different tables are created for two different models as shown in the following image. We recommend that you execute the above example in a step-by-step manner for better understanding. 19 Lectures 5 hours Trevoir Williams 33 Lectures 3.5 hours Nilay Mehta 21 Lectures 2.5 hours TELCOMA Global 89 Lectures 7.5 hours Mustafa Radaideh Print Add Notes Bookmark this page
[ { "code": null, "e": 3172, "s": 3032, "text": "In this chapter, we will be learning how to migrate changes into the database when there are multiple DbContext classes in the application." }, { "code": null, "e": 3237, "s": 3172, "text": "Multiple DbContext was first introduced in Entity Framework 6.0." }, { "code": null, "e": 3322, "s": 3237, "text": "Multiple context classes may belong to a single database or two different databases." }, { "code": null, "e": 3476, "s": 3322, "text": "In our example, we will define two Context classes for the same database. In the following code, there are two DbContext classes for Student and Teacher." }, { "code": null, "e": 4163, "s": 3476, "text": "public class Student {\n public int ID { get; set; }\n public string LastName { get; set; }\n public string FirstMidName { get; set; }\n public DateTime EnrollmentDate { get; set; }\n}\n\npublic class MyStudentContext : DbContext {\n public MyStudentContext() : base(\"UniContextDB\") {}\n public virtual DbSet<Student> Students { get; set; }\n}\n\npublic class Teacher {\n public int ID { get; set; }\n public string LastName { get; set; }\n public string FirstMidName { get; set; }\n public DateTime HireDate { get; set; }\n}\n\npublic class MyTeacherContext : DbContext {\n public MyTeacherContext() : base(\"UniContextDB\") {}\n public virtual DbSet<Teacher> Teachers { get; set; }\n}" }, { "code": null, "e": 4419, "s": 4163, "text": "As you can see in the above code, there are two models called “Student” and “Teacher”. Each one is associated with a particular corresponding context class, i.e., Student is associated with MyStudentContext and Teacher is associated with MyTeacherContext." }, { "code": null, "e": 4539, "s": 4419, "text": "Here is the basic rule to migrate changes in database, when there are multiple Context classes within the same project." }, { "code": null, "e": 4655, "s": 4539, "text": "enable-migrations -ContextTypeName <DbContext-Name-with-Namespaces> MigrationsDirectory:<Migrations-Directory-Name>" }, { "code": null, "e": 4771, "s": 4655, "text": "enable-migrations -ContextTypeName <DbContext-Name-with-Namespaces> MigrationsDirectory:<Migrations-Directory-Name>" }, { "code": null, "e": 4876, "s": 4771, "text": "Add-Migration -configuration <DbContext-Migrations-Configuration-Class-withNamespaces> <Migrations-Name>" }, { "code": null, "e": 4981, "s": 4876, "text": "Add-Migration -configuration <DbContext-Migrations-Configuration-Class-withNamespaces> <Migrations-Name>" }, { "code": null, "e": 5079, "s": 4981, "text": "Update-Database -configuration <DbContext-Migrations-Configuration-Class-withNamespaces> -Verbose" }, { "code": null, "e": 5177, "s": 5079, "text": "Update-Database -configuration <DbContext-Migrations-Configuration-Class-withNamespaces> -Verbose" }, { "code": null, "e": 5284, "s": 5177, "text": "Let’s enable migration for MyStudentContext by executing the following command in Package Manager Console." }, { "code": null, "e": 5357, "s": 5284, "text": "PM→ enable-migrations -ContextTypeName:EFCodeFirstDemo.MyStudentContext\n" }, { "code": null, "e": 5498, "s": 5357, "text": "Once it is executed, we will add the model in the migration history and for that, we have to fire add-migration command in the same console." }, { "code": null, "e": 5581, "s": 5498, "text": "PM→ add-migration -configuration EFCodeFirstDemo.Migrations.Configuration Initial\n" }, { "code": null, "e": 5657, "s": 5581, "text": "Let us now add some data into Students and Teachers tables in the database." }, { "code": null, "e": 7967, "s": 5657, "text": "static void Main(string[] args) {\n\n using (var context = new MyStudentContext()) {\n\t\n //// Create and save a new Students\n Console.WriteLine(\"Adding new students\");\n\n var student = new Student {\n FirstMidName = \"Alain\", \n LastName = \"Bomer\", \n EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())\n //Age = 24\n };\n\n context.Students.Add(student);\n\n var student1 = new Student {\n FirstMidName = \"Mark\",\n LastName = \"Upston\", \n EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())\n //Age = 30\n };\n\n context.Students.Add(student1);\n context.SaveChanges();\n\t\t\n // Display all Students from the database\n var students = (from s in context.Students orderby s.FirstMidName\n select s).ToList<Student>();\n\t\t\n Console.WriteLine(\"Retrieve all Students from the database:\");\n\n foreach (var stdnt in students) {\n string name = stdnt.FirstMidName + \" \" + stdnt.LastName;\n Console.WriteLine(\"ID: {0}, Name: {1}\", stdnt.ID, name);\n }\n\n Console.WriteLine(\"Press any key to exit...\");\n Console.ReadKey();\n }\n\n using (var context = new MyTeacherContext()) {\n\n //// Create and save a new Teachers\n Console.WriteLine(\"Adding new teachers\");\n\n var student = new Teacher {\n FirstMidName = \"Alain\", \n LastName = \"Bomer\", \n HireDate = DateTime.Parse(DateTime.Today.ToString())\n //Age = 24\n };\n\n context.Teachers.Add(student);\n\n var student1 = new Teacher {\n FirstMidName = \"Mark\", \n LastName = \"Upston\", \n HireDate = DateTime.Parse(DateTime.Today.ToString())\n //Age = 30\n };\n\n context.Teachers.Add(student1);\n context.SaveChanges();\n \n // Display all Teachers from the database\n var teachers = (from t in context.Teachers orderby t.FirstMidName\n select t).ToList<Teacher>();\n\t\t\n Console.WriteLine(\"Retrieve all teachers from the database:\");\n\n foreach (var teacher in teachers) {\n string name = teacher.FirstMidName + \" \" + teacher.LastName;\n Console.WriteLine(\"ID: {0}, Name: {1}\", teacher.ID, name);\n }\n\n Console.WriteLine(\"Press any key to exit...\");\n Console.ReadKey();\n }\n}" }, { "code": null, "e": 8109, "s": 7967, "text": "When the above code is executed, you will see that two different tables are created for two different models as shown in the following image." }, { "code": null, "e": 8208, "s": 8109, "text": "We recommend that you execute the above example in a step-by-step manner for better understanding." }, { "code": null, "e": 8241, "s": 8208, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 8259, "s": 8241, "text": " Trevoir Williams" }, { "code": null, "e": 8294, "s": 8259, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8307, "s": 8294, "text": " Nilay Mehta" }, { "code": null, "e": 8342, "s": 8307, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8358, "s": 8342, "text": " TELCOMA Global" }, { "code": null, "e": 8393, "s": 8358, "text": "\n 89 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8411, "s": 8393, "text": " Mustafa Radaideh" }, { "code": null, "e": 8418, "s": 8411, "text": " Print" }, { "code": null, "e": 8429, "s": 8418, "text": " Add Notes" } ]
How to create 2-ValueTuple in C#? - GeeksforGeeks
23 Jul, 2019 In C#, a pair or 2 value tuple is a value type tuple which holds two elements in it. You can create a pair of value tuple using two different ways: Using ValueTuple <T1, T2>(T1, T2) ConstructorUsing Create <T1, T2>(T1, T2) Method Using ValueTuple <T1, T2>(T1, T2) Constructor Using Create <T1, T2>(T1, T2) Method You can create a pair value tuple by using ValueTuple <T1, T2>(T1, T2) constructor. It initializes a new instance of the ValueTuple <T1, T2> struct. But when you create a value tuple using this constructor, then you have to specify the type of the element stored in the value tuple. Syntax: public ValueTuple (T1 item1, T2 item2); Parameters: item1: It is the value of the first value tuple component. item2: It is the value of the second value tuple component. Example: // C# program to create a pair ValueTuple// using value tuple constructorusing System; class GFG { // Main method static public void Main() { // Creating a value tuple with two elements // Using ValueTuple<T1, T2>(T1, T2) constructor ValueTuple<string, string> MyTpl = new ValueTuple<string, string>("Geeks", "GFG"); Console.WriteLine("Component 1: " + MyTpl.Item1); Console.WriteLine("Component 2: " + MyTpl.Item2); }} Component 1: Geeks Component 2: GFG You can also create a pair value tuple with the help of Create <T1, T2>(T1, T2) method. When you use this method, then there is no need to specify the type of the elements stored in the value tuple. Syntax: public static ValueTuple<T1, T2> Create<T1, T2> (T1 item1, T2 item2); Type Parameters: T1: It is the type of the value tuple’s first component. T2: It is the type of the value tuple’s second component. Parameters: item1: It is the value of the value tuple’s first component. item2: It is the value of the value tuple’s second component. Returns: This method returns a value tuple with two elements. Example: // C# program to create a pair value tuple// using Create<T1, T2>(T1, T2) methodusing System; public class GFG { // Main method static public void Main() { // Creating a value tuple with two elements // Using Create<T1, T2>(T1, T2) method var MyTple = ValueTuple.Create("Geeks123", "gfg"); Console.WriteLine("Component 1: " + MyTple.Item1); Console.WriteLine("Component 2: " + MyTple.Item2); }} Component 1: Geeks123 Component 2: gfg Reference: https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple-2.-ctor?view=netframework-4.8 https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple.create?view=netframework-4.8#System_ValueTuple_Create__2___0___1_ CSharp-ValueTuple C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples C# | Method Overriding C# | Class and Object C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Constructors C# | Delegates Introduction to .NET Framework Difference between Ref and Out keywords in C# C# | Data Types
[ { "code": null, "e": 24012, "s": 23984, "text": "\n23 Jul, 2019" }, { "code": null, "e": 24160, "s": 24012, "text": "In C#, a pair or 2 value tuple is a value type tuple which holds two elements in it. You can create a pair of value tuple using two different ways:" }, { "code": null, "e": 24242, "s": 24160, "text": "Using ValueTuple <T1, T2>(T1, T2) ConstructorUsing Create <T1, T2>(T1, T2) Method" }, { "code": null, "e": 24288, "s": 24242, "text": "Using ValueTuple <T1, T2>(T1, T2) Constructor" }, { "code": null, "e": 24325, "s": 24288, "text": "Using Create <T1, T2>(T1, T2) Method" }, { "code": null, "e": 24608, "s": 24325, "text": "You can create a pair value tuple by using ValueTuple <T1, T2>(T1, T2) constructor. It initializes a new instance of the ValueTuple <T1, T2> struct. But when you create a value tuple using this constructor, then you have to specify the type of the element stored in the value tuple." }, { "code": null, "e": 24616, "s": 24608, "text": "Syntax:" }, { "code": null, "e": 24656, "s": 24616, "text": "public ValueTuple (T1 item1, T2 item2);" }, { "code": null, "e": 24668, "s": 24656, "text": "Parameters:" }, { "code": null, "e": 24727, "s": 24668, "text": "item1: It is the value of the first value tuple component." }, { "code": null, "e": 24787, "s": 24727, "text": "item2: It is the value of the second value tuple component." }, { "code": null, "e": 24796, "s": 24787, "text": "Example:" }, { "code": "// C# program to create a pair ValueTuple// using value tuple constructorusing System; class GFG { // Main method static public void Main() { // Creating a value tuple with two elements // Using ValueTuple<T1, T2>(T1, T2) constructor ValueTuple<string, string> MyTpl = new ValueTuple<string, string>(\"Geeks\", \"GFG\"); Console.WriteLine(\"Component 1: \" + MyTpl.Item1); Console.WriteLine(\"Component 2: \" + MyTpl.Item2); }}", "e": 25311, "s": 24796, "text": null }, { "code": null, "e": 25348, "s": 25311, "text": "Component 1: Geeks\nComponent 2: GFG\n" }, { "code": null, "e": 25547, "s": 25348, "text": "You can also create a pair value tuple with the help of Create <T1, T2>(T1, T2) method. When you use this method, then there is no need to specify the type of the elements stored in the value tuple." }, { "code": null, "e": 25555, "s": 25547, "text": "Syntax:" }, { "code": null, "e": 25625, "s": 25555, "text": "public static ValueTuple<T1, T2> Create<T1, T2> (T1 item1, T2 item2);" }, { "code": null, "e": 25642, "s": 25625, "text": "Type Parameters:" }, { "code": null, "e": 25699, "s": 25642, "text": "T1: It is the type of the value tuple’s first component." }, { "code": null, "e": 25757, "s": 25699, "text": "T2: It is the type of the value tuple’s second component." }, { "code": null, "e": 25769, "s": 25757, "text": "Parameters:" }, { "code": null, "e": 25830, "s": 25769, "text": "item1: It is the value of the value tuple’s first component." }, { "code": null, "e": 25892, "s": 25830, "text": "item2: It is the value of the value tuple’s second component." }, { "code": null, "e": 25954, "s": 25892, "text": "Returns: This method returns a value tuple with two elements." }, { "code": null, "e": 25963, "s": 25954, "text": "Example:" }, { "code": "// C# program to create a pair value tuple// using Create<T1, T2>(T1, T2) methodusing System; public class GFG { // Main method static public void Main() { // Creating a value tuple with two elements // Using Create<T1, T2>(T1, T2) method var MyTple = ValueTuple.Create(\"Geeks123\", \"gfg\"); Console.WriteLine(\"Component 1: \" + MyTple.Item1); Console.WriteLine(\"Component 2: \" + MyTple.Item2); }}", "e": 26412, "s": 25963, "text": null }, { "code": null, "e": 26452, "s": 26412, "text": "Component 1: Geeks123\nComponent 2: gfg\n" }, { "code": null, "e": 26463, "s": 26452, "text": "Reference:" }, { "code": null, "e": 26555, "s": 26463, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple-2.-ctor?view=netframework-4.8" }, { "code": null, "e": 26683, "s": 26555, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple.create?view=netframework-4.8#System_ValueTuple_Create__2___0___1_" }, { "code": null, "e": 26701, "s": 26683, "text": "CSharp-ValueTuple" }, { "code": null, "e": 26704, "s": 26701, "text": "C#" }, { "code": null, "e": 26802, "s": 26704, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26811, "s": 26802, "text": "Comments" }, { "code": null, "e": 26824, "s": 26811, "text": "Old Comments" }, { "code": null, "e": 26852, "s": 26824, "text": "C# Dictionary with examples" }, { "code": null, "e": 26875, "s": 26852, "text": "C# | Method Overriding" }, { "code": null, "e": 26897, "s": 26875, "text": "C# | Class and Object" }, { "code": null, "e": 26937, "s": 26897, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 26960, "s": 26937, "text": "Extension Method in C#" }, { "code": null, "e": 26978, "s": 26960, "text": "C# | Constructors" }, { "code": null, "e": 26993, "s": 26978, "text": "C# | Delegates" }, { "code": null, "e": 27024, "s": 26993, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27070, "s": 27024, "text": "Difference between Ref and Out keywords in C#" } ]
Draw a filled polygon using the OpenCV function fillPoly() - GeeksforGeeks
04 Jan, 2022 fillPoly() function of OpenCV is used to draw filled polygons like rectangle, triangle, pentagon over an image. This function takes inputs an image and endpoints of Polygon and color. Syntax: cv2.fillpoly(Image,End_Points,Color) Parameter: Image: This is image on which we want draw filled polygon End_Points: Points of polygon(for triangle 3 end points, for rectangle 4 end points will be there) Color: It specifies the color of polygon In this example we will draw filled polygon triangle by giving 3 endpoints such as [160,130],[350,130],[250,300] to fillPoly() function. Input Image: Code: Python3 # Import necessary librariesimport cv2import numpy as np # Read an imageimg = cv2.imread("image.png") # Define an array of endpoints of trianglepoints = np.array([[160, 130], [350, 130], [250, 300]]) # Use fillPoly() function and give input as# image, end points,color of polygon# Here color of polygon will bluecv2.fillPoly(img, pts=[points], color=(255, 0, 0)) # Displaying the imagecv2.imshow("Triangle", img) # wait for the user to press any key to # exit windowcv2.waitKey(0) # Closing all open windowscv2.destroyAllWindows() Output: In this example we will draw a hexagon by giving 6 endpoints such as [220,120],[130,200],[130,300],[220,380],[310,300],[310,200] to fillPoly() function. Input: Code: Python3 # Import necessary librariesimport cv2import numpy as np # Read an imageimg = cv2.imread("image.png") # Define an array of endpoints of Hexagonpoints = np.array([[220, 120], [130, 200], [130, 300], [220, 380], [310, 300], [310, 200]]) # Use fillPoly() function and give input as image,# end points,color of polygon# Here color of polygon will be greencv2.fillPoly(img, pts=[points], color=(0, 255, 0)) # Displaying the imagecv2.imshow("Hexagon", img) # wait for the user to press any key to # exit windowcv2.waitKey(0) # Closing all open windowscv2.destroyAllWindows() Output: Sometimes there is a requirement that we need to show photos of someone by hiding their faces. In this case, we can use this function to hide the face of a person. Input: Code: Python3 # Import necessary librariesimport cv2import numpy as np # Read an imageimg = cv2.imread("Documents/Person_Image.jpg", cv2.IMREAD_COLOR) # Define an array of endpoints of Rectanglepoints = np.array([[300, 180], [400, 180], [400, 280], [300, 280]]) # Use fillPoly() function and give input as image,# end points,color of polygon# Here color of polygon will be redcv2.fillPoly(img, pts=[points], color=(0, 0, 255)) # Displaying the imagecv2.imshow("Rectangle", img) # wait for the user to press any key to exit windowcv2.waitKey(0) # Closing all open windowscv2.destroyAllWindows() Output: Picked Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Python | Get dictionary keys as a list Bar Plot in Matplotlib Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method loops in python Python - Call function from another file Ways to filter Pandas DataFrame by column values Python | Convert set into a list Python program to find number of days between two given dates
[ { "code": null, "e": 23901, "s": 23873, "text": "\n04 Jan, 2022" }, { "code": null, "e": 24085, "s": 23901, "text": "fillPoly() function of OpenCV is used to draw filled polygons like rectangle, triangle, pentagon over an image. This function takes inputs an image and endpoints of Polygon and color." }, { "code": null, "e": 24130, "s": 24085, "text": "Syntax: cv2.fillpoly(Image,End_Points,Color)" }, { "code": null, "e": 24141, "s": 24130, "text": "Parameter:" }, { "code": null, "e": 24199, "s": 24141, "text": "Image: This is image on which we want draw filled polygon" }, { "code": null, "e": 24298, "s": 24199, "text": "End_Points: Points of polygon(for triangle 3 end points, for rectangle 4 end points will be there)" }, { "code": null, "e": 24339, "s": 24298, "text": "Color: It specifies the color of polygon" }, { "code": null, "e": 24476, "s": 24339, "text": "In this example we will draw filled polygon triangle by giving 3 endpoints such as [160,130],[350,130],[250,300] to fillPoly() function." }, { "code": null, "e": 24489, "s": 24476, "text": "Input Image:" }, { "code": null, "e": 24495, "s": 24489, "text": "Code:" }, { "code": null, "e": 24503, "s": 24495, "text": "Python3" }, { "code": "# Import necessary librariesimport cv2import numpy as np # Read an imageimg = cv2.imread(\"image.png\") # Define an array of endpoints of trianglepoints = np.array([[160, 130], [350, 130], [250, 300]]) # Use fillPoly() function and give input as# image, end points,color of polygon# Here color of polygon will bluecv2.fillPoly(img, pts=[points], color=(255, 0, 0)) # Displaying the imagecv2.imshow(\"Triangle\", img) # wait for the user to press any key to # exit windowcv2.waitKey(0) # Closing all open windowscv2.destroyAllWindows()", "e": 25040, "s": 24503, "text": null }, { "code": null, "e": 25048, "s": 25040, "text": "Output:" }, { "code": null, "e": 25201, "s": 25048, "text": "In this example we will draw a hexagon by giving 6 endpoints such as [220,120],[130,200],[130,300],[220,380],[310,300],[310,200] to fillPoly() function." }, { "code": null, "e": 25208, "s": 25201, "text": "Input:" }, { "code": null, "e": 25214, "s": 25208, "text": "Code:" }, { "code": null, "e": 25222, "s": 25214, "text": "Python3" }, { "code": "# Import necessary librariesimport cv2import numpy as np # Read an imageimg = cv2.imread(\"image.png\") # Define an array of endpoints of Hexagonpoints = np.array([[220, 120], [130, 200], [130, 300], [220, 380], [310, 300], [310, 200]]) # Use fillPoly() function and give input as image,# end points,color of polygon# Here color of polygon will be greencv2.fillPoly(img, pts=[points], color=(0, 255, 0)) # Displaying the imagecv2.imshow(\"Hexagon\", img) # wait for the user to press any key to # exit windowcv2.waitKey(0) # Closing all open windowscv2.destroyAllWindows()", "e": 25815, "s": 25222, "text": null }, { "code": null, "e": 25823, "s": 25815, "text": "Output:" }, { "code": null, "e": 25987, "s": 25823, "text": "Sometimes there is a requirement that we need to show photos of someone by hiding their faces. In this case, we can use this function to hide the face of a person." }, { "code": null, "e": 25994, "s": 25987, "text": "Input:" }, { "code": null, "e": 26000, "s": 25994, "text": "Code:" }, { "code": null, "e": 26008, "s": 26000, "text": "Python3" }, { "code": "# Import necessary librariesimport cv2import numpy as np # Read an imageimg = cv2.imread(\"Documents/Person_Image.jpg\", cv2.IMREAD_COLOR) # Define an array of endpoints of Rectanglepoints = np.array([[300, 180], [400, 180], [400, 280], [300, 280]]) # Use fillPoly() function and give input as image,# end points,color of polygon# Here color of polygon will be redcv2.fillPoly(img, pts=[points], color=(0, 0, 255)) # Displaying the imagecv2.imshow(\"Rectangle\", img) # wait for the user to press any key to exit windowcv2.waitKey(0) # Closing all open windowscv2.destroyAllWindows()", "e": 26630, "s": 26008, "text": null }, { "code": null, "e": 26638, "s": 26630, "text": "Output:" }, { "code": null, "e": 26645, "s": 26638, "text": "Picked" }, { "code": null, "e": 26659, "s": 26645, "text": "Python-OpenCV" }, { "code": null, "e": 26666, "s": 26659, "text": "Python" }, { "code": null, "e": 26764, "s": 26666, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26773, "s": 26764, "text": "Comments" }, { "code": null, "e": 26786, "s": 26773, "text": "Old Comments" }, { "code": null, "e": 26822, "s": 26786, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 26861, "s": 26822, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26884, "s": 26861, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26935, "s": 26884, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 26967, "s": 26935, "text": "Python Dictionary keys() method" }, { "code": null, "e": 26983, "s": 26967, "text": "loops in python" }, { "code": null, "e": 27024, "s": 26983, "text": "Python - Call function from another file" }, { "code": null, "e": 27073, "s": 27024, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 27106, "s": 27073, "text": "Python | Convert set into a list" } ]
Euler Totient | Practice | GeeksforGeeks
Consider Ø(n) as the Euler Totient Function for n. You will be given a positive integer N and you have to find the smallest positive integer n, n <= N for which the ratio n/Ø(n) is maximized. Example 1: Input: N = 6 Output: 6 Explanation: For n = 1, 2, 3, 4, 5 and 6 the values of the ratio are 1, 2, 1.5, 2, 1.25 and 3 respectively. The maximum is obtained at 6. Example 2: Input: N = 50 Output: 30 Explanation: For n = 1 to 50, the maximum value of the ratio is 3.75 which is obtained at n = 30. Your Task: You don't need to read input or print anything. Your task is to complete the function maximizeEulerRatio() which takes an Integer N as input and returns the smallest positive integer (<= N) which maximizes the ratio n/Ø(n) is maximized. Expected Time Complexity: O(constant) Expected Auxiliary Space: O(constant) Constraints: 1 <= N <= 1012 0 Debarshi Maitra1 year ago Debarshi Maitra O(1) Solution : https://ide.geeksforgeeks.o... 0 Rahul Raj2 years ago Rahul Raj CPP 0.01 Solutionhttps://ide.geeksforgeeks.o... 0 Kartik Bhatia2 years ago Kartik Bhatia if any one can approach his approach ? 0 Surya Prakash Reddy4 years ago Surya Prakash Reddy 0.01 Solution...https://ide.geeksforgeeks.o... 0 Rishabh Acharya This comment was deleted. 0 Hemant Dhanuka4 years ago Hemant Dhanuka on solving equation, u have to minimize product of ( (p-1)/p) where p is prime no which divides n 0 Dipta Ghosh5 years ago Dipta Ghosh http://code.geeksforgeeks.o... Run time error on submission , but giving correct o/p. 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": 430, "s": 238, "text": "Consider Ø(n) as the Euler Totient Function for n. You will be given a positive integer N and you have to find the smallest positive integer n, n <= N for which the ratio n/Ø(n) is maximized." }, { "code": null, "e": 443, "s": 432, "text": "Example 1:" }, { "code": null, "e": 604, "s": 443, "text": "Input:\nN = 6\nOutput:\n6\nExplanation:\nFor n = 1, 2, 3, 4, 5 and 6 the values of\nthe ratio are 1, 2, 1.5, 2, 1.25 and 3\nrespectively. The maximum is obtained at 6." }, { "code": null, "e": 615, "s": 604, "text": "Example 2:" }, { "code": null, "e": 738, "s": 615, "text": "Input:\nN = 50\nOutput:\n30\nExplanation:\nFor n = 1 to 50, the maximum value of the\nratio is 3.75 which is obtained at n = 30." }, { "code": null, "e": 988, "s": 740, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function maximizeEulerRatio() which takes an Integer N as input and returns the smallest positive integer (<= N) which maximizes the ratio n/Ø(n) is maximized." }, { "code": null, "e": 1066, "s": 990, "text": "Expected Time Complexity: O(constant)\nExpected Auxiliary Space: O(constant)" }, { "code": null, "e": 1096, "s": 1068, "text": "Constraints:\n1 <= N <= 1012" }, { "code": null, "e": 1098, "s": 1096, "text": "0" }, { "code": null, "e": 1124, "s": 1098, "text": "Debarshi Maitra1 year ago" }, { "code": null, "e": 1140, "s": 1124, "text": "Debarshi Maitra" }, { "code": null, "e": 1187, "s": 1140, "text": "O(1) Solution : https://ide.geeksforgeeks.o..." }, { "code": null, "e": 1189, "s": 1187, "text": "0" }, { "code": null, "e": 1210, "s": 1189, "text": "Rahul Raj2 years ago" }, { "code": null, "e": 1220, "s": 1210, "text": "Rahul Raj" }, { "code": null, "e": 1268, "s": 1220, "text": "CPP 0.01 Solutionhttps://ide.geeksforgeeks.o..." }, { "code": null, "e": 1270, "s": 1268, "text": "0" }, { "code": null, "e": 1295, "s": 1270, "text": "Kartik Bhatia2 years ago" }, { "code": null, "e": 1309, "s": 1295, "text": "Kartik Bhatia" }, { "code": null, "e": 1348, "s": 1309, "text": "if any one can approach his approach ?" }, { "code": null, "e": 1350, "s": 1348, "text": "0" }, { "code": null, "e": 1381, "s": 1350, "text": "Surya Prakash Reddy4 years ago" }, { "code": null, "e": 1401, "s": 1381, "text": "Surya Prakash Reddy" }, { "code": null, "e": 1448, "s": 1401, "text": "0.01 Solution...https://ide.geeksforgeeks.o..." }, { "code": null, "e": 1450, "s": 1448, "text": "0" }, { "code": null, "e": 1466, "s": 1450, "text": "Rishabh Acharya" }, { "code": null, "e": 1492, "s": 1466, "text": "This comment was deleted." }, { "code": null, "e": 1494, "s": 1492, "text": "0" }, { "code": null, "e": 1520, "s": 1494, "text": "Hemant Dhanuka4 years ago" }, { "code": null, "e": 1535, "s": 1520, "text": "Hemant Dhanuka" }, { "code": null, "e": 1633, "s": 1535, "text": "on solving equation, u have to minimize product of ( (p-1)/p) where p is prime no which divides n" }, { "code": null, "e": 1635, "s": 1633, "text": "0" }, { "code": null, "e": 1658, "s": 1635, "text": "Dipta Ghosh5 years ago" }, { "code": null, "e": 1670, "s": 1658, "text": "Dipta Ghosh" }, { "code": null, "e": 1701, "s": 1670, "text": "http://code.geeksforgeeks.o..." }, { "code": null, "e": 1756, "s": 1701, "text": "Run time error on submission , but giving correct o/p." }, { "code": null, "e": 1902, "s": 1756, "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": 1938, "s": 1902, "text": " Login to access your submissions. " }, { "code": null, "e": 1948, "s": 1938, "text": "\nProblem\n" }, { "code": null, "e": 1958, "s": 1948, "text": "\nContest\n" }, { "code": null, "e": 2021, "s": 1958, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2169, "s": 2021, "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": 2377, "s": 2169, "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": 2483, "s": 2377, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Automating Emails in Apache Airflow: A How-To Guide | by Zach Alexander | Towards Data Science
As a Data Engineer, some of the work I do involves automating data pulls at regular intervals from third-party sources for various teams at the organization. Although I like to think staff are always aware of when a new data pull occurs (ha!), I can’t expect them to remember each time it happens. Because of this, Apache Airflow has been a great service to help send e-mail reminders to interested parties when a data pipeline has completed and a new dataset has been processed. Airflow not only does a great job orchestrating the data pull itself but works well with Python libraries (such as SMTP) to facilitate the transfer of the email to the proper recipient(s). In this quick guide below, I’ll walk you through setting up your first directed acyclic graph (DAG) in Apache Airflow that orchestrates this e-mail automation process! If you don’t know what Apache Airflow is, feel free to first read through these resources below to get a better sense of some of its use cases. Official Airflow Documentation: https://airflow.apache.org/docs/apache-airflow/stable/index.html A Good Medium Post on Airflow: https://medium.com/swlh/apache-airflow-in-5-minutes-c005b4b11b26 Mainly, you’ll want to have a basic understanding of tasks, operators, and Airflow’s file structure. Additionally, e-mail automation in Python with SMTP depends on a properly configured sender e-mail address. Although many different e-mail providers can be used, I’ve found that Gmail makes it very easy. In order for the sender e-mail to operate correctly with SMTP and Python, you’ll need to follow the instructions here (under the Option 1: Setting Up A Gmail Account for Development). This should be a pretty quick step, where you’ll need to change one of your security settings to “Allow less secure apps to ON”. When both prerequisites are met, you’ll then want to tackle installing Airflow on your local machine (if you haven’t already). If/when you feel comfortable with Airflow, you’ll then want to make sure it’s installed locally. If you need some help with this process, here are a few starters for local installations: Installation on Mac: https://arpitrana.medium.com/install-airflow-on-macos-guide-fc66399b2a9e Installation via Docker: https://medium.com/@itunpredictable/apache-airflow-on-docker-for-complete-beginners-cf76cf7b2c9a Installation on Windows 10: https://medium.com/@ryanroline/installing-apache-airflow-on-windows-10-5247aa1249ef As a quick note, if you are planning to install Airflow on Windows (without Docker), you’ll need to create a Linux subsystem. The instructions should be helpful in the guide above, but it might take a bit of configuration with your local setup to get this working. Once you have Airflow installed, and you have a good handle on the software itself, we can get started. If you haven’t already, spin up your webserver by running the following command in a terminal window: airflow webserver Additionally, you can spin up the Airflow scheduler in a separate terminal window: airflow scheduler You should then be able to navigate to http://localhost:8080 (or whichever endpoint you’ve configured for your local webserver), and find your UI. To avoid duplication with other posts, and to cut down on the length of the article, I won’t go into detail about uploading dags. Ultimately, when you spin up the webserver you should see your dags load into the UI if your directory and environment are structured correctly. If you are spinning up your webserver for the first time, you may see some sample dags in the UI if you configured this option in your airflow.cfg file. Now, with the webserver running on your local machine, we can create the DAG that’ll send an e-mail. To help guide you through this process, I’ve posted my DAG file on GitHub: https://github.com/zachalexander/airflow-medium-post Feel free to clone the repository and work through this simultaneously, or read through the guide below and then use the code to integrate this into your DAGs later on! Important Note: For those that are already using Airflow regularly, since the DAG file contains a just a few functions, you can integrate these into any pipeline you already have set up (and add it on as a task). However, for the sake of this walkthrough, I’ll create this as a separate, one-step dag for simplicity. To create our e-mail automation DAG, we can navigate to the dags folder in your Airflow project, which should be structured similar to my GitHub repo. You can either use my existing “email_automation.py” file or you can create your own blank python file. An example of the directory structure is below: airflow dags/ email_automation.py Inside of this python file, you can add the following imports at the top: from airflow import DAGfrom airflow.operators.python_operator import PythonOperatorfrom datetime import timedeltaimport smtplib, sslfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipart The first import allows for DAG functionality in Airflow, and the second allows for Airflow’s Python Operator, which we’ll use to initiate the e-mail later on. Importing timedelta will help us regulate a timeout interval in the occurrence of our DAG taking too long to run (Airflow best practice). Then, we’ll import some e-mail and SMTP libraries that will be essential to sending the e-mail to our recipients. After this, we can then add our first function declaration, which is named send_email_basic(): def send_email_basic(sender, receiver, email_subject):port = 465 # For SSLsmtp_server = "smtp.gmail.com"sender_email = sender # Enter your addressreceiver_email = receiver # Enter receiver addresspassword = 'env variable' # Enter your gmail passwordemail_html = """<html> <body> <p>Hello!</p> <p>Add any text you'd like to the body of the e-mail here!</p> <br> </body></html>"""message = MIMEMultipart("multipart")# Turn these into plain/html MIMEText objectspart2 = MIMEText(email_html, "html")# Add HTML/plain-text parts to MIMEMultipart message# The email client will try to render the last part firstmessage.attach(part2)message["Subject"] = email_subjectmessage["From"] = sender_email## iterating through the receiver listfor i, val in enumerate(receiver):message["To"] = valcontext = ssl.create_default_context()with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:server.login(sender_email, password)server.sendmail(sender_email, receiver_email, message.as_string()) In this function, we are doing a few things: We are identifying the SSL port Identifying the SMTP server Storing the sender and recipient addresses in variables, as well as the sender’s e-mail password. Creating a text string that has the custom html for our e-mail body and saving it to a variable Identifying the e-mail as a “multipart” e-mail, and attaching the body text to our e-mail message Attaching a “subject” and “from” parameters to our message Iterating through our receiver list (in case of multiple recipients for the e-mail) to add to our “to” parameter of our message Connecting to our server and sending the e-mail with the message parameters for “to”, “from”, “subject” and “message”. Although there appears to be a lot to this, the function call is pretty straightforward. For more information about some of the e-mail jargon above, feel free to read up on this process here: https://realpython.com/python-send-email/ (same article as above for setting up your Gmail account as a proper sender). Next, we can declare our next function: def init_email():sender = "yourgmailaddress@gmail.com" # add the sender gmail address hererecipients = ["email address 1", "email address 2"] # add your e-mail recipients heresubject = "Subject Line" # add the subject of the e-mail you'd like heresend_email_basic(sender, recipients, subject) This function, init_email(), will be used by our Python Operator to trigger our e-mail in a bit. Here is a breakdown of what’s happening above: We are saving our sender address (which is the Gmail address you’ll use to send the e-mails from) in a sender variable We are saving our recipient addresses as a list in a recipients variable. Here, since we have set up a way to iterate through this list in our previous function, we can just list out our e-mail addresses in the list here. We are creating the text for our subject line and saving it to a subject variable Finally, we are going to add these variables as parameters to our initial send_email_basic() function Finally, we can set up our Airflow syntax to initialize this DAG and add the parameters needed: default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': 'trigger date', 'email': ['your Airflow email'], 'email_on_failure': True, 'email_on_retry': True, 'retries': 0}dag = DAG('email_automation', default_args=default_args, dagrun_timeout=timedelta(minutes=5), # schedule_interval = '0 13 * * 1', # if you want to set up an automation schedule you can do that here catchup=False)t1 = PythonOperator( task_id='send_email', python_callable=init_email, dag=dag)t1 Here we are doing the following: Creating our default arguments for our DAG, similar to the Airflow documentation. Creating our DAG(), naming it email_automation . Using the PythonOperator() to create a task, call our init_email python function. Assigning our task as t1 . Once this is ready to go, your DAG file should be all set! By running: airflow init db You should be able to now see a new dag loaded in as email_automation. If you’ve made it to this point, congratulations! With this sample DAG, you can now do a lot of different things: If you’d like to truly automate this to send an e-mail to recipients at certain intervals (i.e. every day, week, etc.), you can uncomment the “schedule_interval” syntax in the DAG from above. More information about how to create syntax for this piece can be found here. Additionally, you can edit the e-mail body message by adjusting the “email_html” variable text. As mentioned in my opening, I’ve used these functions from this DAG as a task in a larger pipeline. For instance, I’ve added an e-mail task at the end of a data pull to send a notice to recipients that new data has been loaded, a new file has been created, etc. Given you can customize the e-mail body language, you can add links to your final data sources, as well as any other important information about the pipeline instance itself. To close, Apache Airflow helps Data Engineers automate a lot of things! I hope this walkthrough was a useful demonstration of how to effectively use SMTP libraries and Python to make e-mail automation an easy task! Thanks for reading! If you liked this article, feel free to head over to my profile for other pieces, where I discuss other Data Engineering, Data Science, and Data Visualization projects I’ve worked on. Additionally, please check out my portfolio at: zach-alexander.com.
[ { "code": null, "e": 651, "s": 171, "text": "As a Data Engineer, some of the work I do involves automating data pulls at regular intervals from third-party sources for various teams at the organization. Although I like to think staff are always aware of when a new data pull occurs (ha!), I can’t expect them to remember each time it happens. Because of this, Apache Airflow has been a great service to help send e-mail reminders to interested parties when a data pipeline has completed and a new dataset has been processed." }, { "code": null, "e": 840, "s": 651, "text": "Airflow not only does a great job orchestrating the data pull itself but works well with Python libraries (such as SMTP) to facilitate the transfer of the email to the proper recipient(s)." }, { "code": null, "e": 1008, "s": 840, "text": "In this quick guide below, I’ll walk you through setting up your first directed acyclic graph (DAG) in Apache Airflow that orchestrates this e-mail automation process!" }, { "code": null, "e": 1152, "s": 1008, "text": "If you don’t know what Apache Airflow is, feel free to first read through these resources below to get a better sense of some of its use cases." }, { "code": null, "e": 1249, "s": 1152, "text": "Official Airflow Documentation: https://airflow.apache.org/docs/apache-airflow/stable/index.html" }, { "code": null, "e": 1345, "s": 1249, "text": "A Good Medium Post on Airflow: https://medium.com/swlh/apache-airflow-in-5-minutes-c005b4b11b26" }, { "code": null, "e": 1446, "s": 1345, "text": "Mainly, you’ll want to have a basic understanding of tasks, operators, and Airflow’s file structure." }, { "code": null, "e": 1650, "s": 1446, "text": "Additionally, e-mail automation in Python with SMTP depends on a properly configured sender e-mail address. Although many different e-mail providers can be used, I’ve found that Gmail makes it very easy." }, { "code": null, "e": 1963, "s": 1650, "text": "In order for the sender e-mail to operate correctly with SMTP and Python, you’ll need to follow the instructions here (under the Option 1: Setting Up A Gmail Account for Development). This should be a pretty quick step, where you’ll need to change one of your security settings to “Allow less secure apps to ON”." }, { "code": null, "e": 2090, "s": 1963, "text": "When both prerequisites are met, you’ll then want to tackle installing Airflow on your local machine (if you haven’t already)." }, { "code": null, "e": 2277, "s": 2090, "text": "If/when you feel comfortable with Airflow, you’ll then want to make sure it’s installed locally. If you need some help with this process, here are a few starters for local installations:" }, { "code": null, "e": 2371, "s": 2277, "text": "Installation on Mac: https://arpitrana.medium.com/install-airflow-on-macos-guide-fc66399b2a9e" }, { "code": null, "e": 2493, "s": 2371, "text": "Installation via Docker: https://medium.com/@itunpredictable/apache-airflow-on-docker-for-complete-beginners-cf76cf7b2c9a" }, { "code": null, "e": 2605, "s": 2493, "text": "Installation on Windows 10: https://medium.com/@ryanroline/installing-apache-airflow-on-windows-10-5247aa1249ef" }, { "code": null, "e": 2870, "s": 2605, "text": "As a quick note, if you are planning to install Airflow on Windows (without Docker), you’ll need to create a Linux subsystem. The instructions should be helpful in the guide above, but it might take a bit of configuration with your local setup to get this working." }, { "code": null, "e": 2974, "s": 2870, "text": "Once you have Airflow installed, and you have a good handle on the software itself, we can get started." }, { "code": null, "e": 3076, "s": 2974, "text": "If you haven’t already, spin up your webserver by running the following command in a terminal window:" }, { "code": null, "e": 3094, "s": 3076, "text": "airflow webserver" }, { "code": null, "e": 3177, "s": 3094, "text": "Additionally, you can spin up the Airflow scheduler in a separate terminal window:" }, { "code": null, "e": 3195, "s": 3177, "text": "airflow scheduler" }, { "code": null, "e": 3342, "s": 3195, "text": "You should then be able to navigate to http://localhost:8080 (or whichever endpoint you’ve configured for your local webserver), and find your UI." }, { "code": null, "e": 3770, "s": 3342, "text": "To avoid duplication with other posts, and to cut down on the length of the article, I won’t go into detail about uploading dags. Ultimately, when you spin up the webserver you should see your dags load into the UI if your directory and environment are structured correctly. If you are spinning up your webserver for the first time, you may see some sample dags in the UI if you configured this option in your airflow.cfg file." }, { "code": null, "e": 3946, "s": 3770, "text": "Now, with the webserver running on your local machine, we can create the DAG that’ll send an e-mail. To help guide you through this process, I’ve posted my DAG file on GitHub:" }, { "code": null, "e": 3999, "s": 3946, "text": "https://github.com/zachalexander/airflow-medium-post" }, { "code": null, "e": 4168, "s": 3999, "text": "Feel free to clone the repository and work through this simultaneously, or read through the guide below and then use the code to integrate this into your DAGs later on!" }, { "code": null, "e": 4485, "s": 4168, "text": "Important Note: For those that are already using Airflow regularly, since the DAG file contains a just a few functions, you can integrate these into any pipeline you already have set up (and add it on as a task). However, for the sake of this walkthrough, I’ll create this as a separate, one-step dag for simplicity." }, { "code": null, "e": 4788, "s": 4485, "text": "To create our e-mail automation DAG, we can navigate to the dags folder in your Airflow project, which should be structured similar to my GitHub repo. You can either use my existing “email_automation.py” file or you can create your own blank python file. An example of the directory structure is below:" }, { "code": null, "e": 4826, "s": 4788, "text": "airflow dags/ email_automation.py" }, { "code": null, "e": 4900, "s": 4826, "text": "Inside of this python file, you can add the following imports at the top:" }, { "code": null, "e": 5115, "s": 4900, "text": "from airflow import DAGfrom airflow.operators.python_operator import PythonOperatorfrom datetime import timedeltaimport smtplib, sslfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipart" }, { "code": null, "e": 5527, "s": 5115, "text": "The first import allows for DAG functionality in Airflow, and the second allows for Airflow’s Python Operator, which we’ll use to initiate the e-mail later on. Importing timedelta will help us regulate a timeout interval in the occurrence of our DAG taking too long to run (Airflow best practice). Then, we’ll import some e-mail and SMTP libraries that will be essential to sending the e-mail to our recipients." }, { "code": null, "e": 5622, "s": 5527, "text": "After this, we can then add our first function declaration, which is named send_email_basic():" }, { "code": null, "e": 6624, "s": 5622, "text": "def send_email_basic(sender, receiver, email_subject):port = 465 # For SSLsmtp_server = \"smtp.gmail.com\"sender_email = sender # Enter your addressreceiver_email = receiver # Enter receiver addresspassword = 'env variable' # Enter your gmail passwordemail_html = \"\"\"<html> <body> <p>Hello!</p> <p>Add any text you'd like to the body of the e-mail here!</p> <br> </body></html>\"\"\"message = MIMEMultipart(\"multipart\")# Turn these into plain/html MIMEText objectspart2 = MIMEText(email_html, \"html\")# Add HTML/plain-text parts to MIMEMultipart message# The email client will try to render the last part firstmessage.attach(part2)message[\"Subject\"] = email_subjectmessage[\"From\"] = sender_email## iterating through the receiver listfor i, val in enumerate(receiver):message[\"To\"] = valcontext = ssl.create_default_context()with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:server.login(sender_email, password)server.sendmail(sender_email, receiver_email, message.as_string())" }, { "code": null, "e": 6669, "s": 6624, "text": "In this function, we are doing a few things:" }, { "code": null, "e": 6701, "s": 6669, "text": "We are identifying the SSL port" }, { "code": null, "e": 6729, "s": 6701, "text": "Identifying the SMTP server" }, { "code": null, "e": 6827, "s": 6729, "text": "Storing the sender and recipient addresses in variables, as well as the sender’s e-mail password." }, { "code": null, "e": 6923, "s": 6827, "text": "Creating a text string that has the custom html for our e-mail body and saving it to a variable" }, { "code": null, "e": 7021, "s": 6923, "text": "Identifying the e-mail as a “multipart” e-mail, and attaching the body text to our e-mail message" }, { "code": null, "e": 7080, "s": 7021, "text": "Attaching a “subject” and “from” parameters to our message" }, { "code": null, "e": 7208, "s": 7080, "text": "Iterating through our receiver list (in case of multiple recipients for the e-mail) to add to our “to” parameter of our message" }, { "code": null, "e": 7327, "s": 7208, "text": "Connecting to our server and sending the e-mail with the message parameters for “to”, “from”, “subject” and “message”." }, { "code": null, "e": 7639, "s": 7327, "text": "Although there appears to be a lot to this, the function call is pretty straightforward. For more information about some of the e-mail jargon above, feel free to read up on this process here: https://realpython.com/python-send-email/ (same article as above for setting up your Gmail account as a proper sender)." }, { "code": null, "e": 7679, "s": 7639, "text": "Next, we can declare our next function:" }, { "code": null, "e": 7972, "s": 7679, "text": "def init_email():sender = \"yourgmailaddress@gmail.com\" # add the sender gmail address hererecipients = [\"email address 1\", \"email address 2\"] # add your e-mail recipients heresubject = \"Subject Line\" # add the subject of the e-mail you'd like heresend_email_basic(sender, recipients, subject)" }, { "code": null, "e": 8116, "s": 7972, "text": "This function, init_email(), will be used by our Python Operator to trigger our e-mail in a bit. Here is a breakdown of what’s happening above:" }, { "code": null, "e": 8235, "s": 8116, "text": "We are saving our sender address (which is the Gmail address you’ll use to send the e-mails from) in a sender variable" }, { "code": null, "e": 8457, "s": 8235, "text": "We are saving our recipient addresses as a list in a recipients variable. Here, since we have set up a way to iterate through this list in our previous function, we can just list out our e-mail addresses in the list here." }, { "code": null, "e": 8539, "s": 8457, "text": "We are creating the text for our subject line and saving it to a subject variable" }, { "code": null, "e": 8641, "s": 8539, "text": "Finally, we are going to add these variables as parameters to our initial send_email_basic() function" }, { "code": null, "e": 8737, "s": 8641, "text": "Finally, we can set up our Airflow syntax to initialize this DAG and add the parameters needed:" }, { "code": null, "e": 9277, "s": 8737, "text": "default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': 'trigger date', 'email': ['your Airflow email'], 'email_on_failure': True, 'email_on_retry': True, 'retries': 0}dag = DAG('email_automation', default_args=default_args, dagrun_timeout=timedelta(minutes=5), # schedule_interval = '0 13 * * 1', # if you want to set up an automation schedule you can do that here catchup=False)t1 = PythonOperator( task_id='send_email', python_callable=init_email, dag=dag)t1" }, { "code": null, "e": 9310, "s": 9277, "text": "Here we are doing the following:" }, { "code": null, "e": 9392, "s": 9310, "text": "Creating our default arguments for our DAG, similar to the Airflow documentation." }, { "code": null, "e": 9441, "s": 9392, "text": "Creating our DAG(), naming it email_automation ." }, { "code": null, "e": 9523, "s": 9441, "text": "Using the PythonOperator() to create a task, call our init_email python function." }, { "code": null, "e": 9550, "s": 9523, "text": "Assigning our task as t1 ." }, { "code": null, "e": 9621, "s": 9550, "text": "Once this is ready to go, your DAG file should be all set! By running:" }, { "code": null, "e": 9637, "s": 9621, "text": "airflow init db" }, { "code": null, "e": 9708, "s": 9637, "text": "You should be able to now see a new dag loaded in as email_automation." }, { "code": null, "e": 9822, "s": 9708, "text": "If you’ve made it to this point, congratulations! With this sample DAG, you can now do a lot of different things:" }, { "code": null, "e": 10092, "s": 9822, "text": "If you’d like to truly automate this to send an e-mail to recipients at certain intervals (i.e. every day, week, etc.), you can uncomment the “schedule_interval” syntax in the DAG from above. More information about how to create syntax for this piece can be found here." }, { "code": null, "e": 10188, "s": 10092, "text": "Additionally, you can edit the e-mail body message by adjusting the “email_html” variable text." }, { "code": null, "e": 10625, "s": 10188, "text": "As mentioned in my opening, I’ve used these functions from this DAG as a task in a larger pipeline. For instance, I’ve added an e-mail task at the end of a data pull to send a notice to recipients that new data has been loaded, a new file has been created, etc. Given you can customize the e-mail body language, you can add links to your final data sources, as well as any other important information about the pipeline instance itself." }, { "code": null, "e": 10840, "s": 10625, "text": "To close, Apache Airflow helps Data Engineers automate a lot of things! I hope this walkthrough was a useful demonstration of how to effectively use SMTP libraries and Python to make e-mail automation an easy task!" }, { "code": null, "e": 11044, "s": 10840, "text": "Thanks for reading! If you liked this article, feel free to head over to my profile for other pieces, where I discuss other Data Engineering, Data Science, and Data Visualization projects I’ve worked on." } ]
5 Best Python Projects With Codes That You Can Complete Within An Hour! | by Bharath K | Towards Data Science
Python is a phenomenal programming language for any developer to learn and understand due to its simplicity, ease of use, and versatility. Apart from the continuous developments, improvements, and progression made with each upcoming version, Python has the most supportive and mature community with a ton of productive and helpful resources to assist you in every way possible. With the help of Python and its equivalent libraries, we can achieve a humungous amount of accomplishments by constructing different types of unique projects. The flexibility of Python allows you to explore any options that you want to, and the tremendous number of wonderful resources will assist you in achieving the task you desire with greater ease. Hence, it is a fantastic idea to start working on numerous Python projects to add to your resume. I try to cover most of the helpful topics for beginner Data Science enthusiasts and programmers. If you are interested in learning how to master the subject of Data Science within the span of 12 months, you should check out the following guide that suggests the 12 steps that you must follow to achieve this goal. towardsdatascience.com In this article, we will look at five different amazing projects that you can build using Python and its libraries. You can effectively compute all the projects mentioned in their respective sections within the time frame duration of an hour. We will look at four simpler Python projects to get started and one slightly more complex Python task with the involvement of artificial intelligence. Let us get started with the construction of our projects! With the help of Python, it is quite easy to automate most of the tasks that would otherwise be considered tricky or complex for humans. With the help of the appropriate libraries and coding patterns, it is possible to automate your PC to achieve a suitable task with the help of Python. In this section, we will explore a similar project with which we can perform such a type of automation to which will prompt us with alerts reminding us about the tasks to complete. In this first project, we will look at how we can set up reminder alerts on a timely basis so that you will be notified accordingly. For this task, we will make use of two essential libraries to accomplish the project. The time module imported in Python and the plyer library, which can be installed with a simple pip command, can be used to specify the notification request accordingly. The code block provided below is a great starting point for achieving the desired results for this project. import timefrom plyer import notificationif __name__ == "__main__": while True: notification.notify( title = "ALERT!!!", message = "Take a break! It has been an hour!", timeout = 10 ) time.sleep(3600) The above code example demonstrates the procedural working for this Python project. However, there are many further improvements and advancements that can be achieved. For the complete explanation of the entire process that you can accomplish with the following project and library, visit the link provided below, as every single concept and attribute related to the following topic is covered in great detail. towardsdatascience.com Creating a calculator with Python is an interesting task. While we have explored several concepts of calculators in my previous articles, from simple calculators to perform simple computations to constructing more complex architectures of calculators with differentiation and integration. While the following code blocks made use of pure code and immediate response, in this project, we will focus on creating a more interactive graphic user environment with Python. For this project, in the first code block, we will declare all the basic requirements and mandatory functions for declaring the expressions, creating the press buttons, and the working of the equals button. Below is the first sample code block for this project. The complete code reference for this sample code block is referenced from the following website. Refer to it for further information and the entire coding procedure. # Import Tkinterfrom tkinter import *# globally declare the expression variableexpression = ""# Function to update expression in the text entry boxdef press(num): global expression expression = expression + str(num) equation.set(expression)# Function to evaluate the final expressiondef equalpress(): try: global expression total = str(eval(expression))equation.set(total) expression = ""except:equation.set(" error ") expression = "" In the next sample code block, we will look at the construction of the basic GUI interface in which you can display the numerous buttons and construct the overall project. For the purpose of this sample code block, I will only display some of the basic elements for creating some basic functionalities. The numbers ranging from one to three can be created as follows, and we can test out the addition operation after clicking the equals button. Click the button elements to display the numbers and perform your desired action accordingly. Once the computation is performed, you can click the equals button to display the final result. # Driver codeif __name__ == "__main__": # create a GUI window gui = Tk()# set the background colour of GUI window gui.configure(background="light green")# set the title of GUI window gui.title("Simple Calculator")# set the configuration of GUI window gui.geometry("270x150")# we create an instance of this class equation = StringVar()# create the text entry box for expression_field = Entry(gui, textvariable=equation)# grid method is used for placing expression_field.grid(columnspan=4, ipadx=70)# create a Buttons and place at a particular. button1 = Button(gui, text=' 1 ', fg='black', bg='red', command=lambda: press(1), height=1, width=7) button1.grid(row=2, column=0)button2 = Button(gui, text=' 2 ', fg='black', bg='red', command=lambda: press(2), height=1, width=7) button2.grid(row=2, column=1)button3 = Button(gui, text=' 3 ', fg='black', bg='red', command=lambda: press(3), height=1, width=7) button3.grid(row=2, column=2)plus = Button(gui, text=' + ', fg='black', bg='red', command=lambda: press("+"), height=1, width=7) plus.grid(row=2, column=3)equal = Button(gui, text=' = ', fg='black', bg='red', command=equalpress, height=1, width=7) equal.grid(row=5, column=2)clear = Button(gui, text='Clear', fg='black', bg='red', command=clear, height=1, width=7) clear.grid(row=5, column='1')Decimal= Button(gui, text='.', fg='black', bg='red', command=lambda: press('.'), height=1, width=7) Decimal.grid(row=6, column=0) # start the GUI gui.mainloop() For checking out further information on this topic, I would recommend checking out this reference from Geek for Geeks. If you are interested in understanding the concept through a video guide, I would suggest following this video guide on YouTube. If you are curious to learn more about Graphics User Interfaces and the other options that you available to you, check out one of my previous articles that covers seven such tools with some starter codes for the development of projects. towardsdatascience.com The audiobook voice-over project, as the name suggests, will involve some textual and voice requirements. For this Python project, we will convert the information to text and get a voice recording that you can automatically listen to. This project will consist of two main phases. The first phase is the conversion of the textual data into audio recordings, and the second step is to interpret the eBooks into a readable format. For the first task, we will utilize the Google Text-To-Speech using Python, while in the second phase, we will utilize the optical character recognition (OCR) techniques to achieve the best results possible. To begin with the first phase of the project, we can start exploring the Google Text-To-Speech (GTTS) module to achieve the task of conversion of textual information into an audio file. Once we obtain a playable version of this audio file, we can choose to either keep or remove this particular file. The code for performing the following action is as follows. from gtts import gTTSimport ostext = "Hello! My name is Bharath."tts = gTTS(text)tts.save("hi.mp3")os.system("hi.mp3") For gaining further information and learning the intricate details on the working of this library, it is recommended to check out one of my previous articles that extensively covers this topic from the following link provided below. towardsdatascience.com For the second phase of this project, we will focus on reading eBooks, which are usually in the PDF (or text files) format, into a textual description such that it is readable by the GTTS module. The reading of information in PDFs or images will require the use of optical character recognition (OCR) technologies. We will use the Pytesseract module for these OCR conversions. The Pytesseract OCR module is one of the best options to interpret the visual information and extract the textual descriptions from that particular image or document. Let us compute the final code block to construct the project of an audiobook reader with these two technologies. #Importing the librariesimport cv2import pytesseractfrom PIL import Imagefrom gtts import gTTSfrom playsound import playsound# Specifying the pathpytesseract.pytesseract.tesseract_cmd = r'C:/Program Files/Tesseract-OCR/tesseract.exe'# Reading the image image = cv2.imread('1.png')# Extraction of text from imagetext = pytesseract.image_to_string(image)# Printing the textprint(text)# Create the voice_text variable to store the data.voice_text = ""# Pre-processing the datafor i in text.split(): voice_text += i + ' ' voice_text = voice_text[:-1]voice_texttts = gTTS(voice_text)tts.save("test.mp3")playsound("test.mp3") To learn more about optical character recognition and the complete working procedure of this library module, I would recommend checking out one of my previous articles on OCR with Python that covers this topic extensively from the link provided below. towardsdatascience.com In this section, we will discuss a couple of gaming projects that you can construct with the help of Python. With the help of Python and the variety of modules it offers the users, you can construct a wide array of games. You can build games like hangman, tic tac toe, rock paper scissors, and so much more, including more graphical oriented games like flappy bird or Mario copies with the help of Pygame. In this first part of the article, we will talk more about how you can use the different libraries that are available in Python to create your own unique games. With the help of the pre-built library modules such as the turtle package and the random library in Python, you can construct a unique project with a slight graphical touch to it. In the code block shown below, we are defining a function where we are drawing a racing track, and once the track is complete, we plan to place a couple of turtles so that they can race each other. The motion of the races can be randomized with the random library, and each result of the roll will be different each time, and hence which turtle wins the race will also be different each time. def treat(): speed(0) penup() goto(-140, 140) for step in range(15): write(step, align='center') right(90) for num in range(8): penup() forward(10) pendown() forward(10) penup() backward(160) left(90) forward(20) turtle1 = Turtle() turtle1.color('red') turtle1.shape('turtle') While the above code block is a sample code for the project that we plan to build, you can either continue from here on your own with some unique ideas or refer to one of the other projects that I constructed as a fun Python project for Halloween. If you are interested in building a similar turtle race project as specified above, then check out the following link provided below. It is a detailed guide on how you can create any type of Python game with a unique and intriguing idea without the requirement of too much programming knowledge. towardsdatascience.com For the second part, you can construct a multitude of projects with Pygame. It is one of the best libraries in Python that allows you to work on many different gaming projects. You can build simpler project ideas with this gaming library or construct more complex projects with deep learning and reinforcement learning. If you are interested in learning more about developing games and why you should develop one yourself with Python and Artificial Intelligence, then check out the following article from the link provided below. towardsdatascience.com Unlike our previously discussed projects, the sentiment analysis project will involve more of other equivalent topics related to AI, such as machine learning and deep learning. However, I find that there are numerous variations of sentiment analysis that you can perform on many different levels, and the complexity can be constantly improved with each variation of any specific action, similar to the calculator project described in the second point of this article. Let us firstly understand what sentiment analysis is, and how you can perform the following in Python with a sample code block. Sentiment analysis (also known as opinion mining or emotion AI) refers to the use of natural language processing, text analysis, computational linguistics, and biometrics to systematically identify, extract, quantify, and study affective states and subjective information. For performing the task of sentiment analysis, we can achieve the most successful results with the help of numerous methods. Usually, for beginners, the best approach is to start with numerous machine learning algorithms after cleaning the text data available to them and performing all the basic operations of tokenization. Machine learning algorithms like logistic regression and Naïve Bayes are methods to consider for approaching this problem. The project we will construct in this article will use some elements of natural language processing toolkit and the inbuilt Naïve Bayes algorithm. We are trying to use the movie corpus dataset, and perform some type of sentiment analysis. The complete code block shown below is taken from the following link. Check it out for further information and details on the following topic. # Load and prepare the datasetimport nltkfrom nltk.corpus import movie_reviewsimport randomdocuments = [(list(movie_reviews.words(fileid)), category) for category in movie_reviews.categories() for fileid in movie_reviews.fileids(category)]random.shuffle(documents)# Define the feature extractorall_words = nltk.FreqDist(w.lower() for w in movie_reviews.words())word_features = list(all_words)[:2000]def document_features(document): document_words = set(document) features = {} for word in word_features: features['contains({})'.format(word)] = (word in document_words) return features# Train Naive Bayes classifierfeaturesets = [(document_features(d), c) for (d,c) in documents]train_set, test_set = featuresets[100:], featuresets[:100]classifier = nltk.NaiveBayesClassifier.train(train_set)# Test the classifierprint(nltk.classify.accuracy(classifier, test_set)) If you are interested in approaching the following problem statement with a more deep learning approach, then you should consider starting off finding a solution using LSTMs. Then, you can approach the following problem with a more complex approach of sequence to sequence models with attention or with the use of 1-Dimensional convolutional layers, etc. As a starting point, I would recommend checking out the following link to get started with the deep learning approach for the sentiment analysis project. If you are interesting in learning more about natural language processing and other similar tasks that you can perform with NLP and deep learning, feel free to check out one of my previous projects that covers the topic of next word prediction. In this project, I go deeper into how you can construct a next word prediction model with the help of deep learning and conduct predictive searches using LSTM. towardsdatascience.com “The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code — not in reams of trivial code that bores the reader to death.” — Guido van Rossum The simplicity of Python allows developers to straight away five into the creation of exceptional projects. With the help of the diverse and phenomenal tools that are available in Python, enthusiasts can build almost any type of project that they want to explore. You can build any kind of AI, Data Science, computer vision, or natural language project that you desire and want to, thanks to the versatility of this programming language. In this article, we covered the topic of how to construct five different Python projects, namely, automating your PC, GUI calculator, Audiobook voice-over, Python Hangman game, and sentiment analysis. With the code blocks, the various references, and other resources, you should easily be able to build these projects without too much difficulty. After working on these projects, take up some of your own choices and start exploring and experimenting with these other options as well. Keep building more and more projects till you learn a lot more. If you have any queries related to the various points stated in this article, then feel free to let me know in the comments below. I will try to get back to you with a response as soon as possible. Check out some of my other articles that you might enjoy reading! towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com Thank you all for sticking on till the end. I hope all of you enjoyed reading the article. Wish you all a wonderful day!
[ { "code": null, "e": 550, "s": 172, "text": "Python is a phenomenal programming language for any developer to learn and understand due to its simplicity, ease of use, and versatility. Apart from the continuous developments, improvements, and progression made with each upcoming version, Python has the most supportive and mature community with a ton of productive and helpful resources to assist you in every way possible." }, { "code": null, "e": 1002, "s": 550, "text": "With the help of Python and its equivalent libraries, we can achieve a humungous amount of accomplishments by constructing different types of unique projects. The flexibility of Python allows you to explore any options that you want to, and the tremendous number of wonderful resources will assist you in achieving the task you desire with greater ease. Hence, it is a fantastic idea to start working on numerous Python projects to add to your resume." }, { "code": null, "e": 1316, "s": 1002, "text": "I try to cover most of the helpful topics for beginner Data Science enthusiasts and programmers. If you are interested in learning how to master the subject of Data Science within the span of 12 months, you should check out the following guide that suggests the 12 steps that you must follow to achieve this goal." }, { "code": null, "e": 1339, "s": 1316, "text": "towardsdatascience.com" }, { "code": null, "e": 1791, "s": 1339, "text": "In this article, we will look at five different amazing projects that you can build using Python and its libraries. You can effectively compute all the projects mentioned in their respective sections within the time frame duration of an hour. We will look at four simpler Python projects to get started and one slightly more complex Python task with the involvement of artificial intelligence. Let us get started with the construction of our projects!" }, { "code": null, "e": 2260, "s": 1791, "text": "With the help of Python, it is quite easy to automate most of the tasks that would otherwise be considered tricky or complex for humans. With the help of the appropriate libraries and coding patterns, it is possible to automate your PC to achieve a suitable task with the help of Python. In this section, we will explore a similar project with which we can perform such a type of automation to which will prompt us with alerts reminding us about the tasks to complete." }, { "code": null, "e": 2756, "s": 2260, "text": "In this first project, we will look at how we can set up reminder alerts on a timely basis so that you will be notified accordingly. For this task, we will make use of two essential libraries to accomplish the project. The time module imported in Python and the plyer library, which can be installed with a simple pip command, can be used to specify the notification request accordingly. The code block provided below is a great starting point for achieving the desired results for this project." }, { "code": null, "e": 3014, "s": 2756, "text": "import timefrom plyer import notificationif __name__ == \"__main__\": while True: notification.notify( title = \"ALERT!!!\", message = \"Take a break! It has been an hour!\", timeout = 10 ) time.sleep(3600)" }, { "code": null, "e": 3425, "s": 3014, "text": "The above code example demonstrates the procedural working for this Python project. However, there are many further improvements and advancements that can be achieved. For the complete explanation of the entire process that you can accomplish with the following project and library, visit the link provided below, as every single concept and attribute related to the following topic is covered in great detail." }, { "code": null, "e": 3448, "s": 3425, "text": "towardsdatascience.com" }, { "code": null, "e": 3915, "s": 3448, "text": "Creating a calculator with Python is an interesting task. While we have explored several concepts of calculators in my previous articles, from simple calculators to perform simple computations to constructing more complex architectures of calculators with differentiation and integration. While the following code blocks made use of pure code and immediate response, in this project, we will focus on creating a more interactive graphic user environment with Python." }, { "code": null, "e": 4343, "s": 3915, "text": "For this project, in the first code block, we will declare all the basic requirements and mandatory functions for declaring the expressions, creating the press buttons, and the working of the equals button. Below is the first sample code block for this project. The complete code reference for this sample code block is referenced from the following website. Refer to it for further information and the entire coding procedure." }, { "code": null, "e": 4782, "s": 4343, "text": "# Import Tkinterfrom tkinter import *# globally declare the expression variableexpression = \"\"# Function to update expression in the text entry boxdef press(num): global expression expression = expression + str(num) equation.set(expression)# Function to evaluate the final expressiondef equalpress(): try: global expression total = str(eval(expression))equation.set(total) expression = \"\"except:equation.set(\" error \") expression = \"\"" }, { "code": null, "e": 5417, "s": 4782, "text": "In the next sample code block, we will look at the construction of the basic GUI interface in which you can display the numerous buttons and construct the overall project. For the purpose of this sample code block, I will only display some of the basic elements for creating some basic functionalities. The numbers ranging from one to three can be created as follows, and we can test out the addition operation after clicking the equals button. Click the button elements to display the numbers and perform your desired action accordingly. Once the computation is performed, you can click the equals button to display the final result." }, { "code": null, "e": 6901, "s": 5417, "text": "# Driver codeif __name__ == \"__main__\": # create a GUI window gui = Tk()# set the background colour of GUI window gui.configure(background=\"light green\")# set the title of GUI window gui.title(\"Simple Calculator\")# set the configuration of GUI window gui.geometry(\"270x150\")# we create an instance of this class equation = StringVar()# create the text entry box for expression_field = Entry(gui, textvariable=equation)# grid method is used for placing expression_field.grid(columnspan=4, ipadx=70)# create a Buttons and place at a particular. button1 = Button(gui, text=' 1 ', fg='black', bg='red', command=lambda: press(1), height=1, width=7) button1.grid(row=2, column=0)button2 = Button(gui, text=' 2 ', fg='black', bg='red', command=lambda: press(2), height=1, width=7) button2.grid(row=2, column=1)button3 = Button(gui, text=' 3 ', fg='black', bg='red', command=lambda: press(3), height=1, width=7) button3.grid(row=2, column=2)plus = Button(gui, text=' + ', fg='black', bg='red', command=lambda: press(\"+\"), height=1, width=7) plus.grid(row=2, column=3)equal = Button(gui, text=' = ', fg='black', bg='red', command=equalpress, height=1, width=7) equal.grid(row=5, column=2)clear = Button(gui, text='Clear', fg='black', bg='red', command=clear, height=1, width=7) clear.grid(row=5, column='1')Decimal= Button(gui, text='.', fg='black', bg='red', command=lambda: press('.'), height=1, width=7) Decimal.grid(row=6, column=0) # start the GUI gui.mainloop()" }, { "code": null, "e": 7386, "s": 6901, "text": "For checking out further information on this topic, I would recommend checking out this reference from Geek for Geeks. If you are interested in understanding the concept through a video guide, I would suggest following this video guide on YouTube. If you are curious to learn more about Graphics User Interfaces and the other options that you available to you, check out one of my previous articles that covers seven such tools with some starter codes for the development of projects." }, { "code": null, "e": 7409, "s": 7386, "text": "towardsdatascience.com" }, { "code": null, "e": 7690, "s": 7409, "text": "The audiobook voice-over project, as the name suggests, will involve some textual and voice requirements. For this Python project, we will convert the information to text and get a voice recording that you can automatically listen to. This project will consist of two main phases." }, { "code": null, "e": 8046, "s": 7690, "text": "The first phase is the conversion of the textual data into audio recordings, and the second step is to interpret the eBooks into a readable format. For the first task, we will utilize the Google Text-To-Speech using Python, while in the second phase, we will utilize the optical character recognition (OCR) techniques to achieve the best results possible." }, { "code": null, "e": 8407, "s": 8046, "text": "To begin with the first phase of the project, we can start exploring the Google Text-To-Speech (GTTS) module to achieve the task of conversion of textual information into an audio file. Once we obtain a playable version of this audio file, we can choose to either keep or remove this particular file. The code for performing the following action is as follows." }, { "code": null, "e": 8526, "s": 8407, "text": "from gtts import gTTSimport ostext = \"Hello! My name is Bharath.\"tts = gTTS(text)tts.save(\"hi.mp3\")os.system(\"hi.mp3\")" }, { "code": null, "e": 8759, "s": 8526, "text": "For gaining further information and learning the intricate details on the working of this library, it is recommended to check out one of my previous articles that extensively covers this topic from the following link provided below." }, { "code": null, "e": 8782, "s": 8759, "text": "towardsdatascience.com" }, { "code": null, "e": 9159, "s": 8782, "text": "For the second phase of this project, we will focus on reading eBooks, which are usually in the PDF (or text files) format, into a textual description such that it is readable by the GTTS module. The reading of information in PDFs or images will require the use of optical character recognition (OCR) technologies. We will use the Pytesseract module for these OCR conversions." }, { "code": null, "e": 9439, "s": 9159, "text": "The Pytesseract OCR module is one of the best options to interpret the visual information and extract the textual descriptions from that particular image or document. Let us compute the final code block to construct the project of an audiobook reader with these two technologies." }, { "code": null, "e": 10065, "s": 9439, "text": "#Importing the librariesimport cv2import pytesseractfrom PIL import Imagefrom gtts import gTTSfrom playsound import playsound# Specifying the pathpytesseract.pytesseract.tesseract_cmd = r'C:/Program Files/Tesseract-OCR/tesseract.exe'# Reading the image image = cv2.imread('1.png')# Extraction of text from imagetext = pytesseract.image_to_string(image)# Printing the textprint(text)# Create the voice_text variable to store the data.voice_text = \"\"# Pre-processing the datafor i in text.split(): voice_text += i + ' ' voice_text = voice_text[:-1]voice_texttts = gTTS(voice_text)tts.save(\"test.mp3\")playsound(\"test.mp3\")" }, { "code": null, "e": 10317, "s": 10065, "text": "To learn more about optical character recognition and the complete working procedure of this library module, I would recommend checking out one of my previous articles on OCR with Python that covers this topic extensively from the link provided below." }, { "code": null, "e": 10340, "s": 10317, "text": "towardsdatascience.com" }, { "code": null, "e": 10746, "s": 10340, "text": "In this section, we will discuss a couple of gaming projects that you can construct with the help of Python. With the help of Python and the variety of modules it offers the users, you can construct a wide array of games. You can build games like hangman, tic tac toe, rock paper scissors, and so much more, including more graphical oriented games like flappy bird or Mario copies with the help of Pygame." }, { "code": null, "e": 11087, "s": 10746, "text": "In this first part of the article, we will talk more about how you can use the different libraries that are available in Python to create your own unique games. With the help of the pre-built library modules such as the turtle package and the random library in Python, you can construct a unique project with a slight graphical touch to it." }, { "code": null, "e": 11480, "s": 11087, "text": "In the code block shown below, we are defining a function where we are drawing a racing track, and once the track is complete, we plan to place a couple of turtles so that they can race each other. The motion of the races can be randomized with the random library, and each result of the roll will be different each time, and hence which turtle wins the race will also be different each time." }, { "code": null, "e": 11879, "s": 11480, "text": "def treat(): speed(0) penup() goto(-140, 140) for step in range(15): write(step, align='center') right(90) for num in range(8): penup() forward(10) pendown() forward(10) penup() backward(160) left(90) forward(20) turtle1 = Turtle() turtle1.color('red') turtle1.shape('turtle')" }, { "code": null, "e": 12423, "s": 11879, "text": "While the above code block is a sample code for the project that we plan to build, you can either continue from here on your own with some unique ideas or refer to one of the other projects that I constructed as a fun Python project for Halloween. If you are interested in building a similar turtle race project as specified above, then check out the following link provided below. It is a detailed guide on how you can create any type of Python game with a unique and intriguing idea without the requirement of too much programming knowledge." }, { "code": null, "e": 12446, "s": 12423, "text": "towardsdatascience.com" }, { "code": null, "e": 12976, "s": 12446, "text": "For the second part, you can construct a multitude of projects with Pygame. It is one of the best libraries in Python that allows you to work on many different gaming projects. You can build simpler project ideas with this gaming library or construct more complex projects with deep learning and reinforcement learning. If you are interested in learning more about developing games and why you should develop one yourself with Python and Artificial Intelligence, then check out the following article from the link provided below." }, { "code": null, "e": 12999, "s": 12976, "text": "towardsdatascience.com" }, { "code": null, "e": 13467, "s": 12999, "text": "Unlike our previously discussed projects, the sentiment analysis project will involve more of other equivalent topics related to AI, such as machine learning and deep learning. However, I find that there are numerous variations of sentiment analysis that you can perform on many different levels, and the complexity can be constantly improved with each variation of any specific action, similar to the calculator project described in the second point of this article." }, { "code": null, "e": 13868, "s": 13467, "text": "Let us firstly understand what sentiment analysis is, and how you can perform the following in Python with a sample code block. Sentiment analysis (also known as opinion mining or emotion AI) refers to the use of natural language processing, text analysis, computational linguistics, and biometrics to systematically identify, extract, quantify, and study affective states and subjective information." }, { "code": null, "e": 14317, "s": 13868, "text": "For performing the task of sentiment analysis, we can achieve the most successful results with the help of numerous methods. Usually, for beginners, the best approach is to start with numerous machine learning algorithms after cleaning the text data available to them and performing all the basic operations of tokenization. Machine learning algorithms like logistic regression and Naïve Bayes are methods to consider for approaching this problem." }, { "code": null, "e": 14700, "s": 14317, "text": "The project we will construct in this article will use some elements of natural language processing toolkit and the inbuilt Naïve Bayes algorithm. We are trying to use the movie corpus dataset, and perform some type of sentiment analysis. The complete code block shown below is taken from the following link. Check it out for further information and details on the following topic." }, { "code": null, "e": 15609, "s": 14700, "text": "# Load and prepare the datasetimport nltkfrom nltk.corpus import movie_reviewsimport randomdocuments = [(list(movie_reviews.words(fileid)), category) for category in movie_reviews.categories() for fileid in movie_reviews.fileids(category)]random.shuffle(documents)# Define the feature extractorall_words = nltk.FreqDist(w.lower() for w in movie_reviews.words())word_features = list(all_words)[:2000]def document_features(document): document_words = set(document) features = {} for word in word_features: features['contains({})'.format(word)] = (word in document_words) return features# Train Naive Bayes classifierfeaturesets = [(document_features(d), c) for (d,c) in documents]train_set, test_set = featuresets[100:], featuresets[:100]classifier = nltk.NaiveBayesClassifier.train(train_set)# Test the classifierprint(nltk.classify.accuracy(classifier, test_set))" }, { "code": null, "e": 16118, "s": 15609, "text": "If you are interested in approaching the following problem statement with a more deep learning approach, then you should consider starting off finding a solution using LSTMs. Then, you can approach the following problem with a more complex approach of sequence to sequence models with attention or with the use of 1-Dimensional convolutional layers, etc. As a starting point, I would recommend checking out the following link to get started with the deep learning approach for the sentiment analysis project." }, { "code": null, "e": 16523, "s": 16118, "text": "If you are interesting in learning more about natural language processing and other similar tasks that you can perform with NLP and deep learning, feel free to check out one of my previous projects that covers the topic of next word prediction. In this project, I go deeper into how you can construct a next word prediction model with the help of deep learning and conduct predictive searches using LSTM." }, { "code": null, "e": 16546, "s": 16523, "text": "towardsdatascience.com" }, { "code": null, "e": 16769, "s": 16546, "text": "“The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code — not in reams of trivial code that bores the reader to death.” — Guido van Rossum" }, { "code": null, "e": 17207, "s": 16769, "text": "The simplicity of Python allows developers to straight away five into the creation of exceptional projects. With the help of the diverse and phenomenal tools that are available in Python, enthusiasts can build almost any type of project that they want to explore. You can build any kind of AI, Data Science, computer vision, or natural language project that you desire and want to, thanks to the versatility of this programming language." }, { "code": null, "e": 17554, "s": 17207, "text": "In this article, we covered the topic of how to construct five different Python projects, namely, automating your PC, GUI calculator, Audiobook voice-over, Python Hangman game, and sentiment analysis. With the code blocks, the various references, and other resources, you should easily be able to build these projects without too much difficulty." }, { "code": null, "e": 17954, "s": 17554, "text": "After working on these projects, take up some of your own choices and start exploring and experimenting with these other options as well. Keep building more and more projects till you learn a lot more. If you have any queries related to the various points stated in this article, then feel free to let me know in the comments below. I will try to get back to you with a response as soon as possible." }, { "code": null, "e": 18020, "s": 17954, "text": "Check out some of my other articles that you might enjoy reading!" }, { "code": null, "e": 18043, "s": 18020, "text": "towardsdatascience.com" }, { "code": null, "e": 18066, "s": 18043, "text": "towardsdatascience.com" }, { "code": null, "e": 18089, "s": 18066, "text": "towardsdatascience.com" }, { "code": null, "e": 18112, "s": 18089, "text": "towardsdatascience.com" }, { "code": null, "e": 18135, "s": 18112, "text": "towardsdatascience.com" } ]
Python 3 - List remove() Method
obj − This is the object to be removed from the list. This method does not return any value but removes the given object from the list. The following example shows the usage of remove() method. #!/usr/bin/python3 list1 = ['physics', 'Biology', 'chemistry', 'maths'] list1.remove('Biology') print ("list now : ", list1) list1.remove('maths') print ("list now : ", list1) When we run above program, it produces the following result − list now : ['physics', 'chemistry', 'maths'] list now : ['physics', 'chemistry'] 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2394, "s": 2340, "text": "obj − This is the object to be removed from the list." }, { "code": null, "e": 2476, "s": 2394, "text": "This method does not return any value but removes the given object from the list." }, { "code": null, "e": 2534, "s": 2476, "text": "The following example shows the usage of remove() method." }, { "code": null, "e": 2711, "s": 2534, "text": "#!/usr/bin/python3\n\nlist1 = ['physics', 'Biology', 'chemistry', 'maths']\nlist1.remove('Biology')\nprint (\"list now : \", list1)\nlist1.remove('maths')\nprint (\"list now : \", list1)" }, { "code": null, "e": 2773, "s": 2711, "text": "When we run above program, it produces the following result −" }, { "code": null, "e": 2857, "s": 2773, "text": "list now : ['physics', 'chemistry', 'maths']\nlist now : ['physics', 'chemistry']\n" }, { "code": null, "e": 2894, "s": 2857, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2910, "s": 2894, "text": " Malhar Lathkar" }, { "code": null, "e": 2943, "s": 2910, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 2962, "s": 2943, "text": " Arnab Chakraborty" }, { "code": null, "e": 2997, "s": 2962, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3019, "s": 2997, "text": " In28Minutes Official" }, { "code": null, "e": 3053, "s": 3019, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3081, "s": 3053, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3116, "s": 3081, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3130, "s": 3116, "text": " Lets Kode It" }, { "code": null, "e": 3163, "s": 3130, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3180, "s": 3163, "text": " Abhilash Nelson" }, { "code": null, "e": 3187, "s": 3180, "text": " Print" }, { "code": null, "e": 3198, "s": 3187, "text": " Add Notes" } ]
C++ Copy Constructor
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to − Initialize one object from another of the same type. Copy an object to pass it as an argument to a function. Copy an object to return it from a function. If a copy constructor is not defined in a class, the compiler itself defines one.If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor. The most common form of copy constructor is shown here − classname (const classname &obj) { // body of constructor } Here, obj is a reference to an object that is being used to initialize another object. #include <iostream> using namespace std; class Line { public: int getLength( void ); Line( int len ); // simple constructor Line( const Line &obj); // copy constructor ~Line(); // destructor private: int *ptr; }; // Member functions definitions including constructor Line::Line(int len) { cout << "Normal constructor allocating ptr" << endl; // allocate memory for the pointer; ptr = new int; *ptr = len; } Line::Line(const Line &obj) { cout << "Copy constructor allocating ptr." << endl; ptr = new int; *ptr = *obj.ptr; // copy the value } Line::~Line(void) { cout << "Freeing memory!" << endl; delete ptr; } int Line::getLength( void ) { return *ptr; } void display(Line obj) { cout << "Length of line : " << obj.getLength() <<endl; } // Main function for the program int main() { Line line(10); display(line); return 0; } When the above code is compiled and executed, it produces the following result − Normal constructor allocating ptr Copy constructor allocating ptr. Length of line : 10 Freeing memory! Freeing memory! Let us see the same example but with a small change to create another object using existing object of the same type − #include <iostream> using namespace std; class Line { public: int getLength( void ); Line( int len ); // simple constructor Line( const Line &obj); // copy constructor ~Line(); // destructor private: int *ptr; }; // Member functions definitions including constructor Line::Line(int len) { cout << "Normal constructor allocating ptr" << endl; // allocate memory for the pointer; ptr = new int; *ptr = len; } Line::Line(const Line &obj) { cout << "Copy constructor allocating ptr." << endl; ptr = new int; *ptr = *obj.ptr; // copy the value } Line::~Line(void) { cout << "Freeing memory!" << endl; delete ptr; } int Line::getLength( void ) { return *ptr; } void display(Line obj) { cout << "Length of line : " << obj.getLength() <<endl; } // Main function for the program int main() { Line line1(10); Line line2 = line1; // This also calls copy constructor display(line1); display(line2); return 0; } When the above code is compiled and executed, it produces the following result − Normal constructor allocating ptr Copy constructor allocating ptr. Copy constructor allocating ptr. Length of line : 10 Freeing memory! Copy constructor allocating ptr. Length of line : 10 Freeing memory! Freeing memory! Freeing memory! 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2503, "s": 2318, "text": "The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to −" }, { "code": null, "e": 2556, "s": 2503, "text": "Initialize one object from another of the same type." }, { "code": null, "e": 2612, "s": 2556, "text": "Copy an object to pass it as an argument to a function." }, { "code": null, "e": 2657, "s": 2612, "text": "Copy an object to return it from a function." }, { "code": null, "e": 2917, "s": 2657, "text": "If a copy constructor is not defined in a class, the compiler itself defines one.If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor. The most common form of copy constructor is shown here −" }, { "code": null, "e": 2981, "s": 2917, "text": "classname (const classname &obj) {\n // body of constructor\n}\n" }, { "code": null, "e": 3068, "s": 2981, "text": "Here, obj is a reference to an object that is being used to initialize another object." }, { "code": null, "e": 4020, "s": 3068, "text": "#include <iostream>\n\nusing namespace std;\n\nclass Line {\n\n public:\n int getLength( void );\n Line( int len ); // simple constructor\n Line( const Line &obj); // copy constructor\n ~Line(); // destructor\n\n private:\n int *ptr;\n};\n\n// Member functions definitions including constructor\nLine::Line(int len) {\n cout << \"Normal constructor allocating ptr\" << endl;\n \n // allocate memory for the pointer;\n ptr = new int;\n *ptr = len;\n}\n\nLine::Line(const Line &obj) {\n cout << \"Copy constructor allocating ptr.\" << endl;\n ptr = new int;\n *ptr = *obj.ptr; // copy the value\n}\n\nLine::~Line(void) {\n cout << \"Freeing memory!\" << endl;\n delete ptr;\n}\n\nint Line::getLength( void ) {\n return *ptr;\n}\n\nvoid display(Line obj) {\n cout << \"Length of line : \" << obj.getLength() <<endl;\n}\n\n// Main function for the program\nint main() {\n Line line(10);\n\n display(line);\n\n return 0;\n}" }, { "code": null, "e": 4101, "s": 4020, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4221, "s": 4101, "text": "Normal constructor allocating ptr\nCopy constructor allocating ptr.\nLength of line : 10\nFreeing memory!\nFreeing memory!\n" }, { "code": null, "e": 4339, "s": 4221, "text": "Let us see the same example but with a small change to create another object using existing object of the same type −" }, { "code": null, "e": 5372, "s": 4339, "text": "#include <iostream>\n\nusing namespace std;\n\nclass Line {\n public:\n int getLength( void );\n Line( int len ); // simple constructor\n Line( const Line &obj); // copy constructor\n ~Line(); // destructor\n\n private:\n int *ptr;\n};\n\n// Member functions definitions including constructor\nLine::Line(int len) {\n cout << \"Normal constructor allocating ptr\" << endl;\n \n // allocate memory for the pointer;\n ptr = new int;\n *ptr = len;\n}\n\nLine::Line(const Line &obj) {\n cout << \"Copy constructor allocating ptr.\" << endl;\n ptr = new int;\n *ptr = *obj.ptr; // copy the value\n}\n\nLine::~Line(void) {\n cout << \"Freeing memory!\" << endl;\n delete ptr;\n}\n\nint Line::getLength( void ) {\n return *ptr;\n}\n\nvoid display(Line obj) {\n cout << \"Length of line : \" << obj.getLength() <<endl;\n}\n\n// Main function for the program\nint main() {\n\n Line line1(10);\n\n Line line2 = line1; // This also calls copy constructor\n\n display(line1);\n display(line2);\n\n return 0;\n}" }, { "code": null, "e": 5453, "s": 5372, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5691, "s": 5453, "text": "Normal constructor allocating ptr\nCopy constructor allocating ptr.\nCopy constructor allocating ptr.\nLength of line : 10\nFreeing memory!\nCopy constructor allocating ptr.\nLength of line : 10\nFreeing memory!\nFreeing memory!\nFreeing memory!\n" }, { "code": null, "e": 5728, "s": 5691, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 5747, "s": 5728, "text": " Arnab Chakraborty" }, { "code": null, "e": 5779, "s": 5747, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 5802, "s": 5779, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 5838, "s": 5802, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 5855, "s": 5838, "text": " Frahaan Hussain" }, { "code": null, "e": 5890, "s": 5855, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5907, "s": 5890, "text": " Frahaan Hussain" }, { "code": null, "e": 5942, "s": 5907, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5959, "s": 5942, "text": " Frahaan Hussain" }, { "code": null, "e": 5994, "s": 5959, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6011, "s": 5994, "text": " Frahaan Hussain" }, { "code": null, "e": 6018, "s": 6011, "text": " Print" }, { "code": null, "e": 6029, "s": 6018, "text": " Add Notes" } ]
Data Labelling. The Triple-Barrier Method | by Ke Gui | Towards Data Science
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. Warning: There is no magical formula or Holy Grail here, though a new world might open the door for you. Note 1: How to install mlfinlab package without error messages can be found here. Note 2: If you are reading Advances in Financial Machine Learning by Marcos Prado. 7. Fractionally Differentiated Features is Chapter 5 about Fractionally Differentiated Features. 8. Data Labelling is Chapter 3 about The Triple-barrier Method. And 9. Meta-labeling is Chapter 3.6 on page 50. I have planned to go through each chapter step by step as I haven't found a very detailed explanation of those concepts in each chapter yet. Please stay tuned! Identifying OutliersIdentifying Outliers — Part TwoIdentifying Outliers — Part ThreeStylized FactsFeature Engineering & Feature SelectionData TransformationFractionally Differentiated FeaturesData LabellingMeta-labeling and Stacking Identifying Outliers Identifying Outliers — Part Two Identifying Outliers — Part Three Stylized Facts Feature Engineering & Feature Selection Data Transformation Fractionally Differentiated Features Data Labelling Meta-labeling and Stacking The triple-barrier method labels an observation according to the first barrier touched out of three barriers introduced in Chapter 3 of Advances in Financial Machine Learning by Marcos Prado1. The conventional way to label the data is by using the next day (lagged) return with the fixed-time horizon method. This method can be described as follows. and There are several drawbacks about this popular conventional labelling method. First, time bars do not exhibit good statistical properties. Second, the same threshold τ is applied regardless of the observed volatility. Basically, labelling doesn’t reflect the current state of the investment. Moreover, in a real case, the chance is that you may not want to sell the next day. Therefore, triple-barrier method makes more sense in practice as it is path-dependent. You can make sound decisions depending on how many days you are planning to hold the stock and what’s happening to the stock during that period. The original code from Chapter 3 of Advances in Financial Machine Learning is created for high-frequency trading, using high-frequency data, and most are intraday data. If you are using daily data, we need to tweak the code a little bit. I also refracted most of the code from the book to make it beginner-friendly by heavily utilizing padas DataFrame structure to store all the information in one place. By this way, it makes life so much easier later on when you start to analysis or plot the data. At the meantime, I employed more complicated approaches such as Average True Range as the daily volatility. You can see all the code at the end of this article. The intuition is like finding outliers as described in my previous articles. The outliers just like the breakthrough in stock trading, which define all the barriers and forming a window for you to make a buy or sell decision. If you haven’t read it, you can always go back to here, here and here. According to Advances in Financial Machine Learning by Marcos Prado1, Triple Barrier method is: Basically, what we are doing here is: We will buy in a stock (let’s say Apple) and hold it for 10 days. If the price is going down and trigger the stop loss alarm we exit at the stop-loss limit, or if the price is going up, we take the profit at a certain point. In an extreme case, the stock price goes sideway, we exit at a certain day after holding it for a while. Assume we have a simple equity management rule: Never risk more than 2% of your total capital in a trade. Always look to trade only those opportunities where you will have a 3:1 earnings ratio. Based on those simple rules, we make a trading plan before we put real money into any stocks. To infuse that trading plan into stock price movement, we need 3 barriers. What are those 3 barriers? 4 lines form a frame, defines a window as showing below. The x-axis is the datetime, y-axis is the stock price. Line a,d belong to x-axis, which is the datatime index, and line b,c belong to y-axis which is the stock price. a: starting date b: stop-loss exit price c: the profit-taking exit price d: starting date + the number of days you are planning to hold it. b and c don’t have to be same. Remember we want to set profit-taking and stop-loss limits that are a function of the risks involved in a bet. And we are always looking to trade only those opportunities where you will have a 3:1 earnings ratio. Here to set c = 3 * b will do the trick. There are few videos on this topic, I just found one on YouTube. OK, without further ado, let’s dive in the code. For consistency, in all the 📈Python for finance series, I will try to reuse the same data as much as I can. More details about data preparation can be found here, here and here or you can refer back to my previous article. Or if you like, you can ignore all the code below and use whatever clean data you have at hand, it won’t affect the things we are going to do together. import pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.style.use('seaborn')plt.rcParams['figure.figsize'] = [16, 9]plt.rcParams['figure.dpi'] = 300plt.rcParams['font.size'] = 20plt.rcParams['axes.labelsize'] = 20plt.rcParams['axes.titlesize'] = 24plt.rcParams['xtick.labelsize'] = 16plt.rcParams['ytick.labelsize'] = 16plt.rcParams['font.family'] = 'serif'import yfinance as yfdef get_data(symbols, begin_date=None,end_date=None): df = yf.download('AAPL', start = begin_date, auto_adjust=True,#only download adjusted data end= end_date) #my convention: always lowercase df.columns = ['open','high','low', 'close','volume'] return dfApple_stock = get_data('AAPL', '2000-01-01', '2010-12-31') price = Apple_stock['close'] The original code (below) of getting daily volatility is for intraday data, which is consecutive data with no weekend, nonbusiness days, etc.. def getDailyVol(close,span0=100): # daily vol, reindexed to close df0=close.index.searchsorted(close.index-pd.Timedelta(days=1)) df0=df0[df0>0] df0=pd.Series(close.index[df0 – 1], index=close.index[close.shape[0]-df0.shape[0]:]) df0=close.loc[df0.index]/close.loc[df0.values].values-1 # daily returns df0=df0.ewm(span=span0).std() return df0 If you run this function, you will get an error message: SyntaxError: invalid character in identifier, that is because close.index[df0–1]. It can be fixed like this: def getDailyVol(close,span0=100): # daily vol, reindexed to close df0=close.index.searchsorted(close.index-pd.Timedelta(days=1)) df0=df0[df0>0] a = df0 -1 #using a variable to avoid the error message. df0=pd.Series(close.index[a], index=close.index[close.shape[0]-df0.shape[0]:]) df0=close.loc[df0.index]/close.loc[df0.values].values-1 # daily returns df0=df0.ewm(span=span0).std() return df0 If you use daily data instead of intraday data, you will end up with lots of duplicates as the date moved backwards 1 day and causing many NaN later on as many dates will be non-business days. df0=close.index.searchsorted(close.index-pd.Timedelta(days=1))pd.Series(df0).value_counts() 2766–2189 = 577 duplicates. With daily data, we can use a simple percentage returns’ Exponential weighted moving average (EWM) as the volatility. def get_Daily_Volatility(close,span0=20): # simple percentage returns df0=close.pct_change() # 20 days, a month EWM's std as boundary df0=df0.ewm(span=span0).std() df0.dropna(inplace=True) return df0df0 = get_Daily_Volatility(price)df0 Depending upon the type of problem, we can choose more complicated approaches such as Average True Range (a technical analysis indicator that measures market volatility). The formula for ATR is: The first step in calculating ATR is to find a series of true range values for a stock price. The price range of an asset for a given trading day is simply its high minus its low, while the true range is current high less the current low; the absolute value of the current high less the previous close; and the absolute value of the current low less the previous close. The average true range is then a moving average, generally using 14 days, of the true ranges. def get_atr(stock, win=14): atr_df = pd.Series(index=stock.index) high = pd.Series(Apple_stock.high.rolling( \ win, min_periods=win)) low = pd.Series(Apple_stock.low.rolling( \ win, min_periods=win)) close = pd.Series(Apple_stock.close.rolling( \ win, min_periods=win)) for i in range(len(stock.index)): tr=np.max([(high[i] - low[i]), \ np.abs(high[i] - close[i]), \ np.abs(low[i] - close[i])], \ axis=0) atr_df[i] = tr.sum() / win return atr_dfget_atr(Apple_stock, 14)atr_df Before we start to work on the barriers, a few parameters need to be decided. #set the boundary of barriers, based on 20 days EWMdaily_volatility = get_Daily_Volatility(price)# how many days we hold the stock which set the vertical barriert_final = 10 #the up and low boundary multipliersupper_lower_multipliers = [2, 2]#allign the indexprices = price[daily_volatility.index] Here, I will use pd.DataFrame as the container to add all the information into one place. def get_3_barriers(): #create a container barriers = pd.DataFrame(columns=['days_passed', 'price', 'vert_barrier', \ 'top_barrier', 'bottom_barrier'], \ index = daily_volatility.index) for day, vol in daily_volatility.iteritems(): days_passed = len(daily_volatility.loc \ [daily_volatility.index[0] : day]) #set the vertical barrier if (days_passed + t_final < len(daily_volatility.index) \ and t_final != 0): vert_barrier = daily_volatility.index[ days_passed + t_final] else: vert_barrier = np.nan #set the top barrier if upper_lower_multipliers[0] > 0: top_barrier = prices.loc[day] + prices.loc[day] * \ upper_lower_multipliers[0] * vol else: #set it to NaNs top_barrier = pd.Series(index=prices.index) #set the bottom barrier if upper_lower_multipliers[1] > 0: bottom_barrier = prices.loc[day] - prices.loc[day] * \ upper_lower_multipliers[1] * vol else: #set it to NaNs bottom_barrier = pd.Series(index=prices.index) barriers.loc[day, ['days_passed', 'price', 'vert_barrier','top_barrier', 'bottom_barrier']] = \ days_passed, prices.loc[day], vert_barrier, top_barrier, bottom_barrier return barriers Let’s have a look at all the barriers. barriers = get_barriers()barriers and have a close look at all the data information. barriers.info() Only the vert_barrier has 11 NaN value at the end as the t_final was set as 10 days. The next step is to label each entry according to which barrier was touched first. I add a new column ‘out’ to the end of barriers. barriers['out'] = Nonebarriers.head() Now, we can work on the labels. def get_labels():'''start: first day of the windowend:last day of the windowprice_initial: first day stock priceprice_final:last day stock pricetop_barrier: profit taking limitbottom_barrier:stop loss limtcondition_pt:top_barrier touching conditoncondition_sl:bottom_barrier touching conditon''' for i in range(len(barriers.index)): start = barriers.index[i] end = barriers.vert_barrier[i] if pd.notna(end): # assign the initial and final price price_initial = barriers.price[start] price_final = barriers.price[end] # assign the top and bottom barriers top_barrier = barriers.top_barrier[i] bottom_barrier = barriers.bottom_barrier[i] #set the profit taking and stop loss conditons condition_pt = (barriers.price[start: end] >= \ top_barrier).any() condition_sl = (barriers.price[start: end] <= \ bottom_barrier).any() #assign the labels if condition_pt: barriers['out'][i] = 1 elif condition_sl: barriers['out'][i] = -1 else: barriers['out'][i] = max( [(price_final - price_initial)/ (top_barrier - price_initial), \ (price_final - price_initial)/ \ (price_initial - bottom_barrier)],\ key=abs) returnget_labels()barriers We can plot the ‘out’ to see its distribution. plt.plot(barriers.out,'bo') and count how many profit taking and stop loss limit were triggered. barriers.out.value_counts() There are 1385 profit-taking and 837 stop-losing out of 2764 data points. 542 cases exit because time is up. We can also pick a random date and show it on a graph. fig,ax = plt.subplots()ax.set(title='Apple stock price', xlabel='date', ylabel='price')ax.plot(barriers.price[100: 200])start = barriers.index[120]end = barriers.vert_barrier[120]upper_barrier = barriers.top_barrier[120]lower_barrier = barriers.bottom_barrier[120]ax.plot([start, end], [upper_barrier, upper_barrier], 'r--');ax.plot([start, end], [lower_barrier, lower_barrier], 'r--');ax.plot([start, end], [(lower_barrier + upper_barrier)*0.5, \ (lower_barrier + upper_barrier)*0.5], 'r--');ax.plot([start, start], [lower_barrier, upper_barrier], 'r-');ax.plot([end, end], [lower_barrier, upper_barrier], 'r-'); We also can draw a dynamic graph with easy. fig,ax = plt.subplots()ax.set(title='Apple stock price', xlabel='date', ylabel='price')ax.plot(barriers.price[100: 200])start = barriers.index[120]end = barriers.index[120+t_final]upper_barrier = barriers.top_barrier[120]lower_barrier = barriers.bottom_barrier[120]ax.plot(barriers.index[120:120+t_final+1], barriers.top_barrier[start:end], 'r--');ax.plot(barriers.index[120:120+t_final+1], barriers.bottom_barrier[start:end], 'r--');ax.plot([start, end], [(lower_barrier + upper_barrier)*0.5, \ (lower_barrier + upper_barrier)*0.5], 'r--');ax.plot([start, start], [lower_barrier, upper_barrier], 'r-');ax.plot([end, end], [barriers.bottom_barrier[end], barriers.top_barrier[end]], 'r-'); Recap the parameters we have: Data: Apple 10-years stock price Hold for: no more than 10 days Profit-taking boundary: 2 times of 20 days return EWM std Stop-loss boundary: 2 times of 20 days return EWM std The rule we expect in the real case: Always look to trade only those opportunities where you will have a 3:1 earn ratio. Never risk more than 2% of your total capital in a trade. The first rule can be easily realized by setting upper_lower_multipliers = [3, 1]. The second one is about the trading size, the side times the size will enable us the calculate the risk (margin/edge). That will be meta-labelling in the next article. So, stay tuned! Here is all the code: import pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.style.use('seaborn')plt.rcParams['figure.figsize'] = [16, 9]plt.rcParams['figure.dpi'] = 300plt.rcParams['font.size'] = 20plt.rcParams['axes.labelsize'] = 20plt.rcParams['axes.titlesize'] = 24plt.rcParams['xtick.labelsize'] = 16plt.rcParams['ytick.labelsize'] = 16plt.rcParams['font.family'] = 'serif'import yfinance as yfdef get_data(symbols, begin_date=None,end_date=None): df = yf.download('AAPL', start = begin_date, auto_adjust=True,#only download adjusted data end= end_date) #my convention: always lowercase df.columns = ['open','high','low', 'close','volume'] return dfApple_stock = get_data('AAPL', '2000-01-01', '2010-12-31') price = Apple_stock['close']def get_Daily_Volatility(close,span0=20): # simple percentage returns df0=close.pct_change() # 20 days, a month EWM's std as boundary df0=df0.ewm(span=span0).std() df0.dropna(inplace=True) return df0df0 = get_Daily_Volatility(price)def get_atr(stock, win=14): atr_df = pd.Series(index=stock.index) high = pd.Series(Apple_stock.high.rolling( \ win, min_periods=win)) low = pd.Series(Apple_stock.low.rolling( \ win, min_periods=win)) close = pd.Series(Apple_stock.close.rolling( \ win, min_periods=win)) for i in range(len(stock.index)): tr=np.max([(high[i] - low[i]), \ np.abs(high[i] - close[i]), \ np.abs(low[i] - close[i])], \ axis=0) atr_df[i] = tr.sum() / win return atr_df#set the boundary of barriers, based on 20 days EWMdaily_volatility = get_Daily_Volatility(price)# how many days we hold the stock which set the vertical barriert_final = 10 #the up and low boundary multipliersupper_lower_multipliers = [2, 2]#allign the indexprices = price[daily_volatility.index]def get_3_barriers(): #create a container barriers = pd.DataFrame(columns=['days_passed', 'price', 'vert_barrier', \ 'top_barrier', 'bottom_barrier'], \ index = daily_volatility.index) for day, vol in daily_volatility.iteritems(): days_passed = len(daily_volatility.loc \ [daily_volatility.index[0] : day]) #set the vertical barrier if (days_passed + t_final < len(daily_volatility.index) \ and t_final != 0): vert_barrier = daily_volatility.index[ days_passed + t_final] else: vert_barrier = np.nan #set the top barrier if upper_lower_multipliers[0] > 0: top_barrier = prices.loc[day] + prices.loc[day] * \ upper_lower_multipliers[0] * vol else: #set it to NaNs top_barrier = pd.Series(index=prices.index) #set the bottom barrier if upper_lower_multipliers[1] > 0: bottom_barrier = prices.loc[day] - prices.loc[day] * \ upper_lower_multipliers[1] * vol else: #set it to NaNs bottom_barrier = pd.Series(index=prices.index) barriers.loc[day, ['days_passed', 'price', \ 'vert_barrier','top_barrier', 'bottom_barrier']] = \ days_passed, prices.loc[day], vert_barrier, \ top_barrier, bottom_barrierreturn barriersdef get_labels():'''start: first day of the windowend:last day of the windowprice_initial: first day stock priceprice_final:last day stock pricetop_barrier: profit taking limitbottom_barrier:stop loss limtcondition_pt:top_barrier touching conditoncondition_sl:bottom_barrier touching conditon'''for i in range(len(barriers.index)):start = barriers.index[i] end = barriers.vert_barrier[i]if pd.notna(end): # assign the initial and final price price_initial = barriers.price[start] price_final = barriers.price[end]# assign the top and bottom barriers top_barrier = barriers.top_barrier[i] bottom_barrier = barriers.bottom_barrier[i]#set the profit taking and stop loss conditons condition_pt = (barriers.price[start: end] >= \ top_barrier).any() condition_sl = (barriers.price[start: end] <= \ bottom_barrier).any()#assign the labels if condition_pt: barriers['out'][i] = 1 elif condition_sl: barriers['out'][i] = -1 else: barriers['out'][i] = max( [(price_final - price_initial)/ (top_barrier - price_initial), \ (price_final - price_initial)/ \ (price_initial - bottom_barrier)],\ key=abs) returnget_labels()barriersfig,ax = plt.subplots()ax.set(title='Apple stock price', xlabel='date', ylabel='price')ax.plot(barriers.price[100: 200])start = barriers.index[120]end = barriers.vert_barrier[120]upper_barrier = barriers.top_barrier[120]lower_barrier = barriers.bottom_barrier[120]ax.plot([start, end], [upper_barrier, upper_barrier], 'r--');ax.plot([start, end], [lower_barrier, lower_barrier], 'r--');ax.plot([start, end], [(lower_barrier + upper_barrier)*0.5, \ (lower_barrier + upper_barrier)*0.5], 'r--');ax.plot([start, start], [lower_barrier, upper_barrier], 'r-');ax.plot([end, end], [lower_barrier, upper_barrier], 'r-');#dynamic graphfig,ax = plt.subplots()ax.set(title='Apple stock price', xlabel='date', ylabel='price')ax.plot(barriers.price[100: 200])start = barriers.index[120]end = barriers.index[120+t_final]upper_barrier = barriers.top_barrier[120]lower_barrier = barriers.bottom_barrier[120]ax.plot(barriers.index[120:120+t_final+1], barriers.top_barrier[start:end], 'r--');ax.plot(barriers.index[120:120+t_final+1], barriers.bottom_barrier[start:end], 'r--');ax.plot([start, end], [(lower_barrier + upper_barrier)*0.5, \ (lower_barrier + upper_barrier)*0.5], 'r--');ax.plot([start, start], [lower_barrier, upper_barrier], 'r-');ax.plot([end, end], [barriers.bottom_barrier[end], barriers.top_barrier[end]], 'r-'); Introduction to “Advances in Financial Machine Learning” by Lopez de Prado Introduction to “Advances in Financial Machine Learning” by Lopez de Prado
[ { "code": null, "e": 472, "s": 172, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 577, "s": 472, "text": "Warning: There is no magical formula or Holy Grail here, though a new world might open the door for you." }, { "code": null, "e": 659, "s": 577, "text": "Note 1: How to install mlfinlab package without error messages can be found here." }, { "code": null, "e": 1111, "s": 659, "text": "Note 2: If you are reading Advances in Financial Machine Learning by Marcos Prado. 7. Fractionally Differentiated Features is Chapter 5 about Fractionally Differentiated Features. 8. Data Labelling is Chapter 3 about The Triple-barrier Method. And 9. Meta-labeling is Chapter 3.6 on page 50. I have planned to go through each chapter step by step as I haven't found a very detailed explanation of those concepts in each chapter yet. Please stay tuned!" }, { "code": null, "e": 1344, "s": 1111, "text": "Identifying OutliersIdentifying Outliers — Part TwoIdentifying Outliers — Part ThreeStylized FactsFeature Engineering & Feature SelectionData TransformationFractionally Differentiated FeaturesData LabellingMeta-labeling and Stacking" }, { "code": null, "e": 1365, "s": 1344, "text": "Identifying Outliers" }, { "code": null, "e": 1397, "s": 1365, "text": "Identifying Outliers — Part Two" }, { "code": null, "e": 1431, "s": 1397, "text": "Identifying Outliers — Part Three" }, { "code": null, "e": 1446, "s": 1431, "text": "Stylized Facts" }, { "code": null, "e": 1486, "s": 1446, "text": "Feature Engineering & Feature Selection" }, { "code": null, "e": 1506, "s": 1486, "text": "Data Transformation" }, { "code": null, "e": 1543, "s": 1506, "text": "Fractionally Differentiated Features" }, { "code": null, "e": 1558, "s": 1543, "text": "Data Labelling" }, { "code": null, "e": 1585, "s": 1558, "text": "Meta-labeling and Stacking" }, { "code": null, "e": 1935, "s": 1585, "text": "The triple-barrier method labels an observation according to the first barrier touched out of three barriers introduced in Chapter 3 of Advances in Financial Machine Learning by Marcos Prado1. The conventional way to label the data is by using the next day (lagged) return with the fixed-time horizon method. This method can be described as follows." }, { "code": null, "e": 1939, "s": 1935, "text": "and" }, { "code": null, "e": 2231, "s": 1939, "text": "There are several drawbacks about this popular conventional labelling method. First, time bars do not exhibit good statistical properties. Second, the same threshold τ is applied regardless of the observed volatility. Basically, labelling doesn’t reflect the current state of the investment." }, { "code": null, "e": 2547, "s": 2231, "text": "Moreover, in a real case, the chance is that you may not want to sell the next day. Therefore, triple-barrier method makes more sense in practice as it is path-dependent. You can make sound decisions depending on how many days you are planning to hold the stock and what’s happening to the stock during that period." }, { "code": null, "e": 3209, "s": 2547, "text": "The original code from Chapter 3 of Advances in Financial Machine Learning is created for high-frequency trading, using high-frequency data, and most are intraday data. If you are using daily data, we need to tweak the code a little bit. I also refracted most of the code from the book to make it beginner-friendly by heavily utilizing padas DataFrame structure to store all the information in one place. By this way, it makes life so much easier later on when you start to analysis or plot the data. At the meantime, I employed more complicated approaches such as Average True Range as the daily volatility. You can see all the code at the end of this article." }, { "code": null, "e": 3506, "s": 3209, "text": "The intuition is like finding outliers as described in my previous articles. The outliers just like the breakthrough in stock trading, which define all the barriers and forming a window for you to make a buy or sell decision. If you haven’t read it, you can always go back to here, here and here." }, { "code": null, "e": 3602, "s": 3506, "text": "According to Advances in Financial Machine Learning by Marcos Prado1, Triple Barrier method is:" }, { "code": null, "e": 3640, "s": 3602, "text": "Basically, what we are doing here is:" }, { "code": null, "e": 3970, "s": 3640, "text": "We will buy in a stock (let’s say Apple) and hold it for 10 days. If the price is going down and trigger the stop loss alarm we exit at the stop-loss limit, or if the price is going up, we take the profit at a certain point. In an extreme case, the stock price goes sideway, we exit at a certain day after holding it for a while." }, { "code": null, "e": 4018, "s": 3970, "text": "Assume we have a simple equity management rule:" }, { "code": null, "e": 4076, "s": 4018, "text": "Never risk more than 2% of your total capital in a trade." }, { "code": null, "e": 4164, "s": 4076, "text": "Always look to trade only those opportunities where you will have a 3:1 earnings ratio." }, { "code": null, "e": 4417, "s": 4164, "text": "Based on those simple rules, we make a trading plan before we put real money into any stocks. To infuse that trading plan into stock price movement, we need 3 barriers. What are those 3 barriers? 4 lines form a frame, defines a window as showing below." }, { "code": null, "e": 4584, "s": 4417, "text": "The x-axis is the datetime, y-axis is the stock price. Line a,d belong to x-axis, which is the datatime index, and line b,c belong to y-axis which is the stock price." }, { "code": null, "e": 4601, "s": 4584, "text": "a: starting date" }, { "code": null, "e": 4625, "s": 4601, "text": "b: stop-loss exit price" }, { "code": null, "e": 4657, "s": 4625, "text": "c: the profit-taking exit price" }, { "code": null, "e": 4724, "s": 4657, "text": "d: starting date + the number of days you are planning to hold it." }, { "code": null, "e": 5009, "s": 4724, "text": "b and c don’t have to be same. Remember we want to set profit-taking and stop-loss limits that are a function of the risks involved in a bet. And we are always looking to trade only those opportunities where you will have a 3:1 earnings ratio. Here to set c = 3 * b will do the trick." }, { "code": null, "e": 5074, "s": 5009, "text": "There are few videos on this topic, I just found one on YouTube." }, { "code": null, "e": 5123, "s": 5074, "text": "OK, without further ado, let’s dive in the code." }, { "code": null, "e": 5498, "s": 5123, "text": "For consistency, in all the 📈Python for finance series, I will try to reuse the same data as much as I can. More details about data preparation can be found here, here and here or you can refer back to my previous article. Or if you like, you can ignore all the code below and use whatever clean data you have at hand, it won’t affect the things we are going to do together." }, { "code": null, "e": 6312, "s": 5498, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.style.use('seaborn')plt.rcParams['figure.figsize'] = [16, 9]plt.rcParams['figure.dpi'] = 300plt.rcParams['font.size'] = 20plt.rcParams['axes.labelsize'] = 20plt.rcParams['axes.titlesize'] = 24plt.rcParams['xtick.labelsize'] = 16plt.rcParams['ytick.labelsize'] = 16plt.rcParams['font.family'] = 'serif'import yfinance as yfdef get_data(symbols, begin_date=None,end_date=None): df = yf.download('AAPL', start = begin_date, auto_adjust=True,#only download adjusted data end= end_date) #my convention: always lowercase df.columns = ['open','high','low', 'close','volume'] return dfApple_stock = get_data('AAPL', '2000-01-01', '2010-12-31') price = Apple_stock['close']" }, { "code": null, "e": 6455, "s": 6312, "text": "The original code (below) of getting daily volatility is for intraday data, which is consecutive data with no weekend, nonbusiness days, etc.." }, { "code": null, "e": 6840, "s": 6455, "text": "def getDailyVol(close,span0=100): # daily vol, reindexed to close df0=close.index.searchsorted(close.index-pd.Timedelta(days=1)) df0=df0[df0>0] df0=pd.Series(close.index[df0 – 1], index=close.index[close.shape[0]-df0.shape[0]:]) df0=close.loc[df0.index]/close.loc[df0.values].values-1 # daily returns df0=df0.ewm(span=span0).std() return df0" }, { "code": null, "e": 7006, "s": 6840, "text": "If you run this function, you will get an error message: SyntaxError: invalid character in identifier, that is because close.index[df0–1]. It can be fixed like this:" }, { "code": null, "e": 7445, "s": 7006, "text": "def getDailyVol(close,span0=100): # daily vol, reindexed to close df0=close.index.searchsorted(close.index-pd.Timedelta(days=1)) df0=df0[df0>0] a = df0 -1 #using a variable to avoid the error message. df0=pd.Series(close.index[a], index=close.index[close.shape[0]-df0.shape[0]:]) df0=close.loc[df0.index]/close.loc[df0.values].values-1 # daily returns df0=df0.ewm(span=span0).std() return df0" }, { "code": null, "e": 7638, "s": 7445, "text": "If you use daily data instead of intraday data, you will end up with lots of duplicates as the date moved backwards 1 day and causing many NaN later on as many dates will be non-business days." }, { "code": null, "e": 7730, "s": 7638, "text": "df0=close.index.searchsorted(close.index-pd.Timedelta(days=1))pd.Series(df0).value_counts()" }, { "code": null, "e": 7758, "s": 7730, "text": "2766–2189 = 577 duplicates." }, { "code": null, "e": 7876, "s": 7758, "text": "With daily data, we can use a simple percentage returns’ Exponential weighted moving average (EWM) as the volatility." }, { "code": null, "e": 8130, "s": 7876, "text": "def get_Daily_Volatility(close,span0=20): # simple percentage returns df0=close.pct_change() # 20 days, a month EWM's std as boundary df0=df0.ewm(span=span0).std() df0.dropna(inplace=True) return df0df0 = get_Daily_Volatility(price)df0" }, { "code": null, "e": 8301, "s": 8130, "text": "Depending upon the type of problem, we can choose more complicated approaches such as Average True Range (a technical analysis indicator that measures market volatility)." }, { "code": null, "e": 8325, "s": 8301, "text": "The formula for ATR is:" }, { "code": null, "e": 8789, "s": 8325, "text": "The first step in calculating ATR is to find a series of true range values for a stock price. The price range of an asset for a given trading day is simply its high minus its low, while the true range is current high less the current low; the absolute value of the current high less the previous close; and the absolute value of the current low less the previous close. The average true range is then a moving average, generally using 14 days, of the true ranges." }, { "code": null, "e": 9432, "s": 8789, "text": "def get_atr(stock, win=14): atr_df = pd.Series(index=stock.index) high = pd.Series(Apple_stock.high.rolling( \\ win, min_periods=win)) low = pd.Series(Apple_stock.low.rolling( \\ win, min_periods=win)) close = pd.Series(Apple_stock.close.rolling( \\ win, min_periods=win)) for i in range(len(stock.index)): tr=np.max([(high[i] - low[i]), \\ np.abs(high[i] - close[i]), \\ np.abs(low[i] - close[i])], \\ axis=0) atr_df[i] = tr.sum() / win return atr_dfget_atr(Apple_stock, 14)atr_df" }, { "code": null, "e": 9510, "s": 9432, "text": "Before we start to work on the barriers, a few parameters need to be decided." }, { "code": null, "e": 9808, "s": 9510, "text": "#set the boundary of barriers, based on 20 days EWMdaily_volatility = get_Daily_Volatility(price)# how many days we hold the stock which set the vertical barriert_final = 10 #the up and low boundary multipliersupper_lower_multipliers = [2, 2]#allign the indexprices = price[daily_volatility.index]" }, { "code": null, "e": 9898, "s": 9808, "text": "Here, I will use pd.DataFrame as the container to add all the information into one place." }, { "code": null, "e": 11362, "s": 9898, "text": "def get_3_barriers(): #create a container barriers = pd.DataFrame(columns=['days_passed', 'price', 'vert_barrier', \\ 'top_barrier', 'bottom_barrier'], \\ index = daily_volatility.index) for day, vol in daily_volatility.iteritems(): days_passed = len(daily_volatility.loc \\ [daily_volatility.index[0] : day]) #set the vertical barrier if (days_passed + t_final < len(daily_volatility.index) \\ and t_final != 0): vert_barrier = daily_volatility.index[ days_passed + t_final] else: vert_barrier = np.nan #set the top barrier if upper_lower_multipliers[0] > 0: top_barrier = prices.loc[day] + prices.loc[day] * \\ upper_lower_multipliers[0] * vol else: #set it to NaNs top_barrier = pd.Series(index=prices.index) #set the bottom barrier if upper_lower_multipliers[1] > 0: bottom_barrier = prices.loc[day] - prices.loc[day] * \\ upper_lower_multipliers[1] * vol else: #set it to NaNs bottom_barrier = pd.Series(index=prices.index) barriers.loc[day, ['days_passed', 'price', 'vert_barrier','top_barrier', 'bottom_barrier']] = \\ days_passed, prices.loc[day], vert_barrier, top_barrier, bottom_barrier return barriers" }, { "code": null, "e": 11401, "s": 11362, "text": "Let’s have a look at all the barriers." }, { "code": null, "e": 11435, "s": 11401, "text": "barriers = get_barriers()barriers" }, { "code": null, "e": 11486, "s": 11435, "text": "and have a close look at all the data information." }, { "code": null, "e": 11502, "s": 11486, "text": "barriers.info()" }, { "code": null, "e": 11587, "s": 11502, "text": "Only the vert_barrier has 11 NaN value at the end as the t_final was set as 10 days." }, { "code": null, "e": 11719, "s": 11587, "text": "The next step is to label each entry according to which barrier was touched first. I add a new column ‘out’ to the end of barriers." }, { "code": null, "e": 11757, "s": 11719, "text": "barriers['out'] = Nonebarriers.head()" }, { "code": null, "e": 11789, "s": 11757, "text": "Now, we can work on the labels." }, { "code": null, "e": 13287, "s": 11789, "text": "def get_labels():'''start: first day of the windowend:last day of the windowprice_initial: first day stock priceprice_final:last day stock pricetop_barrier: profit taking limitbottom_barrier:stop loss limtcondition_pt:top_barrier touching conditoncondition_sl:bottom_barrier touching conditon''' for i in range(len(barriers.index)): start = barriers.index[i] end = barriers.vert_barrier[i] if pd.notna(end): # assign the initial and final price price_initial = barriers.price[start] price_final = barriers.price[end] # assign the top and bottom barriers top_barrier = barriers.top_barrier[i] bottom_barrier = barriers.bottom_barrier[i] #set the profit taking and stop loss conditons condition_pt = (barriers.price[start: end] >= \\ top_barrier).any() condition_sl = (barriers.price[start: end] <= \\ bottom_barrier).any() #assign the labels if condition_pt: barriers['out'][i] = 1 elif condition_sl: barriers['out'][i] = -1 else: barriers['out'][i] = max( [(price_final - price_initial)/ (top_barrier - price_initial), \\ (price_final - price_initial)/ \\ (price_initial - bottom_barrier)],\\ key=abs) returnget_labels()barriers" }, { "code": null, "e": 13334, "s": 13287, "text": "We can plot the ‘out’ to see its distribution." }, { "code": null, "e": 13362, "s": 13334, "text": "plt.plot(barriers.out,'bo')" }, { "code": null, "e": 13431, "s": 13362, "text": "and count how many profit taking and stop loss limit were triggered." }, { "code": null, "e": 13459, "s": 13431, "text": "barriers.out.value_counts()" }, { "code": null, "e": 13568, "s": 13459, "text": "There are 1385 profit-taking and 837 stop-losing out of 2764 data points. 542 cases exit because time is up." }, { "code": null, "e": 13623, "s": 13568, "text": "We can also pick a random date and show it on a graph." }, { "code": null, "e": 14265, "s": 13623, "text": "fig,ax = plt.subplots()ax.set(title='Apple stock price', xlabel='date', ylabel='price')ax.plot(barriers.price[100: 200])start = barriers.index[120]end = barriers.vert_barrier[120]upper_barrier = barriers.top_barrier[120]lower_barrier = barriers.bottom_barrier[120]ax.plot([start, end], [upper_barrier, upper_barrier], 'r--');ax.plot([start, end], [lower_barrier, lower_barrier], 'r--');ax.plot([start, end], [(lower_barrier + upper_barrier)*0.5, \\ (lower_barrier + upper_barrier)*0.5], 'r--');ax.plot([start, start], [lower_barrier, upper_barrier], 'r-');ax.plot([end, end], [lower_barrier, upper_barrier], 'r-');" }, { "code": null, "e": 14309, "s": 14265, "text": "We also can draw a dynamic graph with easy." }, { "code": null, "e": 15026, "s": 14309, "text": "fig,ax = plt.subplots()ax.set(title='Apple stock price', xlabel='date', ylabel='price')ax.plot(barriers.price[100: 200])start = barriers.index[120]end = barriers.index[120+t_final]upper_barrier = barriers.top_barrier[120]lower_barrier = barriers.bottom_barrier[120]ax.plot(barriers.index[120:120+t_final+1], barriers.top_barrier[start:end], 'r--');ax.plot(barriers.index[120:120+t_final+1], barriers.bottom_barrier[start:end], 'r--');ax.plot([start, end], [(lower_barrier + upper_barrier)*0.5, \\ (lower_barrier + upper_barrier)*0.5], 'r--');ax.plot([start, start], [lower_barrier, upper_barrier], 'r-');ax.plot([end, end], [barriers.bottom_barrier[end], barriers.top_barrier[end]], 'r-');" }, { "code": null, "e": 15056, "s": 15026, "text": "Recap the parameters we have:" }, { "code": null, "e": 15089, "s": 15056, "text": "Data: Apple 10-years stock price" }, { "code": null, "e": 15120, "s": 15089, "text": "Hold for: no more than 10 days" }, { "code": null, "e": 15178, "s": 15120, "text": "Profit-taking boundary: 2 times of 20 days return EWM std" }, { "code": null, "e": 15232, "s": 15178, "text": "Stop-loss boundary: 2 times of 20 days return EWM std" }, { "code": null, "e": 15269, "s": 15232, "text": "The rule we expect in the real case:" }, { "code": null, "e": 15353, "s": 15269, "text": "Always look to trade only those opportunities where you will have a 3:1 earn ratio." }, { "code": null, "e": 15411, "s": 15353, "text": "Never risk more than 2% of your total capital in a trade." }, { "code": null, "e": 15678, "s": 15411, "text": "The first rule can be easily realized by setting upper_lower_multipliers = [3, 1]. The second one is about the trading size, the side times the size will enable us the calculate the risk (margin/edge). That will be meta-labelling in the next article. So, stay tuned!" }, { "code": null, "e": 15700, "s": 15678, "text": "Here is all the code:" }, { "code": null, "e": 21942, "s": 15700, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.style.use('seaborn')plt.rcParams['figure.figsize'] = [16, 9]plt.rcParams['figure.dpi'] = 300plt.rcParams['font.size'] = 20plt.rcParams['axes.labelsize'] = 20plt.rcParams['axes.titlesize'] = 24plt.rcParams['xtick.labelsize'] = 16plt.rcParams['ytick.labelsize'] = 16plt.rcParams['font.family'] = 'serif'import yfinance as yfdef get_data(symbols, begin_date=None,end_date=None): df = yf.download('AAPL', start = begin_date, auto_adjust=True,#only download adjusted data end= end_date) #my convention: always lowercase df.columns = ['open','high','low', 'close','volume'] return dfApple_stock = get_data('AAPL', '2000-01-01', '2010-12-31') price = Apple_stock['close']def get_Daily_Volatility(close,span0=20): # simple percentage returns df0=close.pct_change() # 20 days, a month EWM's std as boundary df0=df0.ewm(span=span0).std() df0.dropna(inplace=True) return df0df0 = get_Daily_Volatility(price)def get_atr(stock, win=14): atr_df = pd.Series(index=stock.index) high = pd.Series(Apple_stock.high.rolling( \\ win, min_periods=win)) low = pd.Series(Apple_stock.low.rolling( \\ win, min_periods=win)) close = pd.Series(Apple_stock.close.rolling( \\ win, min_periods=win)) for i in range(len(stock.index)): tr=np.max([(high[i] - low[i]), \\ np.abs(high[i] - close[i]), \\ np.abs(low[i] - close[i])], \\ axis=0) atr_df[i] = tr.sum() / win return atr_df#set the boundary of barriers, based on 20 days EWMdaily_volatility = get_Daily_Volatility(price)# how many days we hold the stock which set the vertical barriert_final = 10 #the up and low boundary multipliersupper_lower_multipliers = [2, 2]#allign the indexprices = price[daily_volatility.index]def get_3_barriers(): #create a container barriers = pd.DataFrame(columns=['days_passed', 'price', 'vert_barrier', \\ 'top_barrier', 'bottom_barrier'], \\ index = daily_volatility.index) for day, vol in daily_volatility.iteritems(): days_passed = len(daily_volatility.loc \\ [daily_volatility.index[0] : day]) #set the vertical barrier if (days_passed + t_final < len(daily_volatility.index) \\ and t_final != 0): vert_barrier = daily_volatility.index[ days_passed + t_final] else: vert_barrier = np.nan #set the top barrier if upper_lower_multipliers[0] > 0: top_barrier = prices.loc[day] + prices.loc[day] * \\ upper_lower_multipliers[0] * vol else: #set it to NaNs top_barrier = pd.Series(index=prices.index) #set the bottom barrier if upper_lower_multipliers[1] > 0: bottom_barrier = prices.loc[day] - prices.loc[day] * \\ upper_lower_multipliers[1] * vol else: #set it to NaNs bottom_barrier = pd.Series(index=prices.index) barriers.loc[day, ['days_passed', 'price', \\ 'vert_barrier','top_barrier', 'bottom_barrier']] = \\ days_passed, prices.loc[day], vert_barrier, \\ top_barrier, bottom_barrierreturn barriersdef get_labels():'''start: first day of the windowend:last day of the windowprice_initial: first day stock priceprice_final:last day stock pricetop_barrier: profit taking limitbottom_barrier:stop loss limtcondition_pt:top_barrier touching conditoncondition_sl:bottom_barrier touching conditon'''for i in range(len(barriers.index)):start = barriers.index[i] end = barriers.vert_barrier[i]if pd.notna(end): # assign the initial and final price price_initial = barriers.price[start] price_final = barriers.price[end]# assign the top and bottom barriers top_barrier = barriers.top_barrier[i] bottom_barrier = barriers.bottom_barrier[i]#set the profit taking and stop loss conditons condition_pt = (barriers.price[start: end] >= \\ top_barrier).any() condition_sl = (barriers.price[start: end] <= \\ bottom_barrier).any()#assign the labels if condition_pt: barriers['out'][i] = 1 elif condition_sl: barriers['out'][i] = -1 else: barriers['out'][i] = max( [(price_final - price_initial)/ (top_barrier - price_initial), \\ (price_final - price_initial)/ \\ (price_initial - bottom_barrier)],\\ key=abs) returnget_labels()barriersfig,ax = plt.subplots()ax.set(title='Apple stock price', xlabel='date', ylabel='price')ax.plot(barriers.price[100: 200])start = barriers.index[120]end = barriers.vert_barrier[120]upper_barrier = barriers.top_barrier[120]lower_barrier = barriers.bottom_barrier[120]ax.plot([start, end], [upper_barrier, upper_barrier], 'r--');ax.plot([start, end], [lower_barrier, lower_barrier], 'r--');ax.plot([start, end], [(lower_barrier + upper_barrier)*0.5, \\ (lower_barrier + upper_barrier)*0.5], 'r--');ax.plot([start, start], [lower_barrier, upper_barrier], 'r-');ax.plot([end, end], [lower_barrier, upper_barrier], 'r-');#dynamic graphfig,ax = plt.subplots()ax.set(title='Apple stock price', xlabel='date', ylabel='price')ax.plot(barriers.price[100: 200])start = barriers.index[120]end = barriers.index[120+t_final]upper_barrier = barriers.top_barrier[120]lower_barrier = barriers.bottom_barrier[120]ax.plot(barriers.index[120:120+t_final+1], barriers.top_barrier[start:end], 'r--');ax.plot(barriers.index[120:120+t_final+1], barriers.bottom_barrier[start:end], 'r--');ax.plot([start, end], [(lower_barrier + upper_barrier)*0.5, \\ (lower_barrier + upper_barrier)*0.5], 'r--');ax.plot([start, start], [lower_barrier, upper_barrier], 'r-');ax.plot([end, end], [barriers.bottom_barrier[end], barriers.top_barrier[end]], 'r-');" }, { "code": null, "e": 22017, "s": 21942, "text": "Introduction to “Advances in Financial Machine Learning” by Lopez de Prado" } ]
Java Examples - Finding Word Occurrence
How to find every occurance of a word? Following example demonstrates how to find every occurance of a word with the help of Pattern.compile() method and m.group() method. import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String args[]) throws Exception { String candidate = "this is a test, A TEST."; String regex = "\\ba\\w*\\b"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(candidate); String val = null; System.out.println("INPUT: " + candidate); System.out.println("REGEX: " + regex + "\r\n"); while (m.find()) { val = m.group(); System.out.println("MATCH: " + val); } if (val == null) { System.out.println("NO MATCHES: "); } } } The above code sample will produce the following result. INPUT: this is a test, A TEST. REGEX: \ba\w*\b MATCH: a Print Add Notes Bookmark this page
[ { "code": null, "e": 2107, "s": 2068, "text": "How to find every occurance of a word?" }, { "code": null, "e": 2240, "s": 2107, "text": "Following example demonstrates how to find every occurance of a word with the help of Pattern.compile() method and m.group() method." }, { "code": null, "e": 2889, "s": 2240, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Main {\n public static void main(String args[]) throws Exception {\n String candidate = \"this is a test, A TEST.\";\n String regex = \"\\\\ba\\\\w*\\\\b\";\n Pattern p = Pattern.compile(regex);\n Matcher m = p.matcher(candidate);\n \n String val = null; \n System.out.println(\"INPUT: \" + candidate);\n System.out.println(\"REGEX: \" + regex + \"\\r\\n\");\n \n while (m.find()) {\n val = m.group();\n System.out.println(\"MATCH: \" + val);\n }\n if (val == null) {\n System.out.println(\"NO MATCHES: \");\n }\n }\n}" }, { "code": null, "e": 2946, "s": 2889, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3004, "s": 2946, "text": "INPUT: this is a test, A TEST.\nREGEX: \\ba\\w*\\b\n\nMATCH: a\n" }, { "code": null, "e": 3011, "s": 3004, "text": " Print" }, { "code": null, "e": 3022, "s": 3011, "text": " Add Notes" } ]
JSON.simple - Quick Guide
JSON.simple is a simple Java based toolkit for JSON. You can use JSON.simple to encode or decode JSON data. Specification Compliant − JSON.simple is fully compliant with JSON Specification - RFC4627. Specification Compliant − JSON.simple is fully compliant with JSON Specification - RFC4627. Lightweight − It have very few classes and provides the necessary functionalities like encode/decode and escaping json. Lightweight − It have very few classes and provides the necessary functionalities like encode/decode and escaping json. Reuses Collections − Most of the operations are done using Map/List interfaces increasing the reusablity. Reuses Collections − Most of the operations are done using Map/List interfaces increasing the reusablity. Streaming supported − Supports streaming of JSON output text. Streaming supported − Supports streaming of JSON output text. SAX like Content Handler − Provides a SAX-like interface to stream large amount of JSON data. SAX like Content Handler − Provides a SAX-like interface to stream large amount of JSON data. High performance − Heap based parser is used and provide high performance. High performance − Heap based parser is used and provide high performance. No dependency − No external library dependency. Can be independently included. No dependency − No external library dependency. Can be independently included. JDK1.2 compatible − Source code and the binary are JDK1.2 compatible JDK1.2 compatible − Source code and the binary are JDK1.2 compatible JSON.simple is a library for Java, so the very first requirement is to have JDK installed in your machine. First of all, open the console and execute a java command based on the operating system you are working on. Let's verify the output for all the operating systems − java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101) java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101) java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101) If you do not have Java installed on your system, then download the Java Software Development Kit (SDK) from the following link www.oracle.com. We are assuming Java 1.8.0_101 as the installed version for this tutorial. Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example. Append Java compiler location to the System Path. Verify Java installation using the command java -version as explained above. Download the latest version of JSON.simple jar file from json-simple @ MVNRepository. At the time of writing this tutorial, we have downloaded json-simple-1.1.1.jar, and copied it into C:\>JSON folder. Set the JSON_JAVA environment variable to point to the base directory location where JSON.simple jar is stored on your machine. Let's assuming we've stored json-simple-1.1.1.jar in the JSON folder. Windows Set the environment variable JSON_JAVA to C:\JSON Linux export JSON_JAVA = /usr/local/JSON Mac export JSON_JAVA = /Library/JSON Set the CLASSPATH environment variable to point to the JSON.simple jar location. Windows Set the environment variable CLASSPATH to %CLASSPATH%;%JSON_JAVA%\json-simple-1.1.1.jar;.; Linux export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-simple-1.1.1.jar:. Mac export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-simple-1.1.1.jar:. JSON.simple maps entities from the left side to the right side while decoding or parsing, and maps entities from the right to the left while encoding. On decoding, the default concrete class of java.util.List is org.json.simple.JSONArray and the default concrete class of java.util.Map is org.json.simple.JSONObject. The following characters are reserved characters and can not be used in JSON and must be properly escaped to be used in strings. Backspace to be replaced with \b Backspace to be replaced with \b Form feed to be replaced with \f Form feed to be replaced with \f Newline to be replaced with \n Newline to be replaced with \n Carriage return to be replaced with \r Carriage return to be replaced with \r Tab to be replaced with \t Tab to be replaced with \t Double quote to be replaced with \" Double quote to be replaced with \" Backslash to be replaced with \\ Backslash to be replaced with \\ JSONObject.escape() method can be used to escape such reserved keywords in a JSON String. Following is the example − import org.json.simple.JSONObject; public class JsonDemo { public static void main(String[] args) { JSONObject jsonObject = new JSONObject(); String text = "Text with special character /\"\'\b\f\t\r\n."; System.out.println(text); System.out.println("After escaping."); text = jsonObject.escape(text); System.out.println(text); } } Text with special character /"' . After escaping. Text with special character \/\"'\b\f\t\r\n. JSONValue provide a static method parse() to parse the given json string to return a JSONObject which can then be used to get the values parsed. See the example below. import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; public class JsonDemo { public static void main(String[] args) { String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]"; Object obj = JSONValue.parse(s); JSONArray array = (JSONArray)obj; System.out.println("The 2nd element of array"); System.out.println(array.get(1)); System.out.println(); JSONObject obj2 = (JSONObject)array.get(1); System.out.println("Field \"1\""); System.out.println(obj2.get("1")); s = "{}"; obj = JSONValue.parse(s); System.out.println(obj); s = "[5,]"; obj = JSONValue.parse(s); System.out.println(obj); s = "[5,,2]"; obj = JSONValue.parse(s); System.out.println(obj); } } The 2nd element of array {"1":{"2":{"3":{"4":[5,{"6":7}]}}}} Field "1" {"2":{"3":{"4":[5,{"6":7}]}}} {} [5] [5,2] JSONParser.parse() throws ParseException in case of invalid JSON. Following example shows how to handle ParseException. import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; class JsonDemo { public static void main(String[] args) { JSONParser parser = new JSONParser(); String text = "[[null, 123.45, \"a\tb c\"]}, true"; try{ Object obj = parser.parse(text); System.out.println(obj); }catch(ParseException pe) { System.out.println("position: " + pe.getPosition()); System.out.println(pe); } } } position: 24 Unexpected token RIGHT BRACE(}) at position 24. ContainerFactory can be used to create Custom container for parsed JSON objects/arrays. First we need to create a ContainerFactory object and then use it in parse Method of JSONParser to get the required object. See the example below − import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.json.simple.parser.ContainerFactory; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; class JsonDemo { public static void main(String[] args) { JSONParser parser = new JSONParser(); String text = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}"; ContainerFactory containerFactory = new ContainerFactory() { @Override public Map createObjectContainer() { return new LinkedHashMap<>(); } @Override public List creatArrayContainer() { return new LinkedList<>(); } }; try { Map map = (Map)parser.parse(text, containerFactory); map.forEach((k,v)->System.out.println("Key : " + k + " Value : " + v)); } catch(ParseException pe) { System.out.println("position: " + pe.getPosition()); System.out.println(pe); } } } Key : first Value : 123 Key : second Value : [4, 5, 6] Key : third Value : 789 ContentHandler interface is used to provide a SAX like interface to stream the large json. It provides stoppable capability as well. Following example illustrates the concept. import java.io.IOException; import java.util.List; import java.util.Stack; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; class JsonDemo { public static void main(String[] args) { JSONParser parser = new JSONParser(); String text = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}"; try { CustomContentHandler handler = new CustomContentHandler(); parser.parse(text, handler,true); } catch(ParseException pe) { } } } class CustomContentHandler implements ContentHandler { @Override public boolean endArray() throws ParseException, IOException { System.out.println("inside endArray"); return true; } @Override public void endJSON() throws ParseException, IOException { System.out.println("inside endJSON"); } @Override public boolean endObject() throws ParseException, IOException { System.out.println("inside endObject"); return true; } @Override public boolean endObjectEntry() throws ParseException, IOException { System.out.println("inside endObjectEntry"); return true; } public boolean primitive(Object value) throws ParseException, IOException { System.out.println("inside primitive: " + value); return true; } @Override public boolean startArray() throws ParseException, IOException { System.out.println("inside startArray"); return true; } @Override public void startJSON() throws ParseException, IOException { System.out.println("inside startJSON"); } @Override public boolean startObject() throws ParseException, IOException { System.out.println("inside startObject"); return true; } @Override public boolean startObjectEntry(String key) throws ParseException, IOException { System.out.println("inside startObjectEntry: " + key); return true; } } inside startJSON inside startObject inside startObjectEntry: first inside primitive: 123 inside endObjectEntry inside startObjectEntry: second inside startArray inside primitive: 4 inside primitive: 5 inside primitive: 6 inside endArray inside endObjectEntry inside startObjectEntry: third inside primitive: 789 inside endObjectEntry inside endObject inside endJSON Using JSON.simple, we can encode a JSON Object using following ways − Encode a JSON Object - to String − Simple encoding. Encode a JSON Object - to String − Simple encoding. Encode a JSON Object - Streaming − Output can be used for streaming. Encode a JSON Object - Streaming − Output can be used for streaming. Encode a JSON Object - Using Map − Encoding by preserving the order. Encode a JSON Object - Using Map − Encoding by preserving the order. Encode a JSON Object - Using Map and Streaming − Encoding by preserving the order and to stream. Encode a JSON Object - Using Map and Streaming − Encoding by preserving the order and to stream. Following example illustrates the above concepts. import java.io.IOException; import java.io.StringWriter; import java.util.LinkedHashMap; import java.util.Map; import org.json.simple.JSONObject; import org.json.simple.JSONValue; class JsonDemo { public static void main(String[] args) throws IOException { JSONObject obj = new JSONObject(); String jsonText; obj.put("name", "foo"); obj.put("num", new Integer(100)); obj.put("balance", new Double(1000.21)); obj.put("is_vip", new Boolean(true)); jsonText = obj.toString(); System.out.println("Encode a JSON Object - to String"); System.out.print(jsonText); StringWriter out = new StringWriter(); obj.writeJSONString(out); jsonText = out.toString(); System.out.println("\nEncode a JSON Object - Streaming"); System.out.print(jsonText); Map obj1 = new LinkedHashMap(); obj1.put("name", "foo"); obj1.put("num", new Integer(100)); obj1.put("balance", new Double(1000.21)); obj1.put("is_vip", new Boolean(true)); jsonText = JSONValue.toJSONString(obj1); System.out.println("\nEncode a JSON Object - Preserving Order"); System.out.print(jsonText); out = new StringWriter(); JSONValue.writeJSONString(obj1, out); jsonText = out.toString(); System.out.println("\nEncode a JSON Object - Preserving Order and Stream"); System.out.print(jsonText); } } Encode a JSON Object - to String {"balance":1000.21,"is_vip":true,"num":100,"name":"foo"} Encode a JSON Object - Streaming {"balance":1000.21,"is_vip":true,"num":100,"name":"foo"} Encode a JSON Object - Preserving Order {"name":"foo","num":100,"balance":1000.21,"is_vip":true} Encode a JSON Object - Preserving Order and Stream {"name":"foo","num":100,"balance":1000.21,"is_vip":true} Using JSON.simple, we can encode a JSON Array using following ways − Encode a JSON Array - to String − Simple encoding. Encode a JSON Array - to String − Simple encoding. Encode a JSON Array - Streaming − Output can be used for streaming. Encode a JSON Array - Streaming − Output can be used for streaming. Encode a JSON Array - Using List − Encoding by using the List. Encode a JSON Array - Using List − Encoding by using the List. Encode a JSON Array - Using List and Streaming − Encoding by using List and to stream. Encode a JSON Array - Using List and Streaming − Encoding by using List and to stream. Following example illustrates the above concepts. import java.io.IOException; import java.io.StringWriter; import java.util.LinkedList; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONValue; class JsonDemo { public static void main(String[] args) throws IOException { JSONArray list = new JSONArray(); String jsonText; list.add("foo"); list.add(new Integer(100)); list.add(new Double(1000.21)); list.add(new Boolean(true)); list.add(null); jsonText = list.toString(); System.out.println("Encode a JSON Array - to String"); System.out.print(jsonText); StringWriter out = new StringWriter(); list.writeJSONString(out); jsonText = out.toString(); System.out.println("\nEncode a JSON Array - Streaming"); System.out.print(jsonText); List list1 = new LinkedList(); list1.add("foo"); list1.add(new Integer(100)); list1.add(new Double(1000.21)); list1.add(new Boolean(true)); list1.add(null); jsonText = JSONValue.toJSONString(list1); System.out.println("\nEncode a JSON Array - Using List"); System.out.print(jsonText); out = new StringWriter(); JSONValue.writeJSONString(list1, out); jsonText = out.toString(); System.out.println("\nEncode a JSON Array - Using List and Stream"); System.out.print(jsonText); } } Encode a JSON Array - to String ["foo",100,1000.21,true,null] Encode a JSON Array - Streaming ["foo",100,1000.21,true,null] Encode a JSON Array - Using List ["foo",100,1000.21,true,null] Encode a JSON Array - Using List and Stream ["foo",100,1000.21,true,null] In JSON.simple, we can merge two JSON Objects easily using JSONObject.putAll() method. Following example illustrates the above concept. import java.io.IOException; import org.json.simple.JSONObject; class JsonDemo { public static void main(String[] args) throws IOException { JSONObject obj1 = new JSONObject(); obj1.put("name", "foo"); obj1.put("num", new Integer(100)); JSONObject obj2 = new JSONObject(); obj2.put("balance", new Double(1000.21)); obj2.put("is_vip", new Boolean(true)); obj1.putAll(obj2); System.out.println(obj1); } } {"balance":1000.21,"is_vip":true,"num":100,"name":"foo"} In JSON.simple, we can merge two JSON Arrays easily using JSONArray.addAll() method. Following example illustrates the above concept. import java.io.IOException; import org.json.simple.JSONArray; class JsonDemo { public static void main(String[] args) throws IOException { JSONArray list1 = new JSONArray(); list1.add("foo"); list1.add(new Integer(100)); JSONArray list2 = new JSONArray(); list2.add(new Double(1000.21)); list2.add(new Boolean(true)); list2.add(null); list1.addAll(list2); System.out.println(list1); } } ["foo",100,1000.21,true,null] Using JSONArray object, we can create a JSON which comprises of primitives, object and array. Following example illustrates the above concept. import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; class JsonDemo { public static void main(String[] args) throws IOException { JSONArray list1 = new JSONArray(); list1.add("foo"); list1.add(new Integer(100)); JSONArray list2 = new JSONArray(); list2.add(new Double(1000.21)); list2.add(new Boolean(true)); list2.add(null); JSONObject obj = new JSONObject(); obj.put("name", "foo"); obj.put("num", new Integer(100)); obj.put("balance", new Double(1000.21)); obj.put("is_vip", new Boolean(true)); obj.put("list1", list1); obj.put("list2", list2); System.out.println(obj); } } {"list1":["foo",100],"balance":1000.21,"is_vip":true,"num":100,"list2":[1000.21,true,null],"name":"foo"} Using JSONValue object, we can create a JSON which comprises of primitives, Map and List. Following example illustrates the above concept. import java.io.IOException; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.json.simple.JSONValue; class JsonDemo { public static void main(String[] args) throws IOException { Map m1 = new LinkedHashMap(); m1.put("k11","v11"); m1.put("k12","v12"); m1.put("k13", "v13"); List l1 = new LinkedList(); l1.add(m1); l1.add(new Integer(100)); String jsonString = JSONValue.toJSONString(l1); System.out.println(jsonString); } } [{"k11":"v11","k12":"v12","k13":"v13"},100] Using JSONValue object, we can create a JSON which comprises of primitives, Object, Map and List. Following example illustrates the above concept. import java.io.IOException; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.json.simple.JSONObject; import org.json.simple.JSONValue; class JsonDemo { public static void main(String[] args) throws IOException { JSONObject obj = new JSONObject(); Map m1 = new LinkedHashMap(); m1.put("k11","v11"); m1.put("k12","v12"); m1.put("k13", "v13"); List l1 = new LinkedList(); l1.add(new Integer(100)); obj.put("m1", m1); obj.put("l1", l1); String jsonString = JSONValue.toJSONString(obj); System.out.println(jsonString); } } {"m1":{"k11":"v11","k12":"v12","k13":"v13"},"l1":[100]} We can customize JSON output based on custom class. Only requirement is to implement JSONAware interface. Following example illustrates the above concept. import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONAware; import org.json.simple.JSONObject; class JsonDemo { public static void main(String[] args) throws IOException { JSONArray students = new JSONArray(); students.add(new Student(1,"Robert")); students.add(new Student(2,"Julia")); System.out.println(students); } } class Student implements JSONAware { int rollNo; String name; Student(int rollNo, String name){ this.rollNo = rollNo; this.name = name; } @Override public String toJSONString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("name"); sb.append(":"); sb.append("\"" + JSONObject.escape(name) + "\""); sb.append(","); sb.append("rollNo"); sb.append(":"); sb.append(rollNo); sb.append("}"); return sb.toString(); } } [{name:"Robert",rollNo:1},{name:"Julia",rollNo:2}] We can customize JSON streaming output based on custom class. Only requirement is to implement JSONStreamAware interface. Following example illustrates the above concept. import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.LinkedHashMap; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONStreamAware; import org.json.simple.JSONValue; class JsonDemo { public static void main(String[] args) throws IOException { JSONArray students = new JSONArray(); students.add(new Student(1,"Robert")); students.add(new Student(2,"Julia")); StringWriter out = new StringWriter(); students.writeJSONString(out); System.out.println(out.toString()); } } class Student implements JSONStreamAware { int rollNo; String name; Student(int rollNo, String name){ this.rollNo = rollNo; this.name = name; } @Override public void writeJSONString(Writer out) throws IOException { Map obj = new LinkedHashMap(); obj.put("name", name); obj.put("rollNo", new Integer(rollNo)); JSONValue.writeJSONString(obj, out); } } [{name:"Robert",rollNo:1},{name:"Julia",rollNo:2}] 20 Lectures 1 hours Laurence Svekis 16 Lectures 1 hours Laurence Svekis 10 Lectures 1 hours Laurence Svekis 23 Lectures 2.5 hours Laurence Svekis 9 Lectures 48 mins Nilay Mehta 18 Lectures 2.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2331, "s": 2223, "text": "JSON.simple is a simple Java based toolkit for JSON. You can use JSON.simple to encode or decode JSON data." }, { "code": null, "e": 2423, "s": 2331, "text": "Specification Compliant − JSON.simple is fully compliant with JSON Specification - RFC4627." }, { "code": null, "e": 2515, "s": 2423, "text": "Specification Compliant − JSON.simple is fully compliant with JSON Specification - RFC4627." }, { "code": null, "e": 2635, "s": 2515, "text": "Lightweight − It have very few classes and provides the necessary functionalities like encode/decode and escaping json." }, { "code": null, "e": 2755, "s": 2635, "text": "Lightweight − It have very few classes and provides the necessary functionalities like encode/decode and escaping json." }, { "code": null, "e": 2861, "s": 2755, "text": "Reuses Collections − Most of the operations are done using Map/List interfaces increasing the reusablity." }, { "code": null, "e": 2967, "s": 2861, "text": "Reuses Collections − Most of the operations are done using Map/List interfaces increasing the reusablity." }, { "code": null, "e": 3029, "s": 2967, "text": "Streaming supported − Supports streaming of JSON output text." }, { "code": null, "e": 3091, "s": 3029, "text": "Streaming supported − Supports streaming of JSON output text." }, { "code": null, "e": 3185, "s": 3091, "text": "SAX like Content Handler − Provides a SAX-like interface to stream large amount of JSON data." }, { "code": null, "e": 3279, "s": 3185, "text": "SAX like Content Handler − Provides a SAX-like interface to stream large amount of JSON data." }, { "code": null, "e": 3354, "s": 3279, "text": "High performance − Heap based parser is used and provide high performance." }, { "code": null, "e": 3429, "s": 3354, "text": "High performance − Heap based parser is used and provide high performance." }, { "code": null, "e": 3508, "s": 3429, "text": "No dependency − No external library dependency. Can be independently included." }, { "code": null, "e": 3587, "s": 3508, "text": "No dependency − No external library dependency. Can be independently included." }, { "code": null, "e": 3656, "s": 3587, "text": "JDK1.2 compatible − Source code and the binary are JDK1.2 compatible" }, { "code": null, "e": 3725, "s": 3656, "text": "JDK1.2 compatible − Source code and the binary are JDK1.2 compatible" }, { "code": null, "e": 3832, "s": 3725, "text": "JSON.simple is a library for Java, so the very first requirement is to have JDK installed in your machine." }, { "code": null, "e": 3940, "s": 3832, "text": "First of all, open the console and execute a java command based on the operating system you are working on." }, { "code": null, "e": 3996, "s": 3940, "text": "Let's verify the output for all the operating systems −" }, { "code": null, "e": 4021, "s": 3996, "text": "java version \"1.8.0_101\"" }, { "code": null, "e": 4071, "s": 4021, "text": "Java(TM) SE Runtime Environment (build 1.8.0_101)" }, { "code": null, "e": 4096, "s": 4071, "text": "java version \"1.8.0_101\"" }, { "code": null, "e": 4146, "s": 4096, "text": "Java(TM) SE Runtime Environment (build 1.8.0_101)" }, { "code": null, "e": 4171, "s": 4146, "text": "java version \"1.8.0_101\"" }, { "code": null, "e": 4221, "s": 4171, "text": "Java(TM) SE Runtime Environment (build 1.8.0_101)" }, { "code": null, "e": 4440, "s": 4221, "text": "If you do not have Java installed on your system, then download the Java Software Development Kit (SDK) from the following link www.oracle.com. We are assuming Java 1.8.0_101 as the installed version for this tutorial." }, { "code": null, "e": 4573, "s": 4440, "text": "Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example." }, { "code": null, "e": 4623, "s": 4573, "text": "Append Java compiler location to the System Path." }, { "code": null, "e": 4700, "s": 4623, "text": "Verify Java installation using the command java -version as explained above." }, { "code": null, "e": 4902, "s": 4700, "text": "Download the latest version of JSON.simple jar file from json-simple @ MVNRepository. At the time of writing this tutorial, we have downloaded json-simple-1.1.1.jar, and copied it into C:\\>JSON folder." }, { "code": null, "e": 5100, "s": 4902, "text": "Set the JSON_JAVA environment variable to point to the base directory location where JSON.simple jar is stored on your machine. Let's assuming we've stored json-simple-1.1.1.jar in the JSON folder." }, { "code": null, "e": 5108, "s": 5100, "text": "Windows" }, { "code": null, "e": 5158, "s": 5108, "text": "Set the environment variable JSON_JAVA to C:\\JSON" }, { "code": null, "e": 5164, "s": 5158, "text": "Linux" }, { "code": null, "e": 5199, "s": 5164, "text": "export JSON_JAVA = /usr/local/JSON" }, { "code": null, "e": 5203, "s": 5199, "text": "Mac" }, { "code": null, "e": 5236, "s": 5203, "text": "export JSON_JAVA = /Library/JSON" }, { "code": null, "e": 5317, "s": 5236, "text": "Set the CLASSPATH environment variable to point to the JSON.simple jar location." }, { "code": null, "e": 5325, "s": 5317, "text": "Windows" }, { "code": null, "e": 5416, "s": 5325, "text": "Set the environment variable CLASSPATH to %CLASSPATH%;%JSON_JAVA%\\json-simple-1.1.1.jar;.;" }, { "code": null, "e": 5422, "s": 5416, "text": "Linux" }, { "code": null, "e": 5487, "s": 5422, "text": "export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-simple-1.1.1.jar:." }, { "code": null, "e": 5491, "s": 5487, "text": "Mac" }, { "code": null, "e": 5556, "s": 5491, "text": "export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-simple-1.1.1.jar:." }, { "code": null, "e": 5707, "s": 5556, "text": "JSON.simple maps entities from the left side to the right side while decoding or parsing, and maps entities from the right to the left while encoding." }, { "code": null, "e": 5873, "s": 5707, "text": "On decoding, the default concrete class of java.util.List is org.json.simple.JSONArray and the default concrete class of java.util.Map is org.json.simple.JSONObject." }, { "code": null, "e": 6002, "s": 5873, "text": "The following characters are reserved characters and can not be used in JSON and must be properly escaped to be used in strings." }, { "code": null, "e": 6035, "s": 6002, "text": "Backspace to be replaced with \\b" }, { "code": null, "e": 6068, "s": 6035, "text": "Backspace to be replaced with \\b" }, { "code": null, "e": 6101, "s": 6068, "text": "Form feed to be replaced with \\f" }, { "code": null, "e": 6134, "s": 6101, "text": "Form feed to be replaced with \\f" }, { "code": null, "e": 6165, "s": 6134, "text": "Newline to be replaced with \\n" }, { "code": null, "e": 6196, "s": 6165, "text": "Newline to be replaced with \\n" }, { "code": null, "e": 6235, "s": 6196, "text": "Carriage return to be replaced with \\r" }, { "code": null, "e": 6274, "s": 6235, "text": "Carriage return to be replaced with \\r" }, { "code": null, "e": 6301, "s": 6274, "text": "Tab to be replaced with \\t" }, { "code": null, "e": 6328, "s": 6301, "text": "Tab to be replaced with \\t" }, { "code": null, "e": 6364, "s": 6328, "text": "Double quote to be replaced with \\\"" }, { "code": null, "e": 6400, "s": 6364, "text": "Double quote to be replaced with \\\"" }, { "code": null, "e": 6433, "s": 6400, "text": "Backslash to be replaced with \\\\" }, { "code": null, "e": 6466, "s": 6433, "text": "Backslash to be replaced with \\\\" }, { "code": null, "e": 6583, "s": 6466, "text": "JSONObject.escape() method can be used to escape such reserved keywords in a JSON String. Following is the example −" }, { "code": null, "e": 6957, "s": 6583, "text": "import org.json.simple.JSONObject;\n\npublic class JsonDemo {\n public static void main(String[] args) {\n JSONObject jsonObject = new JSONObject();\n String text = \"Text with special character /\\\"\\'\\b\\f\\t\\r\\n.\";\n System.out.println(text);\n System.out.println(\"After escaping.\");\n text = jsonObject.escape(text);\n System.out.println(text);\n }\n}" }, { "code": null, "e": 7053, "s": 6957, "text": "Text with special character /\"'\n.\nAfter escaping.\nText with special character \\/\\\"'\\b\\f\\t\\r\\n.\n" }, { "code": null, "e": 7221, "s": 7053, "text": "JSONValue provide a static method parse() to parse the given json string to return a JSONObject which can then be used to get the values parsed. See the example below." }, { "code": null, "e": 8055, "s": 7221, "text": "import org.json.simple.JSONArray;\nimport org.json.simple.JSONObject;\nimport org.json.simple.JSONValue;\n\npublic class JsonDemo {\n public static void main(String[] args) {\n String s = \"[0,{\\\"1\\\":{\\\"2\\\":{\\\"3\\\":{\\\"4\\\":[5,{\\\"6\\\":7}]}}}}]\";\n Object obj = JSONValue.parse(s);\n JSONArray array = (JSONArray)obj;\n\n System.out.println(\"The 2nd element of array\");\n System.out.println(array.get(1));\n System.out.println();\n\n JSONObject obj2 = (JSONObject)array.get(1);\n System.out.println(\"Field \\\"1\\\"\");\n System.out.println(obj2.get(\"1\")); \n\n s = \"{}\";\n obj = JSONValue.parse(s);\n System.out.println(obj);\n\n s = \"[5,]\";\n obj = JSONValue.parse(s);\n System.out.println(obj);\n\n s = \"[5,,2]\";\n obj = JSONValue.parse(s);\n System.out.println(obj);\n }\n}" }, { "code": null, "e": 8171, "s": 8055, "text": "The 2nd element of array\n{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}\n\nField \"1\"\n{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}\n{}\n[5]\n[5,2]\n" }, { "code": null, "e": 8291, "s": 8171, "text": "JSONParser.parse() throws ParseException in case of invalid JSON. Following example shows how to handle ParseException." }, { "code": null, "e": 8784, "s": 8291, "text": "import org.json.simple.parser.JSONParser;\nimport org.json.simple.parser.ParseException;\n\nclass JsonDemo {\n public static void main(String[] args) {\n JSONParser parser = new JSONParser();\n String text = \"[[null, 123.45, \\\"a\\tb c\\\"]}, true\";\n\n try{\n Object obj = parser.parse(text); \n System.out.println(obj);\n }catch(ParseException pe) {\n System.out.println(\"position: \" + pe.getPosition());\n System.out.println(pe);\n }\n }\n}" }, { "code": null, "e": 8846, "s": 8784, "text": "position: 24\nUnexpected token RIGHT BRACE(}) at position 24.\n" }, { "code": null, "e": 9083, "s": 8846, "text": "ContainerFactory can be used to create Custom container for parsed JSON objects/arrays. First we need to create a ContainerFactory object and then use it in parse Method of JSONParser to get the required object. See the example below − " }, { "code": null, "e": 10127, "s": 9083, "text": "import java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.json.simple.parser.ContainerFactory;\nimport org.json.simple.parser.JSONParser;\nimport org.json.simple.parser.ParseException;\n\nclass JsonDemo {\n public static void main(String[] args) {\n JSONParser parser = new JSONParser();\n String text = \"{\\\"first\\\": 123, \\\"second\\\": [4, 5, 6], \\\"third\\\": 789}\";\n ContainerFactory containerFactory = new ContainerFactory() {\n @Override\n public Map createObjectContainer() {\n return new LinkedHashMap<>();\n }\n @Override\n public List creatArrayContainer() {\n return new LinkedList<>();\n }\n };\n try {\n Map map = (Map)parser.parse(text, containerFactory); \n map.forEach((k,v)->System.out.println(\"Key : \" + k + \" Value : \" + v));\n } catch(ParseException pe) {\n System.out.println(\"position: \" + pe.getPosition());\n System.out.println(pe);\n }\n }\n}" }, { "code": null, "e": 10207, "s": 10127, "text": "Key : first Value : 123\nKey : second Value : [4, 5, 6]\nKey : third Value : 789\n" }, { "code": null, "e": 10383, "s": 10207, "text": "ContentHandler interface is used to provide a SAX like interface to stream the large json. It provides stoppable capability as well. Following example illustrates the concept." }, { "code": null, "e": 12465, "s": 10383, "text": "import java.io.IOException;\nimport java.util.List;\nimport java.util.Stack;\n\nimport org.json.simple.JSONArray;\nimport org.json.simple.JSONObject;\nimport org.json.simple.parser.ContentHandler;\nimport org.json.simple.parser.JSONParser;\nimport org.json.simple.parser.ParseException;\n\nclass JsonDemo {\n public static void main(String[] args) {\n JSONParser parser = new JSONParser();\n String text = \"{\\\"first\\\": 123, \\\"second\\\": [4, 5, 6], \\\"third\\\": 789}\";\n try {\n CustomContentHandler handler = new CustomContentHandler();\n parser.parse(text, handler,true); \n } catch(ParseException pe) {\n }\n }\n}\nclass CustomContentHandler implements ContentHandler {\n @Override\n public boolean endArray() throws ParseException, IOException { \n System.out.println(\"inside endArray\");\n return true;\n }\n @Override\n public void endJSON() throws ParseException, IOException {\n System.out.println(\"inside endJSON\");\n }\n @Override\n public boolean endObject() throws ParseException, IOException { \n System.out.println(\"inside endObject\");\n return true;\n }\n @Override\n public boolean endObjectEntry() throws ParseException, IOException {\n System.out.println(\"inside endObjectEntry\");\n return true;\n }\n public boolean primitive(Object value) throws ParseException, IOException {\n System.out.println(\"inside primitive: \" + value);\n return true;\n }\n @Override\n public boolean startArray() throws ParseException, IOException {\n System.out.println(\"inside startArray\");\n return true;\n }\n @Override\n public void startJSON() throws ParseException, IOException {\n System.out.println(\"inside startJSON\");\n }\n @Override\n public boolean startObject() throws ParseException, IOException {\n System.out.println(\"inside startObject\"); \n return true;\n }\n @Override\n public boolean startObjectEntry(String key) throws ParseException, IOException {\n System.out.println(\"inside startObjectEntry: \" + key); \n return true;\n } \n}" }, { "code": null, "e": 12832, "s": 12465, "text": "inside startJSON\ninside startObject\ninside startObjectEntry: first\ninside primitive: 123\ninside endObjectEntry\ninside startObjectEntry: second\ninside startArray\ninside primitive: 4\ninside primitive: 5\ninside primitive: 6\ninside endArray\ninside endObjectEntry\ninside startObjectEntry: third\ninside primitive: 789\ninside endObjectEntry\ninside endObject\ninside endJSON\n" }, { "code": null, "e": 12902, "s": 12832, "text": "Using JSON.simple, we can encode a JSON Object using following ways −" }, { "code": null, "e": 12954, "s": 12902, "text": "Encode a JSON Object - to String − Simple encoding." }, { "code": null, "e": 13006, "s": 12954, "text": "Encode a JSON Object - to String − Simple encoding." }, { "code": null, "e": 13075, "s": 13006, "text": "Encode a JSON Object - Streaming − Output can be used for streaming." }, { "code": null, "e": 13144, "s": 13075, "text": "Encode a JSON Object - Streaming − Output can be used for streaming." }, { "code": null, "e": 13213, "s": 13144, "text": "Encode a JSON Object - Using Map − Encoding by preserving the order." }, { "code": null, "e": 13282, "s": 13213, "text": "Encode a JSON Object - Using Map − Encoding by preserving the order." }, { "code": null, "e": 13379, "s": 13282, "text": "Encode a JSON Object - Using Map and Streaming − Encoding by preserving the order and to stream." }, { "code": null, "e": 13476, "s": 13379, "text": "Encode a JSON Object - Using Map and Streaming − Encoding by preserving the order and to stream." }, { "code": null, "e": 13526, "s": 13476, "text": "Following example illustrates the above concepts." }, { "code": null, "e": 14960, "s": 13526, "text": "import java.io.IOException;\nimport java.io.StringWriter;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\nimport org.json.simple.JSONObject;\nimport org.json.simple.JSONValue;\n\nclass JsonDemo {\n public static void main(String[] args) throws IOException {\n JSONObject obj = new JSONObject();\n String jsonText;\n\n obj.put(\"name\", \"foo\");\n obj.put(\"num\", new Integer(100));\n obj.put(\"balance\", new Double(1000.21));\n obj.put(\"is_vip\", new Boolean(true));\n jsonText = obj.toString();\n\n System.out.println(\"Encode a JSON Object - to String\");\n System.out.print(jsonText);\n\n StringWriter out = new StringWriter();\n obj.writeJSONString(out); \n jsonText = out.toString();\n\n System.out.println(\"\\nEncode a JSON Object - Streaming\"); \n System.out.print(jsonText);\n\n Map obj1 = new LinkedHashMap();\n obj1.put(\"name\", \"foo\");\n obj1.put(\"num\", new Integer(100));\n obj1.put(\"balance\", new Double(1000.21));\n obj1.put(\"is_vip\", new Boolean(true));\n\n jsonText = JSONValue.toJSONString(obj1); \n System.out.println(\"\\nEncode a JSON Object - Preserving Order\");\n System.out.print(jsonText);\n\n out = new StringWriter();\n JSONValue.writeJSONString(obj1, out); \n jsonText = out.toString();\n System.out.println(\"\\nEncode a JSON Object - Preserving Order and Stream\");\n System.out.print(jsonText);\n }\n}" }, { "code": null, "e": 15346, "s": 14960, "text": "Encode a JSON Object - to String\n{\"balance\":1000.21,\"is_vip\":true,\"num\":100,\"name\":\"foo\"}\nEncode a JSON Object - Streaming\n{\"balance\":1000.21,\"is_vip\":true,\"num\":100,\"name\":\"foo\"}\nEncode a JSON Object - Preserving Order\n{\"name\":\"foo\",\"num\":100,\"balance\":1000.21,\"is_vip\":true}\nEncode a JSON Object - Preserving Order and Stream\n{\"name\":\"foo\",\"num\":100,\"balance\":1000.21,\"is_vip\":true}\n" }, { "code": null, "e": 15415, "s": 15346, "text": "Using JSON.simple, we can encode a JSON Array using following ways −" }, { "code": null, "e": 15466, "s": 15415, "text": "Encode a JSON Array - to String − Simple encoding." }, { "code": null, "e": 15517, "s": 15466, "text": "Encode a JSON Array - to String − Simple encoding." }, { "code": null, "e": 15585, "s": 15517, "text": "Encode a JSON Array - Streaming − Output can be used for streaming." }, { "code": null, "e": 15653, "s": 15585, "text": "Encode a JSON Array - Streaming − Output can be used for streaming." }, { "code": null, "e": 15716, "s": 15653, "text": "Encode a JSON Array - Using List − Encoding by using the List." }, { "code": null, "e": 15779, "s": 15716, "text": "Encode a JSON Array - Using List − Encoding by using the List." }, { "code": null, "e": 15866, "s": 15779, "text": "Encode a JSON Array - Using List and Streaming − Encoding by using List and to stream." }, { "code": null, "e": 15953, "s": 15866, "text": "Encode a JSON Array - Using List and Streaming − Encoding by using List and to stream." }, { "code": null, "e": 16003, "s": 15953, "text": "Following example illustrates the above concepts." }, { "code": null, "e": 17401, "s": 16003, "text": "import java.io.IOException;\nimport java.io.StringWriter;\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport org.json.simple.JSONArray;\nimport org.json.simple.JSONValue;\n\nclass JsonDemo {\n public static void main(String[] args) throws IOException {\n JSONArray list = new JSONArray();\n String jsonText;\n\n list.add(\"foo\");\n list.add(new Integer(100));\n list.add(new Double(1000.21));\n list.add(new Boolean(true));\n list.add(null);\n jsonText = list.toString();\n\n System.out.println(\"Encode a JSON Array - to String\");\n System.out.print(jsonText);\n\n StringWriter out = new StringWriter();\n list.writeJSONString(out); \n jsonText = out.toString();\n\n System.out.println(\"\\nEncode a JSON Array - Streaming\"); \n System.out.print(jsonText);\n\n List list1 = new LinkedList();\n list1.add(\"foo\");\n list1.add(new Integer(100));\n list1.add(new Double(1000.21));\n list1.add(new Boolean(true));\n list1.add(null);\n\n jsonText = JSONValue.toJSONString(list1); \n System.out.println(\"\\nEncode a JSON Array - Using List\");\n System.out.print(jsonText);\n\n out = new StringWriter();\n JSONValue.writeJSONString(list1, out); \n jsonText = out.toString();\n System.out.println(\"\\nEncode a JSON Array - Using List and Stream\");\n System.out.print(jsonText);\n }\n}" }, { "code": null, "e": 17663, "s": 17401, "text": "Encode a JSON Array - to String\n[\"foo\",100,1000.21,true,null]\nEncode a JSON Array - Streaming\n[\"foo\",100,1000.21,true,null]\nEncode a JSON Array - Using List\n[\"foo\",100,1000.21,true,null]\nEncode a JSON Array - Using List and Stream\n[\"foo\",100,1000.21,true,null]\n" }, { "code": null, "e": 17750, "s": 17663, "text": "In JSON.simple, we can merge two JSON Objects easily using JSONObject.putAll() method." }, { "code": null, "e": 17799, "s": 17750, "text": "Following example illustrates the above concept." }, { "code": null, "e": 18286, "s": 17799, "text": "import java.io.IOException;\nimport org.json.simple.JSONObject;\n\nclass JsonDemo {\n public static void main(String[] args) throws IOException {\n JSONObject obj1 = new JSONObject(); \n obj1.put(\"name\", \"foo\");\n obj1.put(\"num\", new Integer(100)); \n\n JSONObject obj2 = new JSONObject(); \n obj2.put(\"balance\", new Double(1000.21));\n obj2.put(\"is_vip\", new Boolean(true)); \n obj1.putAll(obj2); \n System.out.println(obj1);\n }\n}" }, { "code": null, "e": 18344, "s": 18286, "text": "{\"balance\":1000.21,\"is_vip\":true,\"num\":100,\"name\":\"foo\"}\n" }, { "code": null, "e": 18429, "s": 18344, "text": "In JSON.simple, we can merge two JSON Arrays easily using JSONArray.addAll() method." }, { "code": null, "e": 18478, "s": 18429, "text": "Following example illustrates the above concept." }, { "code": null, "e": 18949, "s": 18478, "text": "import java.io.IOException;\nimport org.json.simple.JSONArray;\n\nclass JsonDemo {\n public static void main(String[] args) throws IOException {\n JSONArray list1 = new JSONArray();\n list1.add(\"foo\");\n list1.add(new Integer(100));\n\n JSONArray list2 = new JSONArray(); \n list2.add(new Double(1000.21));\n list2.add(new Boolean(true));\n list2.add(null);\n\n list1.addAll(list2); \n System.out.println(list1); \n }\n}" }, { "code": null, "e": 18980, "s": 18949, "text": "[\"foo\",100,1000.21,true,null]\n" }, { "code": null, "e": 19074, "s": 18980, "text": "Using JSONArray object, we can create a JSON which comprises of primitives, object and array." }, { "code": null, "e": 19123, "s": 19074, "text": "Following example illustrates the above concept." }, { "code": null, "e": 19865, "s": 19123, "text": "import java.io.IOException;\nimport org.json.simple.JSONArray;\nimport org.json.simple.JSONObject;\n\nclass JsonDemo {\n public static void main(String[] args) throws IOException {\n JSONArray list1 = new JSONArray();\n list1.add(\"foo\");\n list1.add(new Integer(100));\n\n JSONArray list2 = new JSONArray(); \n list2.add(new Double(1000.21));\n list2.add(new Boolean(true));\n list2.add(null);\n\n JSONObject obj = new JSONObject();\n\n obj.put(\"name\", \"foo\");\n obj.put(\"num\", new Integer(100));\n obj.put(\"balance\", new Double(1000.21));\n obj.put(\"is_vip\", new Boolean(true));\n \n obj.put(\"list1\", list1); \n obj.put(\"list2\", list2);\n System.out.println(obj); \n }\n}" }, { "code": null, "e": 19971, "s": 19865, "text": "{\"list1\":[\"foo\",100],\"balance\":1000.21,\"is_vip\":true,\"num\":100,\"list2\":[1000.21,true,null],\"name\":\"foo\"}\n" }, { "code": null, "e": 20061, "s": 19971, "text": "Using JSONValue object, we can create a JSON which comprises of primitives, Map and List." }, { "code": null, "e": 20110, "s": 20061, "text": "Following example illustrates the above concept." }, { "code": null, "e": 20666, "s": 20110, "text": "import java.io.IOException;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.json.simple.JSONValue;\n\nclass JsonDemo {\n public static void main(String[] args) throws IOException {\n Map m1 = new LinkedHashMap(); \n m1.put(\"k11\",\"v11\"); \n m1.put(\"k12\",\"v12\"); \n m1.put(\"k13\", \"v13\");\n\n List l1 = new LinkedList();\n l1.add(m1);\n l1.add(new Integer(100));\n\n String jsonString = JSONValue.toJSONString(l1);\n System.out.println(jsonString);\n }\n}" }, { "code": null, "e": 20711, "s": 20666, "text": "[{\"k11\":\"v11\",\"k12\":\"v12\",\"k13\":\"v13\"},100]\n" }, { "code": null, "e": 20809, "s": 20711, "text": "Using JSONValue object, we can create a JSON which comprises of primitives, Object, Map and List." }, { "code": null, "e": 20858, "s": 20809, "text": "Following example illustrates the above concept." }, { "code": null, "e": 21528, "s": 20858, "text": "import java.io.IOException;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.json.simple.JSONObject;\nimport org.json.simple.JSONValue;\n\nclass JsonDemo {\n public static void main(String[] args) throws IOException {\n JSONObject obj = new JSONObject();\n\n Map m1 = new LinkedHashMap(); \n m1.put(\"k11\",\"v11\");\n m1.put(\"k12\",\"v12\");\n m1.put(\"k13\", \"v13\");\n\n List l1 = new LinkedList(); \n l1.add(new Integer(100));\n\n obj.put(\"m1\", m1);\n obj.put(\"l1\", l1);\n String jsonString = JSONValue.toJSONString(obj);\n System.out.println(jsonString);\n }\n}" }, { "code": null, "e": 21585, "s": 21528, "text": "{\"m1\":{\"k11\":\"v11\",\"k12\":\"v12\",\"k13\":\"v13\"},\"l1\":[100]}\n" }, { "code": null, "e": 21691, "s": 21585, "text": "We can customize JSON output based on custom class. Only requirement is to implement JSONAware interface." }, { "code": null, "e": 21740, "s": 21691, "text": "Following example illustrates the above concept." }, { "code": null, "e": 22675, "s": 21740, "text": "import java.io.IOException;\n\nimport org.json.simple.JSONArray;\nimport org.json.simple.JSONAware;\nimport org.json.simple.JSONObject;\n\nclass JsonDemo {\n public static void main(String[] args) throws IOException {\n JSONArray students = new JSONArray(); \n students.add(new Student(1,\"Robert\")); \n students.add(new Student(2,\"Julia\")); \n\n System.out.println(students); \n }\n}\nclass Student implements JSONAware {\n int rollNo;\n String name;\n Student(int rollNo, String name){\n this.rollNo = rollNo;\n this.name = name;\n }\n @Override\n public String toJSONString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"{\");\n sb.append(\"name\");\n sb.append(\":\");\n sb.append(\"\\\"\" + JSONObject.escape(name) + \"\\\"\");\n sb.append(\",\");\n sb.append(\"rollNo\");\n sb.append(\":\");\n sb.append(rollNo);\n sb.append(\"}\");\n return sb.toString();\n } \n}" }, { "code": null, "e": 22727, "s": 22675, "text": "[{name:\"Robert\",rollNo:1},{name:\"Julia\",rollNo:2}]\n" }, { "code": null, "e": 22849, "s": 22727, "text": "We can customize JSON streaming output based on custom class. Only requirement is to implement JSONStreamAware interface." }, { "code": null, "e": 22898, "s": 22849, "text": "Following example illustrates the above concept." }, { "code": null, "e": 23915, "s": 22898, "text": "import java.io.IOException;\nimport java.io.StringWriter;\nimport java.io.Writer;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\nimport org.json.simple.JSONArray;\nimport org.json.simple.JSONStreamAware;\nimport org.json.simple.JSONValue;\n\nclass JsonDemo {\n public static void main(String[] args) throws IOException {\n JSONArray students = new JSONArray(); \n students.add(new Student(1,\"Robert\")); \n students.add(new Student(2,\"Julia\")); \n StringWriter out = new StringWriter();\n students.writeJSONString(out); \n System.out.println(out.toString()); \n }\n}\nclass Student implements JSONStreamAware {\n int rollNo;\n String name;\n\n Student(int rollNo, String name){\n this.rollNo = rollNo;\n this.name = name;\n }\n @Override\n public void writeJSONString(Writer out) throws IOException {\n Map obj = new LinkedHashMap();\n obj.put(\"name\", name);\n obj.put(\"rollNo\", new Integer(rollNo));\n JSONValue.writeJSONString(obj, out); \n } \n}" }, { "code": null, "e": 23967, "s": 23915, "text": "[{name:\"Robert\",rollNo:1},{name:\"Julia\",rollNo:2}]\n" }, { "code": null, "e": 24000, "s": 23967, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 24017, "s": 24000, "text": " Laurence Svekis" }, { "code": null, "e": 24050, "s": 24017, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 24067, "s": 24050, "text": " Laurence Svekis" }, { "code": null, "e": 24100, "s": 24067, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 24117, "s": 24100, "text": " Laurence Svekis" }, { "code": null, "e": 24152, "s": 24117, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 24169, "s": 24152, "text": " Laurence Svekis" }, { "code": null, "e": 24200, "s": 24169, "text": "\n 9 Lectures \n 48 mins\n" }, { "code": null, "e": 24213, "s": 24200, "text": " Nilay Mehta" }, { "code": null, "e": 24248, "s": 24213, "text": "\n 18 Lectures \n 2.5 hours \n" }, { "code": null, "e": 24271, "s": 24248, "text": " Stone River ELearning" }, { "code": null, "e": 24278, "s": 24271, "text": " Print" }, { "code": null, "e": 24289, "s": 24278, "text": " Add Notes" } ]
ReactJS | forms - GeeksforGeeks
22 Jan, 2021 Forms are really important in any website for login, signup, or whatever. It is easy to make a form but forms in React work a little differently. If you make a simple form in React it works, but it’s good to add some JavaScript code to our form so that it can handle the form submission and retrieve data that the user entered. To do this we use controlled components.Controlled Components: In simple HTML elements like input tag, the value of the input field is changed whenever the user type. But, In React, whatever the value user types we save it in state and pass the same value to the input tag as its value, so here its value is not changed by DOM, it is controlled by react state. This may sound complicated But let’s understand with an example. First, create react app, and from your project directory update your index.js file from src folder. src index.js: javascript import React from 'react';import ReactDOM from 'react-dom'; class App extends React.Component { onInputChange(event) { console.log(event.target.value); } render() { return ( <div> <form> <label>Enter text</label> <input type="text" onChange={this.onInputChange}/> </form> </div> ); }} ReactDOM.render(<App />, document.querySelector('#root')); In the above example, the input element is uncontrolled whatever the value user type is in the DOM. We are logging that value on the console by getting it from the DOM and the method onInputChange will be called any time user type in anything so the value will be printed on the console every time (Ctrl + Shift + F11) Google chrome user to open the console.React is used to handle the value of user enters. Edit src/index.js with given code: Src index.js: javascript import React from 'react';import ReactDOM from 'react-dom'; class App extends React.Component { state = { inputValue: '' }; render() { return ( <div> <form> <label> Enter text </label> <input type="text" value={this.state.inputValue} onChange={(e) => this.setState( { inputValue: e.target.value })}/> </form> <br/> <div> Entered Value: {this.state.inputValue} </div> </div> ); }} ReactDOM.render(<App />, document.querySelector('#root')); What will happening in the above react example, when we have made inputValue state with value null, and the value of that state is provided to the input field which means whatever the value of the inputValue is we will see it in the input box. And we are updating the value of inputValue each time user changing the value in the input by calling setState() function and dom is re-rendering because we are changing the value of inputValue using setState(). Here, we can easily get the value whatever user type in the input field and pass it to wherever we want from React state. The same happens with other elements like the text area and select. Here is another example that prevents the browser from automatically submitting the form. Edit src index.js: javascript import React from 'react';import ReactDOM from 'react-dom'; class App extends React.Component { state = { inputValue: '' }; onFormSubmit = (event) => { event.preventDefault(); this.setState({ inputValue: 'Hello World!'}); } render() { return ( <div> <form onSubmit={this.onFormSubmit}> <label> Enter text </label> <input type="text" value={this.state.inputValue} onChange={(e) => this.setState( { inputValue: e.target.value })}/> </form> <br/> <div> Entered Value: {this.state.inputValue} </div> </div> ); }} ReactDOM.render(<App />, document.querySelector('#root')); Output: Here we just add onSubmit event handler which calls the function onFormSumbit and performs the action of replacing the value of inputValue to ‘Hello World!’, and the preventDefault() function is used to prevent the browser from submitting the form and reloading the page. shubhamyadav4 react-js Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? File uploading in React.js How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 26775, "s": 26747, "text": "\n22 Jan, 2021" }, { "code": null, "e": 27529, "s": 26775, "text": "Forms are really important in any website for login, signup, or whatever. It is easy to make a form but forms in React work a little differently. If you make a simple form in React it works, but it’s good to add some JavaScript code to our form so that it can handle the form submission and retrieve data that the user entered. To do this we use controlled components.Controlled Components: In simple HTML elements like input tag, the value of the input field is changed whenever the user type. But, In React, whatever the value user types we save it in state and pass the same value to the input tag as its value, so here its value is not changed by DOM, it is controlled by react state. This may sound complicated But let’s understand with an example." }, { "code": null, "e": 27629, "s": 27529, "text": "First, create react app, and from your project directory update your index.js file from src folder." }, { "code": null, "e": 27644, "s": 27629, "text": "src index.js: " }, { "code": null, "e": 27655, "s": 27644, "text": "javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom'; class App extends React.Component { onInputChange(event) { console.log(event.target.value); } render() { return ( <div> <form> <label>Enter text</label> <input type=\"text\" onChange={this.onInputChange}/> </form> </div> ); }} ReactDOM.render(<App />, document.querySelector('#root'));", "e": 28166, "s": 27655, "text": null }, { "code": null, "e": 28576, "s": 28166, "text": "In the above example, the input element is uncontrolled whatever the value user type is in the DOM. We are logging that value on the console by getting it from the DOM and the method onInputChange will be called any time user type in anything so the value will be printed on the console every time (Ctrl + Shift + F11) Google chrome user to open the console.React is used to handle the value of user enters. " }, { "code": null, "e": 28611, "s": 28576, "text": "Edit src/index.js with given code:" }, { "code": null, "e": 28625, "s": 28611, "text": "Src index.js:" }, { "code": null, "e": 28636, "s": 28625, "text": "javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom'; class App extends React.Component { state = { inputValue: '' }; render() { return ( <div> <form> <label> Enter text </label> <input type=\"text\" value={this.state.inputValue} onChange={(e) => this.setState( { inputValue: e.target.value })}/> </form> <br/> <div> Entered Value: {this.state.inputValue} </div> </div> ); }} ReactDOM.render(<App />, document.querySelector('#root'));", "e": 29290, "s": 28636, "text": null }, { "code": null, "e": 30026, "s": 29290, "text": "What will happening in the above react example, when we have made inputValue state with value null, and the value of that state is provided to the input field which means whatever the value of the inputValue is we will see it in the input box. And we are updating the value of inputValue each time user changing the value in the input by calling setState() function and dom is re-rendering because we are changing the value of inputValue using setState(). Here, we can easily get the value whatever user type in the input field and pass it to wherever we want from React state. The same happens with other elements like the text area and select. Here is another example that prevents the browser from automatically submitting the form." }, { "code": null, "e": 30046, "s": 30026, "text": "Edit src index.js: " }, { "code": null, "e": 30057, "s": 30046, "text": "javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom'; class App extends React.Component { state = { inputValue: '' }; onFormSubmit = (event) => { event.preventDefault(); this.setState({ inputValue: 'Hello World!'}); } render() { return ( <div> <form onSubmit={this.onFormSubmit}> <label> Enter text </label> <input type=\"text\" value={this.state.inputValue} onChange={(e) => this.setState( { inputValue: e.target.value })}/> </form> <br/> <div> Entered Value: {this.state.inputValue} </div> </div> ); }} ReactDOM.render(<App />, document.querySelector('#root'));", "e": 30850, "s": 30057, "text": null }, { "code": null, "e": 30858, "s": 30850, "text": "Output:" }, { "code": null, "e": 31131, "s": 30858, "text": "Here we just add onSubmit event handler which calls the function onFormSumbit and performs the action of replacing the value of inputValue to ‘Hello World!’, and the preventDefault() function is used to prevent the browser from submitting the form and reloading the page. " }, { "code": null, "e": 31145, "s": 31131, "text": "shubhamyadav4" }, { "code": null, "e": 31154, "s": 31145, "text": "react-js" }, { "code": null, "e": 31171, "s": 31154, "text": "Web Technologies" }, { "code": null, "e": 31198, "s": 31171, "text": "Web technologies Questions" }, { "code": null, "e": 31296, "s": 31198, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31305, "s": 31296, "text": "Comments" }, { "code": null, "e": 31318, "s": 31305, "text": "Old Comments" }, { "code": null, "e": 31374, "s": 31318, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 31407, "s": 31374, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31469, "s": 31407, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31512, "s": 31469, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31562, "s": 31512, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 31595, "s": 31562, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31645, "s": 31595, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 31705, "s": 31645, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31732, "s": 31705, "text": "File uploading in React.js" } ]
Quickhull Algorithm for Convex Hull - GeeksforGeeks
28 Jun, 2021 Given a set of points, a Convex hull is the smallest convex polygon containing all the given points. Input is an array of points specified by their x and y coordinates. Output is a convex hull of this set of points in ascending order of x coordinates. Example : Input : points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}}; Output : The points in convex hull are: (0, 0) (0, 3) (3, 1) (4, 4) Input : points[] = {{0, 3}, {1, 1} Output : Not Possible There must be at least three points to form a hull. Input : points[] = {(0, 0), (0, 4), (-4, 0), (5, 0), (0, -6), (1, 0)}; Output : (-4, 0), (5, 0), (0, -6), (0, 4) We have discussed following algorithms for Convex Hull problem.Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping)Convex Hull | Set 2 (Graham Scan) The QuickHull algorithm is a Divide and Conquer algorithm similar to QuickSort. Let a[0...n-1] be the input array of points. Following are the steps for finding the convex hull of these points. Find the point with minimum x-coordinate lets say, min_x and similarly the point with maximum x-coordinate, max_x.Make a line joining these two points, say L. This line will divide the whole set into two parts. Take both the parts one by one and proceed further.For a part, find the point P with maximum distance from the line L. P forms a triangle with the points min_x, max_x. It is clear that the points residing inside this triangle can never be the part of convex hull.The above step divides the problem into two sub-problems (solved recursively). Now the line joining the points P and min_x and the line joining the points P and max_x are new lines and the points residing outside the triangle is the set of points. Repeat point no. 3 till there no point left with the line. Add the end points of this point to the convex hull. Find the point with minimum x-coordinate lets say, min_x and similarly the point with maximum x-coordinate, max_x. Make a line joining these two points, say L. This line will divide the whole set into two parts. Take both the parts one by one and proceed further. For a part, find the point P with maximum distance from the line L. P forms a triangle with the points min_x, max_x. It is clear that the points residing inside this triangle can never be the part of convex hull. The above step divides the problem into two sub-problems (solved recursively). Now the line joining the points P and min_x and the line joining the points P and max_x are new lines and the points residing outside the triangle is the set of points. Repeat point no. 3 till there no point left with the line. Add the end points of this point to the convex hull. Below is C++ implementation of above idea. The implementation uses set to store points so that points can be printed in sorted order. A point is represented as a pair. // C++ program to implement Quick Hull algorithm// to find convex hull.#include<bits/stdc++.h>using namespace std; // iPair is integer pairs#define iPair pair<int, int> // Stores the result (points of convex hull)set<iPair> hull; // Returns the side of point p with respect to line// joining points p1 and p2.int findSide(iPair p1, iPair p2, iPair p){ int val = (p.second - p1.second) * (p2.first - p1.first) - (p2.second - p1.second) * (p.first - p1.first); if (val > 0) return 1; if (val < 0) return -1; return 0;} // returns a value proportional to the distance// between the point p and the line joining the// points p1 and p2int lineDist(iPair p1, iPair p2, iPair p){ return abs ((p.second - p1.second) * (p2.first - p1.first) - (p2.second - p1.second) * (p.first - p1.first));} // End points of line L are p1 and p2. side can have value// 1 or -1 specifying each of the parts made by the line Lvoid quickHull(iPair a[], int n, iPair p1, iPair p2, int side){ int ind = -1; int max_dist = 0; // finding the point with maximum distance // from L and also on the specified side of L. for (int i=0; i<n; i++) { int temp = lineDist(p1, p2, a[i]); if (findSide(p1, p2, a[i]) == side && temp > max_dist) { ind = i; max_dist = temp; } } // If no point is found, add the end points // of L to the convex hull. if (ind == -1) { hull.insert(p1); hull.insert(p2); return; } // Recur for the two parts divided by a[ind] quickHull(a, n, a[ind], p1, -findSide(a[ind], p1, p2)); quickHull(a, n, a[ind], p2, -findSide(a[ind], p2, p1));} void printHull(iPair a[], int n){ // a[i].second -> y-coordinate of the ith point if (n < 3) { cout << "Convex hull not possible\n"; return; } // Finding the point with minimum and // maximum x-coordinate int min_x = 0, max_x = 0; for (int i=1; i<n; i++) { if (a[i].first < a[min_x].first) min_x = i; if (a[i].first > a[max_x].first) max_x = i; } // Recursively find convex hull points on // one side of line joining a[min_x] and // a[max_x] quickHull(a, n, a[min_x], a[max_x], 1); // Recursively find convex hull points on // other side of line joining a[min_x] and // a[max_x] quickHull(a, n, a[min_x], a[max_x], -1); cout << "The points in Convex Hull are:\n"; while (!hull.empty()) { cout << "(" <<( *hull.begin()).first << ", " << (*hull.begin()).second << ") "; hull.erase(hull.begin()); }} // Driver codeint main(){ iPair a[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}}; int n = sizeof(a)/sizeof(a[0]); printHull(a, n); return 0;} Input : The points in Convex Hull are: (0, 0) (0, 3) (3, 1) (4, 4) Time Complexity: The analysis is similar to Quick Sort. On average, we get time complexity as O(n Log n), but in worst case, it can become O(n2) This article is contributed by Amritya Yagni. 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. Akanksha_Rai Divide and Conquer Geometric Technical Scripter Divide and Conquer Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Count number of occurrences (or frequency) in a sorted array Quick Sort vs Merge Sort Closest Pair of Points using Divide and Conquer algorithm Maximum Subarray Sum using Divide and Conquer algorithm Find a peak element Closest Pair of Points using Divide and Conquer algorithm Program for distance between two points on earth Find if two rectangles overlap Check whether triangle is valid or not if sides are given Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
[ { "code": null, "e": 24527, "s": 24499, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24628, "s": 24527, "text": "Given a set of points, a Convex hull is the smallest convex polygon containing all the given points." }, { "code": null, "e": 24779, "s": 24628, "text": "Input is an array of points specified by their x and y coordinates. Output is a convex hull of this set of points in ascending order of x coordinates." }, { "code": null, "e": 24789, "s": 24779, "text": "Example :" }, { "code": null, "e": 25221, "s": 24789, "text": "Input : points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4},\n {0, 0}, {1, 2}, {3, 1}, {3, 3}};\nOutput : The points in convex hull are:\n (0, 0) (0, 3) (3, 1) (4, 4)\n\nInput : points[] = {{0, 3}, {1, 1}\nOutput : Not Possible\nThere must be at least three points to form a hull.\n\nInput : points[] = {(0, 0), (0, 4), (-4, 0), (5, 0), \n (0, -6), (1, 0)};\nOutput : (-4, 0), (5, 0), (0, -6), (0, 4)\n" }, { "code": null, "e": 25370, "s": 25221, "text": "We have discussed following algorithms for Convex Hull problem.Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping)Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 25564, "s": 25370, "text": "The QuickHull algorithm is a Divide and Conquer algorithm similar to QuickSort. Let a[0...n-1] be the input array of points. Following are the steps for finding the convex hull of these points." }, { "code": null, "e": 26398, "s": 25564, "text": "Find the point with minimum x-coordinate lets say, min_x and similarly the point with maximum x-coordinate, max_x.Make a line joining these two points, say L. This line will divide the whole set into two parts. Take both the parts one by one and proceed further.For a part, find the point P with maximum distance from the line L. P forms a triangle with the points min_x, max_x. It is clear that the points residing inside this triangle can never be the part of convex hull.The above step divides the problem into two sub-problems (solved recursively). Now the line joining the points P and min_x and the line joining the points P and max_x are new lines and the points residing outside the triangle is the set of points. Repeat point no. 3 till there no point left with the line. Add the end points of this point to the convex hull." }, { "code": null, "e": 26513, "s": 26398, "text": "Find the point with minimum x-coordinate lets say, min_x and similarly the point with maximum x-coordinate, max_x." }, { "code": null, "e": 26662, "s": 26513, "text": "Make a line joining these two points, say L. This line will divide the whole set into two parts. Take both the parts one by one and proceed further." }, { "code": null, "e": 26875, "s": 26662, "text": "For a part, find the point P with maximum distance from the line L. P forms a triangle with the points min_x, max_x. It is clear that the points residing inside this triangle can never be the part of convex hull." }, { "code": null, "e": 27235, "s": 26875, "text": "The above step divides the problem into two sub-problems (solved recursively). Now the line joining the points P and min_x and the line joining the points P and max_x are new lines and the points residing outside the triangle is the set of points. Repeat point no. 3 till there no point left with the line. Add the end points of this point to the convex hull." }, { "code": null, "e": 27403, "s": 27235, "text": "Below is C++ implementation of above idea. The implementation uses set to store points so that points can be printed in sorted order. A point is represented as a pair." }, { "code": "// C++ program to implement Quick Hull algorithm// to find convex hull.#include<bits/stdc++.h>using namespace std; // iPair is integer pairs#define iPair pair<int, int> // Stores the result (points of convex hull)set<iPair> hull; // Returns the side of point p with respect to line// joining points p1 and p2.int findSide(iPair p1, iPair p2, iPair p){ int val = (p.second - p1.second) * (p2.first - p1.first) - (p2.second - p1.second) * (p.first - p1.first); if (val > 0) return 1; if (val < 0) return -1; return 0;} // returns a value proportional to the distance// between the point p and the line joining the// points p1 and p2int lineDist(iPair p1, iPair p2, iPair p){ return abs ((p.second - p1.second) * (p2.first - p1.first) - (p2.second - p1.second) * (p.first - p1.first));} // End points of line L are p1 and p2. side can have value// 1 or -1 specifying each of the parts made by the line Lvoid quickHull(iPair a[], int n, iPair p1, iPair p2, int side){ int ind = -1; int max_dist = 0; // finding the point with maximum distance // from L and also on the specified side of L. for (int i=0; i<n; i++) { int temp = lineDist(p1, p2, a[i]); if (findSide(p1, p2, a[i]) == side && temp > max_dist) { ind = i; max_dist = temp; } } // If no point is found, add the end points // of L to the convex hull. if (ind == -1) { hull.insert(p1); hull.insert(p2); return; } // Recur for the two parts divided by a[ind] quickHull(a, n, a[ind], p1, -findSide(a[ind], p1, p2)); quickHull(a, n, a[ind], p2, -findSide(a[ind], p2, p1));} void printHull(iPair a[], int n){ // a[i].second -> y-coordinate of the ith point if (n < 3) { cout << \"Convex hull not possible\\n\"; return; } // Finding the point with minimum and // maximum x-coordinate int min_x = 0, max_x = 0; for (int i=1; i<n; i++) { if (a[i].first < a[min_x].first) min_x = i; if (a[i].first > a[max_x].first) max_x = i; } // Recursively find convex hull points on // one side of line joining a[min_x] and // a[max_x] quickHull(a, n, a[min_x], a[max_x], 1); // Recursively find convex hull points on // other side of line joining a[min_x] and // a[max_x] quickHull(a, n, a[min_x], a[max_x], -1); cout << \"The points in Convex Hull are:\\n\"; while (!hull.empty()) { cout << \"(\" <<( *hull.begin()).first << \", \" << (*hull.begin()).second << \") \"; hull.erase(hull.begin()); }} // Driver codeint main(){ iPair a[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}}; int n = sizeof(a)/sizeof(a[0]); printHull(a, n); return 0;}", "e": 30253, "s": 27403, "text": null }, { "code": null, "e": 30261, "s": 30253, "text": "Input :" }, { "code": null, "e": 30322, "s": 30261, "text": "The points in Convex Hull are:\n(0, 0) (0, 3) (3, 1) (4, 4) \n" }, { "code": null, "e": 30467, "s": 30322, "text": "Time Complexity: The analysis is similar to Quick Sort. On average, we get time complexity as O(n Log n), but in worst case, it can become O(n2)" }, { "code": null, "e": 30764, "s": 30467, "text": "This article is contributed by Amritya Yagni. 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": 30889, "s": 30764, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30902, "s": 30889, "text": "Akanksha_Rai" }, { "code": null, "e": 30921, "s": 30902, "text": "Divide and Conquer" }, { "code": null, "e": 30931, "s": 30921, "text": "Geometric" }, { "code": null, "e": 30950, "s": 30931, "text": "Technical Scripter" }, { "code": null, "e": 30969, "s": 30950, "text": "Divide and Conquer" }, { "code": null, "e": 30979, "s": 30969, "text": "Geometric" }, { "code": null, "e": 31077, "s": 30979, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31086, "s": 31077, "text": "Comments" }, { "code": null, "e": 31099, "s": 31086, "text": "Old Comments" }, { "code": null, "e": 31160, "s": 31099, "text": "Count number of occurrences (or frequency) in a sorted array" }, { "code": null, "e": 31185, "s": 31160, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 31243, "s": 31185, "text": "Closest Pair of Points using Divide and Conquer algorithm" }, { "code": null, "e": 31299, "s": 31243, "text": "Maximum Subarray Sum using Divide and Conquer algorithm" }, { "code": null, "e": 31319, "s": 31299, "text": "Find a peak element" }, { "code": null, "e": 31377, "s": 31319, "text": "Closest Pair of Points using Divide and Conquer algorithm" }, { "code": null, "e": 31426, "s": 31377, "text": "Program for distance between two points on earth" }, { "code": null, "e": 31457, "s": 31426, "text": "Find if two rectangles overlap" }, { "code": null, "e": 31515, "s": 31457, "text": "Check whether triangle is valid or not if sides are given" } ]
p5.js | split() function - GeeksforGeeks
06 May, 2022 The split() function in p5.js is used to break the input string into pieces using a delimiter. This delimiter could be any string or symbol used between each piece of the input string. Syntax: split(String, Delimiter) Parameters: This function accepts two parameters which are described below: String: This is the input string which are to be splitted. Delimiter: This is any string or symbol used to separate the data of the input string. Return Value: It returns the splitted data of the input string. Below programs illustrate the split() function in p5.js. Example 1: This example uses split() function to break the input string into pieces of substring using delimiter. javascript function setup() { // Creating Canvas size createCanvas(450, 150);}function draw() { // Set the background color background(220); // Initializing the Strings let String = 'GeeksforGeeks/Geeks/Geek/gfg'; // Calling to split() function. let A = split(String, '/'); // Set the size of text textSize(16); // Set the text color fill(color('red')); // Getting splitted string text("Splitted string is: " + A[0], 50, 30); text("Splitted string is: " + A[1], 50, 60); text("Splitted string is: " + A[2], 50, 90); text("Splitted string is: " + A[3], 50, 120);} Output: Example 2: This example uses split() function to break the input string into pieces of substring using delimiter. javascript function setup() { // Creating Canvas size createCanvas(450, 150);}function draw() { // Set the background color background(220); // Initializing the Strings let String = '0&11&222&3333'; // Calling to split() function. let A = split(String, '&'); // Set the size of text textSize(16); // Set the text color fill(color('red')); // Getting splitted string text("Splitted string is: " + A[0], 50, 30); text("Splitted string is: " + A[1], 50, 60); text("Splitted string is: " + A[2], 50, 90); text("Splitted string is: " + A[3], 50, 120);} Output: Reference: https://p5js.org/reference/#/p5/split rkbhola5 JavaScript-p5.js 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25933, "s": 25905, "text": "\n06 May, 2022" }, { "code": null, "e": 26126, "s": 25933, "text": "The split() function in p5.js is used to break the input string into pieces using a delimiter. This delimiter could be any string or symbol used between each piece of the input string. Syntax:" }, { "code": null, "e": 26151, "s": 26126, "text": "split(String, Delimiter)" }, { "code": null, "e": 26227, "s": 26151, "text": "Parameters: This function accepts two parameters which are described below:" }, { "code": null, "e": 26286, "s": 26227, "text": "String: This is the input string which are to be splitted." }, { "code": null, "e": 26373, "s": 26286, "text": "Delimiter: This is any string or symbol used to separate the data of the input string." }, { "code": null, "e": 26609, "s": 26373, "text": "Return Value: It returns the splitted data of the input string. Below programs illustrate the split() function in p5.js. Example 1: This example uses split() function to break the input string into pieces of substring using delimiter. " }, { "code": null, "e": 26620, "s": 26609, "text": "javascript" }, { "code": "function setup() { // Creating Canvas size createCanvas(450, 150);}function draw() { // Set the background color background(220); // Initializing the Strings let String = 'GeeksforGeeks/Geeks/Geek/gfg'; // Calling to split() function. let A = split(String, '/'); // Set the size of text textSize(16); // Set the text color fill(color('red')); // Getting splitted string text(\"Splitted string is: \" + A[0], 50, 30); text(\"Splitted string is: \" + A[1], 50, 60); text(\"Splitted string is: \" + A[2], 50, 90); text(\"Splitted string is: \" + A[3], 50, 120);}", "e": 27259, "s": 26620, "text": null }, { "code": null, "e": 27383, "s": 27259, "text": "Output: Example 2: This example uses split() function to break the input string into pieces of substring using delimiter. " }, { "code": null, "e": 27394, "s": 27383, "text": "javascript" }, { "code": "function setup() { // Creating Canvas size createCanvas(450, 150);}function draw() { // Set the background color background(220); // Initializing the Strings let String = '0&11&222&3333'; // Calling to split() function. let A = split(String, '&'); // Set the size of text textSize(16); // Set the text color fill(color('red')); // Getting splitted string text(\"Splitted string is: \" + A[0], 50, 30); text(\"Splitted string is: \" + A[1], 50, 60); text(\"Splitted string is: \" + A[2], 50, 90); text(\"Splitted string is: \" + A[3], 50, 120);}", "e": 28018, "s": 27394, "text": null }, { "code": null, "e": 28076, "s": 28018, "text": "Output: Reference: https://p5js.org/reference/#/p5/split" }, { "code": null, "e": 28085, "s": 28076, "text": "rkbhola5" }, { "code": null, "e": 28102, "s": 28085, "text": "JavaScript-p5.js" }, { "code": null, "e": 28113, "s": 28102, "text": "JavaScript" }, { "code": null, "e": 28130, "s": 28113, "text": "Web Technologies" }, { "code": null, "e": 28228, "s": 28130, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28268, "s": 28228, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28313, "s": 28268, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28374, "s": 28313, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28446, "s": 28374, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28498, "s": 28446, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 28538, "s": 28498, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28571, "s": 28538, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28616, "s": 28571, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28659, "s": 28616, "text": "How to fetch data from an API in ReactJS ?" } ]
GATE | GATE CS 2012 | Question 56 - GeeksforGeeks
17 May, 2019 The cost function for a product in a firm is given by 5q2, where q is the amount of production. The firm can sell the product at a market price of Rs 50 per unit. The number of units to be produced by the firm such that the profit is maximized is(A) 5(B) 10(C) 15(D) 25Answer: (A)Explanation: Profit = Price - Cost = 50q - 5q2 The above function will be maximum for the values on which its first derivative becomes 0. 50 - 10*q = 0 50 = 10 * q q = 5. The value of above expression is maximum at q = 5. Quiz of this Question GATE-CS-2012 GATE-GATE CS 2012 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25721, "s": 25693, "text": "\n17 May, 2019" }, { "code": null, "e": 26014, "s": 25721, "text": "The cost function for a product in a firm is given by 5q2, where q is the amount of production. The firm can sell the product at a market price of Rs 50 per unit. The number of units to be produced by the firm such that the profit is maximized is(A) 5(B) 10(C) 15(D) 25Answer: (A)Explanation:" }, { "code": null, "e": 26255, "s": 26014, "text": "Profit = Price - Cost\n = 50q - 5q2\nThe above function will be maximum for the values on which its first derivative becomes 0.\n 50 - 10*q = 0\n 50 = 10 * q\n q = 5.\nThe value of above expression is maximum at q = 5. " }, { "code": null, "e": 26277, "s": 26255, "text": "Quiz of this Question" }, { "code": null, "e": 26290, "s": 26277, "text": "GATE-CS-2012" }, { "code": null, "e": 26308, "s": 26290, "text": "GATE-GATE CS 2012" }, { "code": null, "e": 26313, "s": 26308, "text": "GATE" }, { "code": null, "e": 26411, "s": 26313, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26445, "s": 26411, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26479, "s": 26445, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26513, "s": 26479, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26546, "s": 26513, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26582, "s": 26546, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26618, "s": 26582, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26652, "s": 26618, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26686, "s": 26652, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26720, "s": 26686, "text": "GATE | GATE-CS-2009 | Question 38" } ]
How to insert values into MySQL server table using Python? - GeeksforGeeks
03 Jan, 2021 Prerequisite: Python: MySQL Create Table In this article, we are going to see how to get the size of a table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database Approach: Set up a Database serving either locally or globally. Install Python Connector inorder to communicate with Databases. Establish Database Connection using a Connector. Need to have a Table to insert data, Create a Table if you don’t have any. Modify Data in Table [ CRUD operation ] using a cursor object returned by Connector. Close the Database connection If you are done with it. We are going to use this table: Example 1: Adding one row into a Table with static values : Syntax : “INSERT INTO table_name (column_name) VALUES ( valuesOfRow );” Below is the implementation: Python3 import mysql.connector db = mysql.connector.connect( host="localhost", user="root", passwd="root", database="testdb")# getting the cursor by cursor() methodmycursor = db.cursor() insertQuery = "INSERT INTO Fruits (Fruit_name) VALUES ('Apple');" mycursor.execute(insertQuery) print("No of Record Inserted :", mycursor.rowcount) # we can use the id to refer to that row later.print("Inserted Id :", mycursor.lastrowid) # To ensure the Data Insertion, commit database.db.commit() # close the Connectiondb.close() Output: No of Record Inserted : 1 Inserted Id : 1 How our table looks in SQL after insertion: Example 2: Adding multiple rows into a table with static values : Syntax : ”INSERT INTO table_name (column_name) VALUES ( valuesOfRow1),(valuesOfRow2),....(valuesOfRowN);” Below is the implementation: Python3 import mysql.connector db = mysql.connector.connect( host="localhost", user="root", passwd="root", database="testdb") #getting the cursor by cursor() methodmycursor = db.cursor() insertQuery = '''INSERT INTO Fruits (Fruit_name, Taste, Production_in ) VALUES ('Banana','Sweet',210);''' mycursor.execute(insertQuery) print("No of Record Inserted :", mycursor.rowcount) # To ensure the data insertion, Always commit to the database.db.commit() # close the Connectiondb.close() Output: No of Record Inserted : 2 How our table looks in SQL after insertion: Picked Python-mySQL 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": 25562, "s": 25534, "text": "\n03 Jan, 2021" }, { "code": null, "e": 25603, "s": 25562, "text": "Prerequisite: Python: MySQL Create Table" }, { "code": null, "e": 25936, "s": 25603, "text": "In this article, we are going to see how to get the size of a table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database" }, { "code": null, "e": 25946, "s": 25936, "text": "Approach:" }, { "code": null, "e": 26000, "s": 25946, "text": "Set up a Database serving either locally or globally." }, { "code": null, "e": 26064, "s": 26000, "text": "Install Python Connector inorder to communicate with Databases." }, { "code": null, "e": 26113, "s": 26064, "text": "Establish Database Connection using a Connector." }, { "code": null, "e": 26188, "s": 26113, "text": "Need to have a Table to insert data, Create a Table if you don’t have any." }, { "code": null, "e": 26273, "s": 26188, "text": "Modify Data in Table [ CRUD operation ] using a cursor object returned by Connector." }, { "code": null, "e": 26328, "s": 26273, "text": "Close the Database connection If you are done with it." }, { "code": null, "e": 26360, "s": 26328, "text": "We are going to use this table:" }, { "code": null, "e": 26420, "s": 26360, "text": "Example 1: Adding one row into a Table with static values :" }, { "code": null, "e": 26492, "s": 26420, "text": "Syntax : “INSERT INTO table_name (column_name) VALUES ( valuesOfRow );”" }, { "code": null, "e": 26521, "s": 26492, "text": "Below is the implementation:" }, { "code": null, "e": 26529, "s": 26521, "text": "Python3" }, { "code": "import mysql.connector db = mysql.connector.connect( host=\"localhost\", user=\"root\", passwd=\"root\", database=\"testdb\")# getting the cursor by cursor() methodmycursor = db.cursor() insertQuery = \"INSERT INTO Fruits (Fruit_name) VALUES ('Apple');\" mycursor.execute(insertQuery) print(\"No of Record Inserted :\", mycursor.rowcount) # we can use the id to refer to that row later.print(\"Inserted Id :\", mycursor.lastrowid) # To ensure the Data Insertion, commit database.db.commit() # close the Connectiondb.close()", "e": 27059, "s": 26529, "text": null }, { "code": null, "e": 27068, "s": 27059, "text": " Output:" }, { "code": null, "e": 27110, "s": 27068, "text": "No of Record Inserted : 1\nInserted Id : 1" }, { "code": null, "e": 27154, "s": 27110, "text": "How our table looks in SQL after insertion:" }, { "code": null, "e": 27220, "s": 27154, "text": "Example 2: Adding multiple rows into a table with static values :" }, { "code": null, "e": 27268, "s": 27220, "text": "Syntax : ”INSERT INTO table_name (column_name) " }, { "code": null, "e": 27356, "s": 27268, "text": " VALUES ( valuesOfRow1),(valuesOfRow2),....(valuesOfRowN);”" }, { "code": null, "e": 27385, "s": 27356, "text": "Below is the implementation:" }, { "code": null, "e": 27393, "s": 27385, "text": "Python3" }, { "code": "import mysql.connector db = mysql.connector.connect( host=\"localhost\", user=\"root\", passwd=\"root\", database=\"testdb\") #getting the cursor by cursor() methodmycursor = db.cursor() insertQuery = '''INSERT INTO Fruits (Fruit_name, Taste, Production_in ) VALUES ('Banana','Sweet',210);''' mycursor.execute(insertQuery) print(\"No of Record Inserted :\", mycursor.rowcount) # To ensure the data insertion, Always commit to the database.db.commit() # close the Connectiondb.close()", "e": 27910, "s": 27393, "text": null }, { "code": null, "e": 27918, "s": 27910, "text": "Output:" }, { "code": null, "e": 27944, "s": 27918, "text": "No of Record Inserted : 2" }, { "code": null, "e": 27988, "s": 27944, "text": "How our table looks in SQL after insertion:" }, { "code": null, "e": 27995, "s": 27988, "text": "Picked" }, { "code": null, "e": 28008, "s": 27995, "text": "Python-mySQL" }, { "code": null, "e": 28015, "s": 28008, "text": "Python" }, { "code": null, "e": 28113, "s": 28015, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28145, "s": 28113, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28187, "s": 28145, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28229, "s": 28187, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28256, "s": 28229, "text": "Python Classes and Objects" }, { "code": null, "e": 28312, "s": 28256, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28334, "s": 28312, "text": "Defaultdict in Python" }, { "code": null, "e": 28373, "s": 28334, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28404, "s": 28373, "text": "Python | os.path.join() method" }, { "code": null, "e": 28433, "s": 28404, "text": "Create a directory in Python" } ]
Database Management Systems | Set 1 - GeeksforGeeks
20 Jan, 2022 Following questions have been asked in GATE CS exam. 1. Given the relations employee (name, salary, deptno) and department (deptno, deptname, address) Which of the following queries cannot be expressed using the basic relational algebra operations (U, -, x, π, σ, p)? (GATE CS 2000) (a) Department address of every employee (b) Employees whose name is the same as their department name (c) The sum of all employees’ salaries (d) All employees of a given department Answer: (c) Explanation: The six basic operators of relational algebra are the selection(σ ), the projection(π), the Cartesian product (x) (also called the cross product or cross join), the set union (U), the set difference (-), and the rename (p). These six operators are fundamental in the sense that none of them can be omitted without losing expressive power. Many other operators have been defined in terms of these six. Among the most important are set intersection, division, and the natural join, but aggregation is not possible with these basic relational algebra operations. So, we cannot run sum of all employees’ salaries with the six operations. References: http://en.wikipedia.org/wiki/Relational_algebra http://faculty.ksu.edu.sa/zitouni/203%20Haseb%20%20Lecture%20Notes/Relional%20Algebra.pdf 2. Given the following relation instance. x y z 1 4 2 1 5 3 1 6 3 3 2 2 Which of the following functional dependencies are satisfied by the instance? (GATE CS 2000) (a) XY -> Z and Z -> Y (b) YZ -> X and Y -> Z (c) YZ -> X and X -> Z (d) XZ -> Y and Y -> X Answer: (b) Explanation: A functional dependency (FD) is a constraint between two sets of attributes in a relation from a database. A FD X->Y require that the value of X uniquely determines the value of Y where X and Y are set of attributes. FD is a generalization of the notion of a key. Given that X, Y, and Z are sets of attributes in a relation R, one can derive several properties of functional dependencies. Among the most important are Armstrong’s axioms, which are used in database normalization: * Subset Property (Axiom of Reflexivity): If Y is a subset of X, then X ? Y * Augmentation (Axiom of Augmentation): If X -> Y, then XZ -> YZ * Transitivity (Axiom of Transitivity): If X -> Y and Y -> Z, then X -> Z From these rules, we can derive these secondary rules: * Union: If X -> Y and X -> Z, then X -> YZ * Decomposition: If X -> YZ, then X -> Y and X -> Z * Pseudotransitivity: If X -> Y and YZ -> W, then XZ -> W In the above question, Y uniquely determines X and Z, for a given value of Y you can easily find out values of X and Z. So, Y -> X and Y -> Z hold for above schema. From rule of augmentation we can say YZ->X. If we understand the notion of FD, we don’t need to apply axioms to find out which option is true, just by looking at the schema and options we can say that (b) is true. References: http://www.cse.iitb.ac.in/~sudarsha/db-book/slide-dir/ch7.pdf http://en.wikipedia.org/wiki/Functional_dependency 3. Given relations r(w, x) and s(y, z), the result of select distinct w, x from r, s is guaranteed to be same as r, provided (GATE CS 2000) (a) r has no duplicates and s is non-empty (b) r and s have no duplicates (c) s has no duplicates and r is non-empty (d) r and s have the same number of tuples Answer: (a) Explanation: The query selects all attributes of r. Since we have distinct in query, result can be equal to r only if r doesn’t have duplicates. If we do not give any attribute on which we want to join two tables, then the queries like above become equivalent to Cartesian product. Cartesian product of two sets will be empty if any of the two sets is empty. So, s should have atleast one record to get all rows of r. 4. In SQL, relations can contain null values, and comparisons with null values are treated as unknown. Suppose all comparisons with a null value are treated as false. Which of the following pairs is not equivalent? (GATE CS 2000) (a) x = 5, not (not (x = 5) (b) x = 5, x > 4 and x < 6, where x is an integer (c) x < 5, not(x = 5) (d) None of the above Answer (c) Explanation: It doesn’t need much explanation. For all values smaller than 5, x < 5 will always be true but x = 5 will be false. 5. Consider a schema R(A, B, C, D) and functional dependencies A -> B and C -> D. Then the decomposition of R into R1 (A, B) and R2(C, D) is (GATE CS 2001) a) dependency preserving and loss less join b) loss less join but not dependency preserving c) dependency preserving but not loss less join d) not dependency preserving and not loss less join Answer: (c) Explanation: Dependency Preserving Decomposition: Decomposition of R into R1 and R2 is a dependency preserving decomposition if closure of functional dependencies after decomposition is same as closure of FDs before decomposition. A simple way is to just check whether we can derive all the original FDs from the FDs present after decomposition. In the above question R(A, B, C, D) is decomposed into R1 (A, B) and R2(C, D) and there are only two FDs A -> B and C -> D. So, the decomposition is dependency preserving Lossless-Join Decomposition: Decomposition of R into R1 and R2 is a lossless-join decomposition if at least one of the following functional dependencies are in F+ (Closure of functional dependencies) R1 ∩ R2 → R1 OR R1 ∩ R2 → R2 In the above question R(A, B, C, D) is decomposed into R1 (A, B) and R2(C, D), and R1 ∩ R2 is empty. So, the decomposition is not lossless. References: http://www.cs.sfu.ca/CC/354/han/materia/notes/354notes-chapter6/node1.html ShubhamMaurya3 clintra DBMS GATE CS MCQ DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL | WITH clause SQL | Join (Inner, Left, Right and Full Joins) SQL query to find second highest salary? SQL Interview Questions CTE in SQL Layers of OSI Model TCP/IP Model Types of Operating Systems Page Replacement Algorithms in Operating Systems Differences between TCP and UDP
[ { "code": null, "e": 30871, "s": 30843, "text": "\n20 Jan, 2022" }, { "code": null, "e": 30925, "s": 30871, "text": "Following questions have been asked in GATE CS exam. " }, { "code": null, "e": 30949, "s": 30925, "text": "1. Given the relations " }, { "code": null, "e": 31025, "s": 30949, "text": "employee (name, salary, deptno) and department (deptno, deptname, address) " }, { "code": null, "e": 31340, "s": 31025, "text": "Which of the following queries cannot be expressed using the basic relational algebra operations (U, -, x, π, σ, p)? (GATE CS 2000) (a) Department address of every employee (b) Employees whose name is the same as their department name (c) The sum of all employees’ salaries (d) All employees of a given department " }, { "code": null, "e": 31353, "s": 31340, "text": "Answer: (c) " }, { "code": null, "e": 32001, "s": 31353, "text": "Explanation: The six basic operators of relational algebra are the selection(σ ), the projection(π), the Cartesian product (x) (also called the cross product or cross join), the set union (U), the set difference (-), and the rename (p). These six operators are fundamental in the sense that none of them can be omitted without losing expressive power. Many other operators have been defined in terms of these six. Among the most important are set intersection, division, and the natural join, but aggregation is not possible with these basic relational algebra operations. So, we cannot run sum of all employees’ salaries with the six operations. " }, { "code": null, "e": 32152, "s": 32001, "text": "References: http://en.wikipedia.org/wiki/Relational_algebra http://faculty.ksu.edu.sa/zitouni/203%20Haseb%20%20Lecture%20Notes/Relional%20Algebra.pdf " }, { "code": null, "e": 32196, "s": 32152, "text": "2. Given the following relation instance. " }, { "code": null, "e": 32237, "s": 32196, "text": "x y z\n1 4 2\n1 5 3\n1 6 3\n3 2 2 " }, { "code": null, "e": 32423, "s": 32237, "text": "Which of the following functional dependencies are satisfied by the instance? (GATE CS 2000) (a) XY -> Z and Z -> Y (b) YZ -> X and Y -> Z (c) YZ -> X and X -> Z (d) XZ -> Y and Y -> X " }, { "code": null, "e": 32436, "s": 32423, "text": "Answer: (b) " }, { "code": null, "e": 32714, "s": 32436, "text": "Explanation: A functional dependency (FD) is a constraint between two sets of attributes in a relation from a database. A FD X->Y require that the value of X uniquely determines the value of Y where X and Y are set of attributes. FD is a generalization of the notion of a key. " }, { "code": null, "e": 32932, "s": 32714, "text": "Given that X, Y, and Z are sets of attributes in a relation R, one can derive several properties of functional dependencies. Among the most important are Armstrong’s axioms, which are used in database normalization: " }, { "code": null, "e": 33152, "s": 32932, "text": " \n* Subset Property (Axiom of Reflexivity): If Y is a subset of X, then X ? Y\n* Augmentation (Axiom of Augmentation): If X -> Y, then XZ -> YZ\n* Transitivity (Axiom of Transitivity): If X -> Y and Y -> Z, then X -> Z" }, { "code": null, "e": 33209, "s": 33152, "text": "From these rules, we can derive these secondary rules: " }, { "code": null, "e": 33368, "s": 33209, "text": " \n* Union: If X -> Y and X -> Z, then X -> YZ\n* Decomposition: If X -> YZ, then X -> Y and X -> Z\n* Pseudotransitivity: If X -> Y and YZ -> W, then XZ -> W" }, { "code": null, "e": 33748, "s": 33368, "text": "In the above question, Y uniquely determines X and Z, for a given value of Y you can easily find out values of X and Z. So, Y -> X and Y -> Z hold for above schema. From rule of augmentation we can say YZ->X. If we understand the notion of FD, we don’t need to apply axioms to find out which option is true, just by looking at the schema and options we can say that (b) is true. " }, { "code": null, "e": 33874, "s": 33748, "text": "References: http://www.cse.iitb.ac.in/~sudarsha/db-book/slide-dir/ch7.pdf http://en.wikipedia.org/wiki/Functional_dependency " }, { "code": null, "e": 34175, "s": 33874, "text": "3. Given relations r(w, x) and s(y, z), the result of select distinct w, x from r, s is guaranteed to be same as r, provided (GATE CS 2000) (a) r has no duplicates and s is non-empty (b) r and s have no duplicates (c) s has no duplicates and r is non-empty (d) r and s have the same number of tuples " }, { "code": null, "e": 34188, "s": 34175, "text": "Answer: (a) " }, { "code": null, "e": 34334, "s": 34188, "text": "Explanation: The query selects all attributes of r. Since we have distinct in query, result can be equal to r only if r doesn’t have duplicates. " }, { "code": null, "e": 34608, "s": 34334, "text": "If we do not give any attribute on which we want to join two tables, then the queries like above become equivalent to Cartesian product. Cartesian product of two sets will be empty if any of the two sets is empty. So, s should have atleast one record to get all rows of r. " }, { "code": null, "e": 34961, "s": 34608, "text": "4. In SQL, relations can contain null values, and comparisons with null values are treated as unknown. Suppose all comparisons with a null value are treated as false. Which of the following pairs is not equivalent? (GATE CS 2000) (a) x = 5, not (not (x = 5) (b) x = 5, x > 4 and x < 6, where x is an integer (c) x < 5, not(x = 5) (d) None of the above " }, { "code": null, "e": 34973, "s": 34961, "text": "Answer (c) " }, { "code": null, "e": 35103, "s": 34973, "text": "Explanation: It doesn’t need much explanation. For all values smaller than 5, x < 5 will always be true but x = 5 will be false. " }, { "code": null, "e": 35452, "s": 35103, "text": "5. Consider a schema R(A, B, C, D) and functional dependencies A -> B and C -> D. Then the decomposition of R into R1 (A, B) and R2(C, D) is (GATE CS 2001) a) dependency preserving and loss less join b) loss less join but not dependency preserving c) dependency preserving but not loss less join d) not dependency preserving and not loss less join " }, { "code": null, "e": 35465, "s": 35452, "text": "Answer: (c) " }, { "code": null, "e": 35812, "s": 35465, "text": "Explanation: Dependency Preserving Decomposition: Decomposition of R into R1 and R2 is a dependency preserving decomposition if closure of functional dependencies after decomposition is same as closure of FDs before decomposition. A simple way is to just check whether we can derive all the original FDs from the FDs present after decomposition. " }, { "code": null, "e": 35984, "s": 35812, "text": "In the above question R(A, B, C, D) is decomposed into R1 (A, B) and R2(C, D) and there are only two FDs A -> B and C -> D. So, the decomposition is dependency preserving " }, { "code": null, "e": 36186, "s": 35984, "text": "Lossless-Join Decomposition: Decomposition of R into R1 and R2 is a lossless-join decomposition if at least one of the following functional dependencies are in F+ (Closure of functional dependencies) " }, { "code": null, "e": 36226, "s": 36186, "text": " R1 ∩ R2 → R1\n OR\n R1 ∩ R2 → R2" }, { "code": null, "e": 36367, "s": 36226, "text": "In the above question R(A, B, C, D) is decomposed into R1 (A, B) and R2(C, D), and R1 ∩ R2 is empty. So, the decomposition is not lossless. " }, { "code": null, "e": 36455, "s": 36367, "text": "References: http://www.cs.sfu.ca/CC/354/han/materia/notes/354notes-chapter6/node1.html " }, { "code": null, "e": 36472, "s": 36457, "text": "ShubhamMaurya3" }, { "code": null, "e": 36480, "s": 36472, "text": "clintra" }, { "code": null, "e": 36485, "s": 36480, "text": "DBMS" }, { "code": null, "e": 36493, "s": 36485, "text": "GATE CS" }, { "code": null, "e": 36497, "s": 36493, "text": "MCQ" }, { "code": null, "e": 36502, "s": 36497, "text": "DBMS" }, { "code": null, "e": 36600, "s": 36502, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36618, "s": 36600, "text": "SQL | WITH clause" }, { "code": null, "e": 36665, "s": 36618, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 36706, "s": 36665, "text": "SQL query to find second highest salary?" }, { "code": null, "e": 36730, "s": 36706, "text": "SQL Interview Questions" }, { "code": null, "e": 36741, "s": 36730, "text": "CTE in SQL" }, { "code": null, "e": 36761, "s": 36741, "text": "Layers of OSI Model" }, { "code": null, "e": 36774, "s": 36761, "text": "TCP/IP Model" }, { "code": null, "e": 36801, "s": 36774, "text": "Types of Operating Systems" }, { "code": null, "e": 36850, "s": 36801, "text": "Page Replacement Algorithms in Operating Systems" } ]
HTML5 <aside> Tag - GeeksforGeeks
03 Mar, 2021 The <aside> tag is used to describe the main object of the web page in a shorter way like a highlighter. It basically identifies the content that is related to the primary content of the web page but does not constitute the main intent of the primary page. The <aside> tag contains mainly author information, links, related content, and so on. <aside> vs <div>: Both tags have same behavior with different meaning. <div>: It defines or creates division or section in the web page. <aside>: It does the same job by creating a section or division but it contains only the content that is related to the main web page. The <aside> tag makes it easy to design the page and it enhances the clarity of HTML document. It let us easily recognize the main text and subordinate text. In both the time <div> and <aside> need CSS to specific design. The <aside> tag supports Global attributes and Event attributes in HTML. Note: The <aside> tag is new in HTML5. This tag does not render as anything special in a browser you have to use CSS for that. Syntax: <aside> <h1>Contents...</h1> <p>Contents...</p> </aside> Example: HTML aside Tag HTML <html><body> <h1>GeeksforGeeks</h1> <h2>HTML aside Tag</h2> <h1>This is normal heading Tag</h1> <p>This is normal paragraph text</p> <aside> <h1>This is heading text in aside Tag</h1> <p>This is paragraph text in aside Tag</p> </aside></body></html> Output: Example: Using Style in HTML aside Tag: HTML <html><head> <style> article { width: 50%; padding: 10px; float: left; } aside { width: 40%; float: right; background-color: green; color: white; padding: 5px; margin: 10px; height: 100px; } </style></head><body> <h1>GeeksforGeeks</h1> <article> <h1>Heading . . .</h1> <p> Aside tag is use to display important information about the primary page. </p> </article> <aside> <h1>Aside tag example</h1> <p>Aside tag content. . .</p> </aside></body></html> Output: Supported Browser : Google Chrome 6.0 and above Internet Explorer 9.0 and above Firefox 4.0 and above Opera 11.1 and above Safari 5.0 and above Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. nidhi_biet charles2101 shubhamyadav4 HTML5 Picked HTML Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property Remove elements from a JavaScript Array Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? File uploading in React.js
[ { "code": null, "e": 31646, "s": 31618, "text": "\n03 Mar, 2021" }, { "code": null, "e": 31990, "s": 31646, "text": "The <aside> tag is used to describe the main object of the web page in a shorter way like a highlighter. It basically identifies the content that is related to the primary content of the web page but does not constitute the main intent of the primary page. The <aside> tag contains mainly author information, links, related content, and so on." }, { "code": null, "e": 32062, "s": 31990, "text": "<aside> vs <div>: Both tags have same behavior with different meaning. " }, { "code": null, "e": 32128, "s": 32062, "text": "<div>: It defines or creates division or section in the web page." }, { "code": null, "e": 32263, "s": 32128, "text": "<aside>: It does the same job by creating a section or division but it contains only the content that is related to the main web page." }, { "code": null, "e": 32558, "s": 32263, "text": "The <aside> tag makes it easy to design the page and it enhances the clarity of HTML document. It let us easily recognize the main text and subordinate text. In both the time <div> and <aside> need CSS to specific design. The <aside> tag supports Global attributes and Event attributes in HTML." }, { "code": null, "e": 32685, "s": 32558, "text": "Note: The <aside> tag is new in HTML5. This tag does not render as anything special in a browser you have to use CSS for that." }, { "code": null, "e": 32693, "s": 32685, "text": "Syntax:" }, { "code": null, "e": 32754, "s": 32693, "text": "<aside>\n <h1>Contents...</h1>\n <p>Contents...</p>\n</aside>" }, { "code": null, "e": 32778, "s": 32754, "text": "Example: HTML aside Tag" }, { "code": null, "e": 32783, "s": 32778, "text": "HTML" }, { "code": "<html><body> <h1>GeeksforGeeks</h1> <h2>HTML aside Tag</h2> <h1>This is normal heading Tag</h1> <p>This is normal paragraph text</p> <aside> <h1>This is heading text in aside Tag</h1> <p>This is paragraph text in aside Tag</p> </aside></body></html>", "e": 33067, "s": 32783, "text": null }, { "code": null, "e": 33077, "s": 33067, "text": "Output: " }, { "code": null, "e": 33117, "s": 33077, "text": "Example: Using Style in HTML aside Tag:" }, { "code": null, "e": 33122, "s": 33117, "text": "HTML" }, { "code": "<html><head> <style> article { width: 50%; padding: 10px; float: left; } aside { width: 40%; float: right; background-color: green; color: white; padding: 5px; margin: 10px; height: 100px; } </style></head><body> <h1>GeeksforGeeks</h1> <article> <h1>Heading . . .</h1> <p> Aside tag is use to display important information about the primary page. </p> </article> <aside> <h1>Aside tag example</h1> <p>Aside tag content. . .</p> </aside></body></html>", "e": 33668, "s": 33122, "text": null }, { "code": null, "e": 33676, "s": 33668, "text": "Output:" }, { "code": null, "e": 33697, "s": 33676, "text": "Supported Browser : " }, { "code": null, "e": 33725, "s": 33697, "text": "Google Chrome 6.0 and above" }, { "code": null, "e": 33757, "s": 33725, "text": "Internet Explorer 9.0 and above" }, { "code": null, "e": 33779, "s": 33757, "text": "Firefox 4.0 and above" }, { "code": null, "e": 33800, "s": 33779, "text": "Opera 11.1 and above" }, { "code": null, "e": 33821, "s": 33800, "text": "Safari 5.0 and above" }, { "code": null, "e": 33958, "s": 33821, "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": 33969, "s": 33958, "text": "nidhi_biet" }, { "code": null, "e": 33981, "s": 33969, "text": "charles2101" }, { "code": null, "e": 33995, "s": 33981, "text": "shubhamyadav4" }, { "code": null, "e": 34001, "s": 33995, "text": "HTML5" }, { "code": null, "e": 34008, "s": 34001, "text": "Picked" }, { "code": null, "e": 34013, "s": 34008, "text": "HTML" }, { "code": null, "e": 34040, "s": 34013, "text": "Web technologies Questions" }, { "code": null, "e": 34045, "s": 34040, "text": "HTML" }, { "code": null, "e": 34143, "s": 34045, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34205, "s": 34143, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34255, "s": 34205, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34303, "s": 34255, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34363, "s": 34303, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 34416, "s": 34363, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 34456, "s": 34416, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34489, "s": 34456, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34539, "s": 34489, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34599, "s": 34539, "text": "How to set the default value for an HTML <select> element ?" } ]
First strictly smaller element in a sorted array in Java - GeeksforGeeks
07 Jun, 2021 Given a sorted array and a target value, find the first element that is strictly smaller than given element.Examples: Input : arr[] = {1, 2, 3, 5, 8, 12} Target = 5 Output : 2 (Index of 3) Input : {1, 2, 3, 5, 8, 12} Target = 8 Output : 3 (Index of 5) Input : {1, 2, 3, 5, 8, 12} Target = 15 Output : -1 A simple solution is to linearly traverse given array and find first element that is strictly greater. If no such element exists, then return -1.An efficient solution is to use Binary Search. In a general binary search, we are looking for a value which appears in the array. Sometimes, however, we need to find the first element which is either greater than a target.To see that this algorithm is correct, consider each comparison being made. If we find an element that’s greater than the target element, then it and everything above it can’t possibly match, so there’s no need to search that region. We can thus search the left half. If we find an element that is smaller than the element in question, then anything before it must also be larger, so they can’t be the first element that’s smaller and so we don’t need to search them. The middle element is thus the last possible place it could be.Note that on each iteration we drop off at least half the remaining elements from consideration. If the top branch executes, then the elements in the range [low, (low + high) / 2] are all discarded, causing us to lose floor((low + high) / 2) – low + 1 >= (low + high) / 2 – low = (high – low) / 2 elements.If the bottom branch executes, then the elements in the range [(low + high) / 2 + 1, high] are all discarded. This loses us high – floor(low + high) / 2 + 1 >= high – (low + high) / 2 = (high – low) / 2 elements.Consequently, we’ll end up finding the first element smaller than the target in O(lg n) iterations of this process. C++ Java Python3 C# PHP // C++ program to find first element that// is strictly smaller than given target.#include<bits/stdc++.h>using namespace std; int next(int arr[], int target, int end){ // Minimum size of the array should be 1 if(end == 0) return -1; // If target lies beyond the max element, than the index of strictly smaller // value than target should be (end - 1) if (target > arr[end - 1]) return end-1; int start = 0; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to the left side if the target is smaller if (arr[mid] >= target) { end = mid - 1; } // Move right side else { ans = mid; start = mid + 1; } } return ans;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 5, 8, 12 }; int n = sizeof(arr)/sizeof(arr[0]); cout << (next(arr, 5, n)); return 0;} // This code is contributed by d-dalal // Java program to find first element that// is strictly smaller than given target. class GfG { private static int next(int[] arr, int target) { int start = 0, end = arr.length-1; // Minimum size of the array should be 1 if(end == 0) return -1; // If target lies beyond the max element, than the index of strictly smaller // value than target should be (end - 1) if (target > arr[end]) return end; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to the left side if the target is smaller if (arr[mid] >= target) { end = mid - 1; } // Move right side else { ans = mid; start = mid + 1; } } return ans; } // Driver code public static void main(String[] args) { int[] arr = { 1, 2, 3, 5, 8, 12 }; System.out.println(next(arr, 5)); }} # Python3 program to find first element that# is strictly smaller than given target def next(arr, target): start = 0; end = len(arr) - 1; # Minimum size of the array should be 1 if (end == 0): return -1; ''' If target lies beyond the max element, than the index of strictly smaller value than target should be (end - 1) ''' if (target > arr[end]): return end; ans = -1; while (start <= end): mid = (start + end) // 2; # Move to the left side if target is # smaller if (arr[mid] >= target): end = mid - 1; # Move right side else: ans = mid; start = mid + 1; return ans; # Driver codeif __name__ == '__main__': arr = [ 1, 2, 3, 5, 8, 12 ]; print(next(arr, 5)); # This code is contributed by d-dalal // C# program to find first element that// is strictly smaller than given target.using System;class GfG { private static int next(int[] arr, int target) { int start = 0, end = arr.Length-1; // Minimum size of the array should be 1 if(end == 0) return -1; // If target lies beyond the max element, than the index of strictly smaller // value than target should be (end - 1) if (target > arr[end]) return end; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to the left side if the target is smaller if (arr[mid] >= target) { end = mid - 1; } // Move right side else { ans = mid; start = mid + 1; } } return ans; } // Driver code public static void Main() { int[] arr = { 1, 2, 3, 5, 8, 12 }; Console.WriteLine(next(arr, 5)); }} // This code is contributed by d-dalal. <?php// PHP program to find first element that// is strictly smaller than given target. function next0($arr, $target) { $start = 0; $end = sizeof($arr)-1; // Minimum size of the array should be 1 if($end == 0) return -1; // If target lies beyond the max element, than the index of strictly smaller // value than target should be (end - 1) if ($target > $arr[$end]) return $end; $ans = -1; while ($start <= $end) { $mid =(int)(($start + $end) / 2); // Move to the left side if the target is smaller if ($arr[$mid] >= $target) { $end = $mid - 1; } // Move right side else { $ans = $mid; $start = $mid + 1; } } return $ans; } // Driver code { $arr = array(1, 2, 3, 5, 8, 12 ); echo(next0($arr, 5)); } // This code is contributed by d-dalal. 2 Code_Mech Rajput-Ji Yash_R d-dalal Binary Search Arrays Divide and Conquer Java Programs Searching Arrays Searching Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Multidimensional Arrays in Java Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Merge Sort QuickSort Program for Tower of Hanoi Count Inversions in an array | Set 1 (Using Merge Sort) Divide and Conquer Algorithm | Introduction
[ { "code": null, "e": 25671, "s": 25643, "text": "\n07 Jun, 2021" }, { "code": null, "e": 25791, "s": 25671, "text": "Given a sorted array and a target value, find the first element that is strictly smaller than given element.Examples: " }, { "code": null, "e": 26006, "s": 25791, "text": "Input : arr[] = {1, 2, 3, 5, 8, 12} \n Target = 5\nOutput : 2 (Index of 3)\n\nInput : {1, 2, 3, 5, 8, 12} \n Target = 8\nOutput : 3 (Index of 5)\n\nInput : {1, 2, 3, 5, 8, 12} \n Target = 15\nOutput : -1" }, { "code": null, "e": 27542, "s": 26008, "text": "A simple solution is to linearly traverse given array and find first element that is strictly greater. If no such element exists, then return -1.An efficient solution is to use Binary Search. In a general binary search, we are looking for a value which appears in the array. Sometimes, however, we need to find the first element which is either greater than a target.To see that this algorithm is correct, consider each comparison being made. If we find an element that’s greater than the target element, then it and everything above it can’t possibly match, so there’s no need to search that region. We can thus search the left half. If we find an element that is smaller than the element in question, then anything before it must also be larger, so they can’t be the first element that’s smaller and so we don’t need to search them. The middle element is thus the last possible place it could be.Note that on each iteration we drop off at least half the remaining elements from consideration. If the top branch executes, then the elements in the range [low, (low + high) / 2] are all discarded, causing us to lose floor((low + high) / 2) – low + 1 >= (low + high) / 2 – low = (high – low) / 2 elements.If the bottom branch executes, then the elements in the range [(low + high) / 2 + 1, high] are all discarded. This loses us high – floor(low + high) / 2 + 1 >= high – (low + high) / 2 = (high – low) / 2 elements.Consequently, we’ll end up finding the first element smaller than the target in O(lg n) iterations of this process. " }, { "code": null, "e": 27546, "s": 27542, "text": "C++" }, { "code": null, "e": 27551, "s": 27546, "text": "Java" }, { "code": null, "e": 27559, "s": 27551, "text": "Python3" }, { "code": null, "e": 27562, "s": 27559, "text": "C#" }, { "code": null, "e": 27566, "s": 27562, "text": "PHP" }, { "code": "// C++ program to find first element that// is strictly smaller than given target.#include<bits/stdc++.h>using namespace std; int next(int arr[], int target, int end){ // Minimum size of the array should be 1 if(end == 0) return -1; // If target lies beyond the max element, than the index of strictly smaller // value than target should be (end - 1) if (target > arr[end - 1]) return end-1; int start = 0; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to the left side if the target is smaller if (arr[mid] >= target) { end = mid - 1; } // Move right side else { ans = mid; start = mid + 1; } } return ans;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 5, 8, 12 }; int n = sizeof(arr)/sizeof(arr[0]); cout << (next(arr, 5, n)); return 0;} // This code is contributed by d-dalal", "e": 28532, "s": 27566, "text": null }, { "code": "// Java program to find first element that// is strictly smaller than given target. class GfG { private static int next(int[] arr, int target) { int start = 0, end = arr.length-1; // Minimum size of the array should be 1 if(end == 0) return -1; // If target lies beyond the max element, than the index of strictly smaller // value than target should be (end - 1) if (target > arr[end]) return end; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to the left side if the target is smaller if (arr[mid] >= target) { end = mid - 1; } // Move right side else { ans = mid; start = mid + 1; } } return ans; } // Driver code public static void main(String[] args) { int[] arr = { 1, 2, 3, 5, 8, 12 }; System.out.println(next(arr, 5)); }}", "e": 29546, "s": 28532, "text": null }, { "code": "# Python3 program to find first element that# is strictly smaller than given target def next(arr, target): start = 0; end = len(arr) - 1; # Minimum size of the array should be 1 if (end == 0): return -1; ''' If target lies beyond the max element, than the index of strictly smaller value than target should be (end - 1) ''' if (target > arr[end]): return end; ans = -1; while (start <= end): mid = (start + end) // 2; # Move to the left side if target is # smaller if (arr[mid] >= target): end = mid - 1; # Move right side else: ans = mid; start = mid + 1; return ans; # Driver codeif __name__ == '__main__': arr = [ 1, 2, 3, 5, 8, 12 ]; print(next(arr, 5)); # This code is contributed by d-dalal", "e": 30390, "s": 29546, "text": null }, { "code": "// C# program to find first element that// is strictly smaller than given target.using System;class GfG { private static int next(int[] arr, int target) { int start = 0, end = arr.Length-1; // Minimum size of the array should be 1 if(end == 0) return -1; // If target lies beyond the max element, than the index of strictly smaller // value than target should be (end - 1) if (target > arr[end]) return end; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to the left side if the target is smaller if (arr[mid] >= target) { end = mid - 1; } // Move right side else { ans = mid; start = mid + 1; } } return ans; } // Driver code public static void Main() { int[] arr = { 1, 2, 3, 5, 8, 12 }; Console.WriteLine(next(arr, 5)); }} // This code is contributed by d-dalal.", "e": 31417, "s": 30390, "text": null }, { "code": "<?php// PHP program to find first element that// is strictly smaller than given target. function next0($arr, $target) { $start = 0; $end = sizeof($arr)-1; // Minimum size of the array should be 1 if($end == 0) return -1; // If target lies beyond the max element, than the index of strictly smaller // value than target should be (end - 1) if ($target > $arr[$end]) return $end; $ans = -1; while ($start <= $end) { $mid =(int)(($start + $end) / 2); // Move to the left side if the target is smaller if ($arr[$mid] >= $target) { $end = $mid - 1; } // Move right side else { $ans = $mid; $start = $mid + 1; } } return $ans; } // Driver code { $arr = array(1, 2, 3, 5, 8, 12 ); echo(next0($arr, 5)); } // This code is contributed by d-dalal.", "e": 32425, "s": 31417, "text": null }, { "code": null, "e": 32427, "s": 32425, "text": "2" }, { "code": null, "e": 32439, "s": 32429, "text": "Code_Mech" }, { "code": null, "e": 32449, "s": 32439, "text": "Rajput-Ji" }, { "code": null, "e": 32456, "s": 32449, "text": "Yash_R" }, { "code": null, "e": 32464, "s": 32456, "text": "d-dalal" }, { "code": null, "e": 32478, "s": 32464, "text": "Binary Search" }, { "code": null, "e": 32485, "s": 32478, "text": "Arrays" }, { "code": null, "e": 32504, "s": 32485, "text": "Divide and Conquer" }, { "code": null, "e": 32518, "s": 32504, "text": "Java Programs" }, { "code": null, "e": 32528, "s": 32518, "text": "Searching" }, { "code": null, "e": 32535, "s": 32528, "text": "Arrays" }, { "code": null, "e": 32545, "s": 32535, "text": "Searching" }, { "code": null, "e": 32564, "s": 32545, "text": "Divide and Conquer" }, { "code": null, "e": 32578, "s": 32564, "text": "Binary Search" }, { "code": null, "e": 32676, "s": 32578, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32699, "s": 32676, "text": "Introduction to Arrays" }, { "code": null, "e": 32731, "s": 32699, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32752, "s": 32731, "text": "Linked List vs Array" }, { "code": null, "e": 32837, "s": 32752, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 32882, "s": 32837, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 32893, "s": 32882, "text": "Merge Sort" }, { "code": null, "e": 32903, "s": 32893, "text": "QuickSort" }, { "code": null, "e": 32930, "s": 32903, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 32986, "s": 32930, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" } ]
How to iterate over a TreeMap in Java? - GeeksforGeeks
03 May, 2022 Given a TreeMap, the task is to iterate this TreeMap in Java. The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. We cannot iterate a TreeMap directly using iterators, because TreeMap is not a Collection. So we will have to use TreeMap.entrySet() method. This method returns a collection-view(Set<Map.Entry>) of the mappings contained in this treemap. So we can iterate over key-value pair using getKey() and getValue() methods of Map.Entry. This method is most common and should be used if you need both map keys and values in the loop. Example 1: Java // Java program to iterate over a TreeMap import java.util.Map;import java.util.TreeMap; class IterationDemo { public static void main(String[] arg) { Map<String, String> gfg = new TreeMap<String, String>(); // enter name/url pair gfg.put("GFG", "geeksforgeeks.org"); gfg.put("Practice", "practice.geeksforgeeks.org"); gfg.put("Code", "code.geeksforgeeks.org"); gfg.put("Quiz", "quiz.geeksforgeeks.org"); // using for-each loop for // iteration over TreeMap.entrySet() for (Map.Entry<String, String> entry : gfg.entrySet()) System.out.println( "[" + entry.getKey() + ", " + entry.getValue() + "]"); }} [Code, code.geeksforgeeks.org] [GFG, geeksforgeeks.org] [Practice, practice.geeksforgeeks.org] [Quiz, quiz.geeksforgeeks.org] Now let us see traversal over the entries in the TreeMap object. In order to implement, we are considering very simple map elements associativity where we are having three elements say they be “Geeks”, “for”, “Geeks” and be the key value ‘1’, ‘2’ and ‘3’ of integer type. So from this only we are able to get we need to make an object of TreeMap class. Example 2: Java // Java Program to Iterate Over Entries in a TreeMap import java.util.*; // Importing required// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a TreeMap class object // Objects are of key-value pairs (integer and // string type) TreeMap<Integer, String> tm = new TreeMap<Integer, String>(); // Customly adding elements tm.put(1, "Geeks"); tm.put(2, "For"); tm.put(3, "Geeks"); // Get all entries using the entrySet() method Set<Map.Entry<Integer, String> > entries = tm.entrySet(); // Way 1 // Using for loops for (Map.Entry<Integer, String> entry : entries) { System.out.println(entry.getKey() + "->" + entry.getValue()); } // New line to differentiate differences in output // between for loop and for each loop System.out.println(); // Way 2 - getting code shorter and simpler // For each loops entries.forEach(entry -> { System.out.println(entry.getKey() + "->" + entry.getValue()); }); // New line to differentiate differences in output // between for each loop and iterator traversal System.out.println(); // Way 3 - New way to // Getting an iterator Iterator<Map.Entry<Integer, String> > iterator = entries.iterator(); // Additional step here // To Initialize object holding for // key-value pairs to null Map.Entry<Integer, String> entry = null; // Holds true till there is no element remaining in // the object using hasNExt() method while (iterator.hasNext()) { // Moving onto next pairs using next() method entry = iterator.next(); // Printing the key-value pairs // using getKet() and getValue() methods System.out.println(entry.getKey() + "->" + entry.getValue()); } }} 1->Geeks 2->For 3->Geeks 1->Geeks 2->For 3->Geeks 1->Geeks 2->For 3->Geeks solankimayank sweetyty anikakapoor avtarkumar719 java-TreeMap Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Multithreading in Java Collections in Java Initializing a List in Java Overriding in Java
[ { "code": null, "e": 25443, "s": 25415, "text": "\n03 May, 2022" }, { "code": null, "e": 26033, "s": 25443, "text": "Given a TreeMap, the task is to iterate this TreeMap in Java. The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. We cannot iterate a TreeMap directly using iterators, because TreeMap is not a Collection. So we will have to use TreeMap.entrySet() method. This method returns a collection-view(Set<Map.Entry>) of the mappings contained in this treemap. So we can iterate over key-value pair using getKey() and getValue() methods of Map.Entry. This method is most common and should be used if you need both map keys and values in the loop. " }, { "code": null, "e": 26044, "s": 26033, "text": "Example 1:" }, { "code": null, "e": 26049, "s": 26044, "text": "Java" }, { "code": "// Java program to iterate over a TreeMap import java.util.Map;import java.util.TreeMap; class IterationDemo { public static void main(String[] arg) { Map<String, String> gfg = new TreeMap<String, String>(); // enter name/url pair gfg.put(\"GFG\", \"geeksforgeeks.org\"); gfg.put(\"Practice\", \"practice.geeksforgeeks.org\"); gfg.put(\"Code\", \"code.geeksforgeeks.org\"); gfg.put(\"Quiz\", \"quiz.geeksforgeeks.org\"); // using for-each loop for // iteration over TreeMap.entrySet() for (Map.Entry<String, String> entry : gfg.entrySet()) System.out.println( \"[\" + entry.getKey() + \", \" + entry.getValue() + \"]\"); }}", "e": 26793, "s": 26049, "text": null }, { "code": null, "e": 26919, "s": 26793, "text": "[Code, code.geeksforgeeks.org]\n[GFG, geeksforgeeks.org]\n[Practice, practice.geeksforgeeks.org]\n[Quiz, quiz.geeksforgeeks.org]" }, { "code": null, "e": 27274, "s": 26921, "text": "Now let us see traversal over the entries in the TreeMap object. In order to implement, we are considering very simple map elements associativity where we are having three elements say they be “Geeks”, “for”, “Geeks” and be the key value ‘1’, ‘2’ and ‘3’ of integer type. So from this only we are able to get we need to make an object of TreeMap class." }, { "code": null, "e": 27285, "s": 27274, "text": "Example 2:" }, { "code": null, "e": 27290, "s": 27285, "text": "Java" }, { "code": "// Java Program to Iterate Over Entries in a TreeMap import java.util.*; // Importing required// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a TreeMap class object // Objects are of key-value pairs (integer and // string type) TreeMap<Integer, String> tm = new TreeMap<Integer, String>(); // Customly adding elements tm.put(1, \"Geeks\"); tm.put(2, \"For\"); tm.put(3, \"Geeks\"); // Get all entries using the entrySet() method Set<Map.Entry<Integer, String> > entries = tm.entrySet(); // Way 1 // Using for loops for (Map.Entry<Integer, String> entry : entries) { System.out.println(entry.getKey() + \"->\" + entry.getValue()); } // New line to differentiate differences in output // between for loop and for each loop System.out.println(); // Way 2 - getting code shorter and simpler // For each loops entries.forEach(entry -> { System.out.println(entry.getKey() + \"->\" + entry.getValue()); }); // New line to differentiate differences in output // between for each loop and iterator traversal System.out.println(); // Way 3 - New way to // Getting an iterator Iterator<Map.Entry<Integer, String> > iterator = entries.iterator(); // Additional step here // To Initialize object holding for // key-value pairs to null Map.Entry<Integer, String> entry = null; // Holds true till there is no element remaining in // the object using hasNExt() method while (iterator.hasNext()) { // Moving onto next pairs using next() method entry = iterator.next(); // Printing the key-value pairs // using getKet() and getValue() methods System.out.println(entry.getKey() + \"->\" + entry.getValue()); } }}", "e": 29396, "s": 27290, "text": null }, { "code": null, "e": 29473, "s": 29396, "text": "1->Geeks\n2->For\n3->Geeks\n\n1->Geeks\n2->For\n3->Geeks\n\n1->Geeks\n2->For\n3->Geeks" }, { "code": null, "e": 29487, "s": 29473, "text": "solankimayank" }, { "code": null, "e": 29496, "s": 29487, "text": "sweetyty" }, { "code": null, "e": 29508, "s": 29496, "text": "anikakapoor" }, { "code": null, "e": 29522, "s": 29508, "text": "avtarkumar719" }, { "code": null, "e": 29535, "s": 29522, "text": "java-TreeMap" }, { "code": null, "e": 29540, "s": 29535, "text": "Java" }, { "code": null, "e": 29545, "s": 29540, "text": "Java" }, { "code": null, "e": 29643, "s": 29545, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29658, "s": 29643, "text": "Stream In Java" }, { "code": null, "e": 29677, "s": 29658, "text": "Interfaces in Java" }, { "code": null, "e": 29695, "s": 29677, "text": "ArrayList in Java" }, { "code": null, "e": 29715, "s": 29695, "text": "Stack Class in Java" }, { "code": null, "e": 29739, "s": 29715, "text": "Singleton Class in Java" }, { "code": null, "e": 29771, "s": 29739, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29794, "s": 29771, "text": "Multithreading in Java" }, { "code": null, "e": 29814, "s": 29794, "text": "Collections in Java" }, { "code": null, "e": 29842, "s": 29814, "text": "Initializing a List in Java" } ]
Collections replaceAll() Method in Java with Examples - GeeksforGeeks
22 Apr, 2022 The replaceAll() method of java.util.Collections class is used to replace all occurrences of one specified value in a list with another. More formally, replaces with newVal each element e in the list such that oldVal == null ? e==null : oldVal.equals(e) Note: This method has no effect on the size of the list. Parameters: This method takes the following argument as a Parameter list: The list in which replacement is to occur. oldVal: The old value to be replaced. newVal: The new value with which oldVal is to be replaced. Return Value: This method returns true if the list contained one or more elements e such that as shown below else false oldVal== null ? e==null : oldVal.equals(e) Syntax: public static boolean replaceAll(List list, T oldVal, T newVal) Example 1: Java // Java program to demonstrate// replaceAll() method for String value // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) throws Exception { // Try block to check for exceptions try { // Creating a vector object of string type List<String> vector = new Vector<String>(); // Populating the above Vector object // Custom input elements vector.add("A"); vector.add("B"); vector.add("A"); vector.add("C"); // Printing the vector System.out.println("Initial Vector :" + vector); // Replacing value // using replaceAll() method Collections.replaceAll(vector, "A", "TAJMAHAL"); // Printing elements of Vector object after // replacing System.out.println("Vector after replace :" + vector); } // Catch block to handle the exceptions catch (IllegalArgumentException e) { // Display message when exception occurs System.out.println("Exception thrown : " + e); } }} Initial Vector :[A, B, A, C] Vector after replace :[TAJMAHAL, B, TAJMAHAL, C] Example 2: Java // Java program to demonstrate// replaceAll() method for Integer value // importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) throws Exception { // Try block to check for exceptions try { // Creating object of List<String> List<Integer> vector = new Vector<Integer>(); // Populate the vector vector.add(20); vector.add(30); vector.add(20); vector.add(30); // Printing the vector before replacing // elements System.out.println("Initial values are :" + vector); // Replacing value // using replaceAll() method Collections.replaceAll(vector, 20, 400); // Printing the vector after replacing elements System.out.println("Value after replace :" + vector); } // Catch block to handle IllegalArgumentException catch (IllegalArgumentException e) { // Display the exceptions on the console System.out.println("Exception thrown : " + e); } }} Initial values are :[20, 30, 20, 30] Value after replace :[400, 30, 400, 30] solankimayank varshagumber28 sumitgumber28 Java - util package Java-Collections Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25731, "s": 25703, "text": "\n22 Apr, 2022" }, { "code": null, "e": 25942, "s": 25731, "text": "The replaceAll() method of java.util.Collections class is used to replace all occurrences of one specified value in a list with another. More formally, replaces with newVal each element e in the list such that " }, { "code": null, "e": 25987, "s": 25942, "text": "oldVal == null ? e==null : oldVal.equals(e) " }, { "code": null, "e": 26044, "s": 25987, "text": "Note: This method has no effect on the size of the list." }, { "code": null, "e": 26114, "s": 26044, "text": "Parameters: This method takes the following argument as a Parameter " }, { "code": null, "e": 26163, "s": 26114, "text": "list: The list in which replacement is to occur." }, { "code": null, "e": 26201, "s": 26163, "text": "oldVal: The old value to be replaced." }, { "code": null, "e": 26260, "s": 26201, "text": "newVal: The new value with which oldVal is to be replaced." }, { "code": null, "e": 26381, "s": 26260, "text": "Return Value: This method returns true if the list contained one or more elements e such that as shown below else false " }, { "code": null, "e": 26424, "s": 26381, "text": "oldVal== null ? e==null : oldVal.equals(e)" }, { "code": null, "e": 26433, "s": 26424, "text": "Syntax: " }, { "code": null, "e": 26498, "s": 26433, "text": "public static boolean replaceAll(List list, T oldVal, T newVal)" }, { "code": null, "e": 26509, "s": 26498, "text": "Example 1:" }, { "code": null, "e": 26514, "s": 26509, "text": "Java" }, { "code": "// Java program to demonstrate// replaceAll() method for String value // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) throws Exception { // Try block to check for exceptions try { // Creating a vector object of string type List<String> vector = new Vector<String>(); // Populating the above Vector object // Custom input elements vector.add(\"A\"); vector.add(\"B\"); vector.add(\"A\"); vector.add(\"C\"); // Printing the vector System.out.println(\"Initial Vector :\" + vector); // Replacing value // using replaceAll() method Collections.replaceAll(vector, \"A\", \"TAJMAHAL\"); // Printing elements of Vector object after // replacing System.out.println(\"Vector after replace :\" + vector); } // Catch block to handle the exceptions catch (IllegalArgumentException e) { // Display message when exception occurs System.out.println(\"Exception thrown : \" + e); } }}", "e": 27749, "s": 26514, "text": null }, { "code": null, "e": 27827, "s": 27749, "text": "Initial Vector :[A, B, A, C]\nVector after replace :[TAJMAHAL, B, TAJMAHAL, C]" }, { "code": null, "e": 27838, "s": 27827, "text": "Example 2:" }, { "code": null, "e": 27843, "s": 27838, "text": "Java" }, { "code": "// Java program to demonstrate// replaceAll() method for Integer value // importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) throws Exception { // Try block to check for exceptions try { // Creating object of List<String> List<Integer> vector = new Vector<Integer>(); // Populate the vector vector.add(20); vector.add(30); vector.add(20); vector.add(30); // Printing the vector before replacing // elements System.out.println(\"Initial values are :\" + vector); // Replacing value // using replaceAll() method Collections.replaceAll(vector, 20, 400); // Printing the vector after replacing elements System.out.println(\"Value after replace :\" + vector); } // Catch block to handle IllegalArgumentException catch (IllegalArgumentException e) { // Display the exceptions on the console System.out.println(\"Exception thrown : \" + e); } }}", "e": 29073, "s": 27843, "text": null }, { "code": null, "e": 29150, "s": 29073, "text": "Initial values are :[20, 30, 20, 30]\nValue after replace :[400, 30, 400, 30]" }, { "code": null, "e": 29166, "s": 29152, "text": "solankimayank" }, { "code": null, "e": 29181, "s": 29166, "text": "varshagumber28" }, { "code": null, "e": 29195, "s": 29181, "text": "sumitgumber28" }, { "code": null, "e": 29215, "s": 29195, "text": "Java - util package" }, { "code": null, "e": 29232, "s": 29215, "text": "Java-Collections" }, { "code": null, "e": 29247, "s": 29232, "text": "Java-Functions" }, { "code": null, "e": 29252, "s": 29247, "text": "Java" }, { "code": null, "e": 29257, "s": 29252, "text": "Java" }, { "code": null, "e": 29274, "s": 29257, "text": "Java-Collections" }, { "code": null, "e": 29372, "s": 29274, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29423, "s": 29372, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29453, "s": 29423, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29472, "s": 29453, "text": "Interfaces in Java" }, { "code": null, "e": 29487, "s": 29472, "text": "Stream In Java" }, { "code": null, "e": 29518, "s": 29487, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29536, "s": 29518, "text": "ArrayList in Java" }, { "code": null, "e": 29568, "s": 29536, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29588, "s": 29568, "text": "Stack Class in Java" }, { "code": null, "e": 29620, "s": 29588, "text": "Multidimensional Arrays in Java" } ]
How to disable a CSS :hover effect? - GeeksforGeeks
17 Sep, 2019 The task is to remove the CSS:hover property from the element. Here we are going to use JavaScript to solve the problem.Approach 1: Simply remove the class which is adding the hover effect to the element using JQuery by .removeClass() method. Example 1: This example using the approach discussed above. <!DOCTYPE HTML> <html> <head> <title> How to Disable a CSS :hover effect. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> .element { height: 100px; width: 200px; background: green; color: white; margin: 0 auto; } .hover:hover { background: blue; } </style> </head> <body style = "text-align:center;" id = "body"> <h1 id = "h1" style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <div id = "div" class = "element hover"> Hover It </div> <br> <button onclick = "gfg_Run()"> Click here </button> <p id = "GFG_DOWN" style = "font-size: 23px; font-weight: bold; color: green; "> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var heading = document.getElementById("h1"); var div = document.getElementById("div"); el_up.innerHTML = "Click on the button to remove the CSS:hover effect."; function gfg_Run() { $('#div').removeClass('hover'); el_down.innerHTML = "Hover effect Removed"; } </script> </body> </html> Output: Before clicking on the button: On hovering over the element: After clicking on the button: Approach 2: Simply remove the class which is adding the hover effect to the element using JavaScript by .classList.remove() method. Example 2: This example using the approach discussed above. <!DOCTYPE HTML> <html> <head> <title> How to Disable a CSS :hover effect. </title> <style> .element { height: 100px; width: 200px; background: green; color: white; margin: 0 auto; } .hover:hover { background: blue; } </style> </head> <body style = "text-align:center;" id = "body"> <h1 id = "h1" style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <div id = "div" class = "element hover"> Hover It </div> <br> <button onclick = "gfg_Run()"> Click here </button> <p id = "GFG_DOWN" style = "font-size: 23px; font-weight: bold; color: green; "> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var heading = document.getElementById("h1"); var div = document.getElementById("div"); el_up.innerHTML = "Click on the button to remove the CSS:hover effect."; function gfg_Run() { document.getElementById('div').classList.remove("hover"); el_down.innerHTML = "Hover effect Removed"; } </script> </body> </html> Output: Before clicking on the button: On hovering over the element: After clicking on the button: JavaScript-Misc 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26433, "s": 26405, "text": "\n17 Sep, 2019" }, { "code": null, "e": 26565, "s": 26433, "text": "The task is to remove the CSS:hover property from the element. Here we are going to use JavaScript to solve the problem.Approach 1:" }, { "code": null, "e": 26676, "s": 26565, "text": "Simply remove the class which is adding the hover effect to the element using JQuery by .removeClass() method." }, { "code": null, "e": 26736, "s": 26676, "text": "Example 1: This example using the approach discussed above." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to Disable a CSS :hover effect. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> .element { height: 100px; width: 200px; background: green; color: white; margin: 0 auto; } .hover:hover { background: blue; } </style> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 id = \"h1\" style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <div id = \"div\" class = \"element hover\"> Hover It </div> <br> <button onclick = \"gfg_Run()\"> Click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 23px; font-weight: bold; color: green; \"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var heading = document.getElementById(\"h1\"); var div = document.getElementById(\"div\"); el_up.innerHTML = \"Click on the button to remove the CSS:hover effect.\"; function gfg_Run() { $('#div').removeClass('hover'); el_down.innerHTML = \"Hover effect Removed\"; } </script> </body> </html>", "e": 28298, "s": 26736, "text": null }, { "code": null, "e": 28306, "s": 28298, "text": "Output:" }, { "code": null, "e": 28337, "s": 28306, "text": "Before clicking on the button:" }, { "code": null, "e": 28367, "s": 28337, "text": "On hovering over the element:" }, { "code": null, "e": 28397, "s": 28367, "text": "After clicking on the button:" }, { "code": null, "e": 28409, "s": 28397, "text": "Approach 2:" }, { "code": null, "e": 28529, "s": 28409, "text": "Simply remove the class which is adding the hover effect to the element using JavaScript by .classList.remove() method." }, { "code": null, "e": 28589, "s": 28529, "text": "Example 2: This example using the approach discussed above." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to Disable a CSS :hover effect. </title> <style> .element { height: 100px; width: 200px; background: green; color: white; margin: 0 auto; } .hover:hover { background: blue; } </style> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 id = \"h1\" style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <div id = \"div\" class = \"element hover\"> Hover It </div> <br> <button onclick = \"gfg_Run()\"> Click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 23px; font-weight: bold; color: green; \"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var heading = document.getElementById(\"h1\"); var div = document.getElementById(\"div\"); el_up.innerHTML = \"Click on the button to remove the CSS:hover effect.\"; function gfg_Run() { document.getElementById('div').classList.remove(\"hover\"); el_down.innerHTML = \"Hover effect Removed\"; } </script> </body> </html>", "e": 30075, "s": 28589, "text": null }, { "code": null, "e": 30083, "s": 30075, "text": "Output:" }, { "code": null, "e": 30114, "s": 30083, "text": "Before clicking on the button:" }, { "code": null, "e": 30144, "s": 30114, "text": "On hovering over the element:" }, { "code": null, "e": 30174, "s": 30144, "text": "After clicking on the button:" }, { "code": null, "e": 30190, "s": 30174, "text": "JavaScript-Misc" }, { "code": null, "e": 30201, "s": 30190, "text": "JavaScript" }, { "code": null, "e": 30218, "s": 30201, "text": "Web Technologies" }, { "code": null, "e": 30316, "s": 30218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30356, "s": 30316, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30401, "s": 30356, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30462, "s": 30401, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30534, "s": 30462, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 30586, "s": 30534, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 30626, "s": 30586, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30659, "s": 30626, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30704, "s": 30659, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30747, "s": 30704, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | Pandas Series.size - GeeksforGeeks
28 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.size attribute returns the number of elements in the underlying data for the given series objects. Syntax:Series.size Parameter : None Returns : size Example #1: Use Series.size attribute to find the number of elements in the underlying data of the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # Print the seriesprint(sr) Output : Now we will use Series.size attribute to find the number of elements in the underlying data of the given Series object. # return the number of elementssr.size Output :As we can see in the output, the Series.size attribute has returned 5 indicating that there are 5 elements in the given series object. Example #2 : Use Series.size attribute to find the number of elements in the underlying data of the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr) Output :Now we will use Series.size attribute to find the number of elements in the underlying data of the given Series object. # return the number of elementssr.size Output :As we can see in the output, the Series.size attribute has returned 4 indicating that there are 4 elements in the given series object. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python
[ { "code": null, "e": 26141, "s": 26113, "text": "\n28 Jan, 2019" }, { "code": null, "e": 26355, "s": 26141, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26612, "s": 26355, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 26725, "s": 26612, "text": "Pandas Series.size attribute returns the number of elements in the underlying data for the given series objects." }, { "code": null, "e": 26744, "s": 26725, "text": "Syntax:Series.size" }, { "code": null, "e": 26761, "s": 26744, "text": "Parameter : None" }, { "code": null, "e": 26776, "s": 26761, "text": "Returns : size" }, { "code": null, "e": 26896, "s": 26776, "text": "Example #1: Use Series.size attribute to find the number of elements in the underlying data of the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # Print the seriesprint(sr)", "e": 27153, "s": 26896, "text": null }, { "code": null, "e": 27162, "s": 27153, "text": "Output :" }, { "code": null, "e": 27282, "s": 27162, "text": "Now we will use Series.size attribute to find the number of elements in the underlying data of the given Series object." }, { "code": "# return the number of elementssr.size", "e": 27321, "s": 27282, "text": null }, { "code": null, "e": 27585, "s": 27321, "text": "Output :As we can see in the output, the Series.size attribute has returned 5 indicating that there are 5 elements in the given series object. Example #2 : Use Series.size attribute to find the number of elements in the underlying data of the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr)", "e": 27824, "s": 27585, "text": null }, { "code": null, "e": 27952, "s": 27824, "text": "Output :Now we will use Series.size attribute to find the number of elements in the underlying data of the given Series object." }, { "code": "# return the number of elementssr.size", "e": 27991, "s": 27952, "text": null }, { "code": null, "e": 28134, "s": 27991, "text": "Output :As we can see in the output, the Series.size attribute has returned 4 indicating that there are 4 elements in the given series object." }, { "code": null, "e": 28155, "s": 28134, "text": "Python pandas-series" }, { "code": null, "e": 28184, "s": 28155, "text": "Python pandas-series-methods" }, { "code": null, "e": 28198, "s": 28184, "text": "Python-pandas" }, { "code": null, "e": 28205, "s": 28198, "text": "Python" }, { "code": null, "e": 28303, "s": 28205, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28321, "s": 28303, "text": "Python Dictionary" }, { "code": null, "e": 28356, "s": 28321, "text": "Read a file line by line in Python" }, { "code": null, "e": 28388, "s": 28356, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28410, "s": 28388, "text": "Enumerate() in Python" }, { "code": null, "e": 28452, "s": 28410, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28482, "s": 28452, "text": "Iterate over a list in Python" }, { "code": null, "e": 28511, "s": 28482, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28555, "s": 28511, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28592, "s": 28555, "text": "Create a Pandas DataFrame from Lists" } ]
Ruby | Array delete_if() operation - GeeksforGeeks
13 Jan, 2022 Array#delete_if() : delete_if() is a Array class method which deletes the arrays elements for which the block condition satisfies. Syntax: Array.delete_if() Parameter: block - condition for deleting the elements. Return: array after deleting the elements Code #1 : Example for delete_if() method Ruby # Ruby code for delete_if() method # declaring arraya = [18, 22, 33, 23, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 12, 24, 50, 6] # deleteputs "delete : #{a.delete_if{|x| x < 1}}\n\n" # deleteputs "delete : #{b.delete_if{|b| b==1}}\n\n" Output : delete : [18, 22, 33, 23, 5, 6] delete : [4, 88, 9] Code #2 : Example for delete_if() method Ruby # Ruby code for delete_if() method # declaring arraya = ["abc", "geeks", "dog"] # declaring arrayb = ["cow", "1", "dog"] # deleteputs "delete : #{a.delete_if{|x| x != "dog"}}\n\n" # deleteputs "delete : #{b.delete_if{|b| b=="1"}}\n\n" Output : delete : ["dog"] delete : ["cow", "dog"] surinderdawra388 Ruby Array-class Ruby Collections Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ruby | Array count() operation Include v/s Extend in Ruby Global Variable in Ruby Ruby | Hash delete() function Ruby | Types of Variables Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | Data Types Ruby | Numeric round() function
[ { "code": null, "e": 25001, "s": 24973, "text": "\n13 Jan, 2022" }, { "code": null, "e": 25133, "s": 25001, "text": "Array#delete_if() : delete_if() is a Array class method which deletes the arrays elements for which the block condition satisfies. " }, { "code": null, "e": 25262, "s": 25133, "text": "Syntax: Array.delete_if()\n\nParameter: block - condition for deleting the elements.\n\nReturn: array after deleting the elements" }, { "code": null, "e": 25304, "s": 25262, "text": "Code #1 : Example for delete_if() method " }, { "code": null, "e": 25309, "s": 25304, "text": "Ruby" }, { "code": "# Ruby code for delete_if() method # declaring arraya = [18, 22, 33, 23, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 12, 24, 50, 6] # deleteputs \"delete : #{a.delete_if{|x| x < 1}}\\n\\n\" # deleteputs \"delete : #{b.delete_if{|b| b==1}}\\n\\n\"", "e": 25591, "s": 25309, "text": null }, { "code": null, "e": 25601, "s": 25591, "text": "Output : " }, { "code": null, "e": 25655, "s": 25601, "text": "delete : [18, 22, 33, 23, 5, 6]\n\ndelete : [4, 88, 9] " }, { "code": null, "e": 25698, "s": 25655, "text": "Code #2 : Example for delete_if() method " }, { "code": null, "e": 25703, "s": 25698, "text": "Ruby" }, { "code": "# Ruby code for delete_if() method # declaring arraya = [\"abc\", \"geeks\", \"dog\"] # declaring arrayb = [\"cow\", \"1\", \"dog\"] # deleteputs \"delete : #{a.delete_if{|x| x != \"dog\"}}\\n\\n\" # deleteputs \"delete : #{b.delete_if{|b| b==\"1\"}}\\n\\n\"", "e": 25949, "s": 25703, "text": null }, { "code": null, "e": 25959, "s": 25949, "text": "Output : " }, { "code": null, "e": 26001, "s": 25959, "text": "delete : [\"dog\"]\n\ndelete : [\"cow\", \"dog\"]" }, { "code": null, "e": 26020, "s": 26003, "text": "surinderdawra388" }, { "code": null, "e": 26037, "s": 26020, "text": "Ruby Array-class" }, { "code": null, "e": 26054, "s": 26037, "text": "Ruby Collections" }, { "code": null, "e": 26067, "s": 26054, "text": "Ruby-Methods" }, { "code": null, "e": 26072, "s": 26067, "text": "Ruby" }, { "code": null, "e": 26170, "s": 26072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26201, "s": 26170, "text": "Ruby | Array count() operation" }, { "code": null, "e": 26228, "s": 26201, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 26252, "s": 26228, "text": "Global Variable in Ruby" }, { "code": null, "e": 26282, "s": 26252, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 26308, "s": 26282, "text": "Ruby | Types of Variables" }, { "code": null, "e": 26351, "s": 26308, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 26373, "s": 26351, "text": "Ruby | Case Statement" }, { "code": null, "e": 26404, "s": 26373, "text": "Ruby | Array select() function" }, { "code": null, "e": 26422, "s": 26404, "text": "Ruby | Data Types" } ]
Check if the elements of stack are pairwise sorted - GeeksforGeeks
03 Aug, 2021 Given a stack of integers, write a function pairWiseSorted() that checks whether numbers in the stack are pairwise sorted or not. The pairs must be increasing, and if the stack has an odd number of elements, the element at the top is left out of a pair. The function should retain the original stack content. Only following standard operations are allowed on the stack. push(X): Enter a element X on top of stack.pop(): Removes top element of the stack.empty(): To check if stack is empty. push(X): Enter a element X on top of stack. pop(): Removes top element of the stack. empty(): To check if stack is empty. Examples: Input: 4, 5, 6, 7, 8, 9 Output: Yes Input: 4, 9, 2, 1, 10, 8 Output: No Approach: The idea is to use another stack. Create an auxiliary stack aux. Transfer contents of given stack to aux. Traverse aux. While traversing fetch top two elements and check if they are sorted or not. After checking put these elements back to original stack. Below is the implementation of above approach: C++ Java Python 3 C# Javascript // C++ program to check if successive// pair of numbers in the stack are// sorted or not#include <bits/stdc++.h>using namespace std; // Function to check if elements are// pairwise sorted in stackbool pairWiseConsecutive(stack<int> s){ // Transfer elements of s to aux. stack<int> aux; while (!s.empty()) { aux.push(s.top()); s.pop(); } // Traverse aux and see if // elements are pairwise // sorted or not. We also // need to make sure that original // content is retained. bool result = true; while (!aux.empty()) { // Fetch current top two // elements of aux and check // if they are sorted. int x = aux.top(); aux.pop(); int y = aux.top(); aux.pop(); if (x > y) result = false; // Push the elements to original // stack. s.push(x); s.push(y); } if (aux.size() == 1) s.push(aux.top()); return result;} // Driver programint main(){ stack<int> s; s.push(4); s.push(5); s.push(-3); s.push(-2); s.push(10); s.push(11); s.push(5); s.push(6); // s.push(20); if (pairWiseConsecutive(s)) cout << "Yes" << endl; else cout << "No" << endl; cout << "Stack content (from top)" " after function call\n"; while (s.empty() == false) { cout << s.top() << " "; s.pop(); } return 0;} // Java program to check if successive// pair of numbers in the stack are// sorted or notimport java.util.Stack; class GFG { // Function to check if elements are// pairwise sorted in stack static boolean pairWiseConsecutive(Stack<Integer> s) { // Transfer elements of s to aux. Stack<Integer> aux = new Stack<>(); while (!s.empty()) { aux.push(s.peek()); s.pop(); } // Traverse aux and see if // elements are pairwise // sorted or not. We also // need to make sure that original // content is retained. boolean result = true; while (!aux.empty()) { // Fetch current top two // elements of aux and check // if they are sorted. int x = aux.peek(); aux.pop(); int y = aux.peek(); aux.pop(); if (x > y) { result = false; } // Push the elements to original // stack. s.push(x); s.push(y); } if (aux.size() == 1) { s.push(aux.peek()); } return result; } // Driver program public static void main(String[] args) { Stack<Integer> s = new Stack<>(); s.push(4); s.push(5); s.push(-3); s.push(-2); s.push(10); s.push(11); s.push(5); s.push(6); // s.push(20); if (pairWiseConsecutive(s)) { System.out.println("Yes"); } else { System.out.println("No"); } System.out.println("Stack content (from top)" + " after function call"); while (s.empty() == false) { System.out.print(s.peek() + " "); s.pop(); } } } # Python program to check if successive# pair of numbers in the stack are# sorted or not # using deque as stackfrom collections import deque # Function to check if elements are# pairwise sorted in stackdef pairWiseConsecutive(s): # Transfer elements of s to aux. aux = deque() while len(s) > 0: aux.append(s.pop()) # Traverse aux and see if # elements are pairwise # sorted or not. We also # need to make sure that original # content is retained. result = True while len(aux) != 0: # Fetch current top two # elements of aux and check # if they are sorted. x = aux.pop() y = aux.pop() if x > y: result = False # Push the elements to original # stack. s.append(x) s.append(y) if len(aux) == 1: s.append(aux.pop()) return result # Driver Codeif __name__ == "__main__": s = deque() s.append(4) s.append(5) s.append(-3) s.append(-2) s.append(10) s.append(11) s.append(5) s.append(6) if pairWiseConsecutive(s): print("Yes") else: print("No") print("Stack content (from top) after function call") while len(s) > 0: print(s.pop(), end=" ") # This code is contributed by# sanjeev2552 // C# program to check if successive// pair of numbers in the stack areusing System;using System.Collections.Generic;public class GFG{ // Function to check if elements are// pairwise sorted in stack static bool pairWiseConsecutive(Stack<int> s) { // Transfer elements of s to aux. Stack<int> aux = new Stack<int>(); while (!(s.Count==0)) { aux.Push(s.Peek()); s.Pop(); } // Traverse aux and see if // elements are pairwise // sorted or not. We also // need to make sure that original // content is retained. bool result = true; while (!(aux.Count==0)) { // Fetch current top two // elements of aux and check // if they are sorted. int x = aux.Peek(); aux.Pop(); int y = aux.Peek(); aux.Pop(); if (x > y) { result = false; } // Push the elements to original // stack. s.Push(x); s.Push(y); } if (aux.Count == 1) { s.Push(aux.Peek()); } return result; } // Driver program public static void Main() { Stack<int> s = new Stack<int>(); s.Push(4); s.Push(5); s.Push(-3); s.Push(-2); s.Push(10); s.Push(11); s.Push(5); s.Push(6); // s.push(20); if (pairWiseConsecutive(s)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } Console.WriteLine("Stack content (from top)" + " after function call"); while (!(s.Count == 0)) { Console.Write(s.Peek() + " "); s.Pop(); } } } <script> // JavaScript program to check if successive// pair of numbers in the stack are// sorted or not // Function to check if elements are// pairwise sorted in stackfunction pairWiseConsecutive(s){ // Transfer elements of s to aux. var aux = []; while (s.length!=0) { aux.push(s[s.length-1]); s.pop(); } // Traverse aux and see if // elements are pairwise // sorted or not. We also // need to make sure that original // content is retained. var result = true; while (aux.length!=0) { // Fetch current top two // elements of aux and check // if they are sorted. var x = aux[aux.length-1]; aux.pop(); var y = aux[aux.length-1]; aux.pop(); if (x > y) result = false; // Push the elements to original // stack. s.push(x); s.push(y); } if (aux.length == 1) s.push(aux[aux.length-1]); return result;} // Driver programvar s = [];s.push(4);s.push(5);s.push(-3);s.push(-2);s.push(10);s.push(11);s.push(5);s.push(6);// s.push(20);if (pairWiseConsecutive(s)) document.write( "Yes" + "<br>");else document.write( "No" + "<br>");document.write( "Stack content (from top)"+ " after function call<br>");while (s.length!=0) { document.write( s[s.length-1] + " "); s.pop();} </script> Yes Stack content (from top) after function call 6 5 11 10 -2 -3 5 4 Time Complexity: O(N)Auxiliary Space: O(N) princiraj1992 sanjeev2552 rutvik_56 pankajsharmagfg cpp-stack Technical Scripter 2018 Data Structures Stack Data Structures Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Start Learning DSA? Introduction to Tree Data Structure Program to implement Singly Linked List in C++ using class Hash Functions and list/types of Hash functions Shortest path in a directed graph by Dijkstra’s algorithm Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Check for Balanced Brackets in an expression (well-formedness) using Stack Stack | Set 2 (Infix to Postfix)
[ { "code": null, "e": 26299, "s": 26271, "text": "\n03 Aug, 2021" }, { "code": null, "e": 26609, "s": 26299, "text": "Given a stack of integers, write a function pairWiseSorted() that checks whether numbers in the stack are pairwise sorted or not. The pairs must be increasing, and if the stack has an odd number of elements, the element at the top is left out of a pair. The function should retain the original stack content. " }, { "code": null, "e": 26672, "s": 26609, "text": "Only following standard operations are allowed on the stack. " }, { "code": null, "e": 26792, "s": 26672, "text": "push(X): Enter a element X on top of stack.pop(): Removes top element of the stack.empty(): To check if stack is empty." }, { "code": null, "e": 26836, "s": 26792, "text": "push(X): Enter a element X on top of stack." }, { "code": null, "e": 26877, "s": 26836, "text": "pop(): Removes top element of the stack." }, { "code": null, "e": 26914, "s": 26877, "text": "empty(): To check if stack is empty." }, { "code": null, "e": 26926, "s": 26914, "text": "Examples: " }, { "code": null, "e": 26999, "s": 26926, "text": "Input: 4, 5, 6, 7, 8, 9\nOutput: Yes\n\nInput: 4, 9, 2, 1, 10, 8\nOutput: No" }, { "code": null, "e": 27047, "s": 27001, "text": "Approach: The idea is to use another stack. " }, { "code": null, "e": 27078, "s": 27047, "text": "Create an auxiliary stack aux." }, { "code": null, "e": 27119, "s": 27078, "text": "Transfer contents of given stack to aux." }, { "code": null, "e": 27210, "s": 27119, "text": "Traverse aux. While traversing fetch top two elements and check if they are sorted or not." }, { "code": null, "e": 27268, "s": 27210, "text": "After checking put these elements back to original stack." }, { "code": null, "e": 27317, "s": 27268, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 27321, "s": 27317, "text": "C++" }, { "code": null, "e": 27326, "s": 27321, "text": "Java" }, { "code": null, "e": 27335, "s": 27326, "text": "Python 3" }, { "code": null, "e": 27338, "s": 27335, "text": "C#" }, { "code": null, "e": 27349, "s": 27338, "text": "Javascript" }, { "code": "// C++ program to check if successive// pair of numbers in the stack are// sorted or not#include <bits/stdc++.h>using namespace std; // Function to check if elements are// pairwise sorted in stackbool pairWiseConsecutive(stack<int> s){ // Transfer elements of s to aux. stack<int> aux; while (!s.empty()) { aux.push(s.top()); s.pop(); } // Traverse aux and see if // elements are pairwise // sorted or not. We also // need to make sure that original // content is retained. bool result = true; while (!aux.empty()) { // Fetch current top two // elements of aux and check // if they are sorted. int x = aux.top(); aux.pop(); int y = aux.top(); aux.pop(); if (x > y) result = false; // Push the elements to original // stack. s.push(x); s.push(y); } if (aux.size() == 1) s.push(aux.top()); return result;} // Driver programint main(){ stack<int> s; s.push(4); s.push(5); s.push(-3); s.push(-2); s.push(10); s.push(11); s.push(5); s.push(6); // s.push(20); if (pairWiseConsecutive(s)) cout << \"Yes\" << endl; else cout << \"No\" << endl; cout << \"Stack content (from top)\" \" after function call\\n\"; while (s.empty() == false) { cout << s.top() << \" \"; s.pop(); } return 0;}", "e": 28770, "s": 27349, "text": null }, { "code": "// Java program to check if successive// pair of numbers in the stack are// sorted or notimport java.util.Stack; class GFG { // Function to check if elements are// pairwise sorted in stack static boolean pairWiseConsecutive(Stack<Integer> s) { // Transfer elements of s to aux. Stack<Integer> aux = new Stack<>(); while (!s.empty()) { aux.push(s.peek()); s.pop(); } // Traverse aux and see if // elements are pairwise // sorted or not. We also // need to make sure that original // content is retained. boolean result = true; while (!aux.empty()) { // Fetch current top two // elements of aux and check // if they are sorted. int x = aux.peek(); aux.pop(); int y = aux.peek(); aux.pop(); if (x > y) { result = false; } // Push the elements to original // stack. s.push(x); s.push(y); } if (aux.size() == 1) { s.push(aux.peek()); } return result; } // Driver program public static void main(String[] args) { Stack<Integer> s = new Stack<>(); s.push(4); s.push(5); s.push(-3); s.push(-2); s.push(10); s.push(11); s.push(5); s.push(6); // s.push(20); if (pairWiseConsecutive(s)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } System.out.println(\"Stack content (from top)\" + \" after function call\"); while (s.empty() == false) { System.out.print(s.peek() + \" \"); s.pop(); } } }", "e": 30551, "s": 28770, "text": null }, { "code": "# Python program to check if successive# pair of numbers in the stack are# sorted or not # using deque as stackfrom collections import deque # Function to check if elements are# pairwise sorted in stackdef pairWiseConsecutive(s): # Transfer elements of s to aux. aux = deque() while len(s) > 0: aux.append(s.pop()) # Traverse aux and see if # elements are pairwise # sorted or not. We also # need to make sure that original # content is retained. result = True while len(aux) != 0: # Fetch current top two # elements of aux and check # if they are sorted. x = aux.pop() y = aux.pop() if x > y: result = False # Push the elements to original # stack. s.append(x) s.append(y) if len(aux) == 1: s.append(aux.pop()) return result # Driver Codeif __name__ == \"__main__\": s = deque() s.append(4) s.append(5) s.append(-3) s.append(-2) s.append(10) s.append(11) s.append(5) s.append(6) if pairWiseConsecutive(s): print(\"Yes\") else: print(\"No\") print(\"Stack content (from top) after function call\") while len(s) > 0: print(s.pop(), end=\" \") # This code is contributed by# sanjeev2552", "e": 31826, "s": 30551, "text": null }, { "code": "// C# program to check if successive// pair of numbers in the stack areusing System;using System.Collections.Generic;public class GFG{ // Function to check if elements are// pairwise sorted in stack static bool pairWiseConsecutive(Stack<int> s) { // Transfer elements of s to aux. Stack<int> aux = new Stack<int>(); while (!(s.Count==0)) { aux.Push(s.Peek()); s.Pop(); } // Traverse aux and see if // elements are pairwise // sorted or not. We also // need to make sure that original // content is retained. bool result = true; while (!(aux.Count==0)) { // Fetch current top two // elements of aux and check // if they are sorted. int x = aux.Peek(); aux.Pop(); int y = aux.Peek(); aux.Pop(); if (x > y) { result = false; } // Push the elements to original // stack. s.Push(x); s.Push(y); } if (aux.Count == 1) { s.Push(aux.Peek()); } return result; } // Driver program public static void Main() { Stack<int> s = new Stack<int>(); s.Push(4); s.Push(5); s.Push(-3); s.Push(-2); s.Push(10); s.Push(11); s.Push(5); s.Push(6); // s.push(20); if (pairWiseConsecutive(s)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } Console.WriteLine(\"Stack content (from top)\" + \" after function call\"); while (!(s.Count == 0)) { Console.Write(s.Peek() + \" \"); s.Pop(); } } }", "e": 33588, "s": 31826, "text": null }, { "code": "<script> // JavaScript program to check if successive// pair of numbers in the stack are// sorted or not // Function to check if elements are// pairwise sorted in stackfunction pairWiseConsecutive(s){ // Transfer elements of s to aux. var aux = []; while (s.length!=0) { aux.push(s[s.length-1]); s.pop(); } // Traverse aux and see if // elements are pairwise // sorted or not. We also // need to make sure that original // content is retained. var result = true; while (aux.length!=0) { // Fetch current top two // elements of aux and check // if they are sorted. var x = aux[aux.length-1]; aux.pop(); var y = aux[aux.length-1]; aux.pop(); if (x > y) result = false; // Push the elements to original // stack. s.push(x); s.push(y); } if (aux.length == 1) s.push(aux[aux.length-1]); return result;} // Driver programvar s = [];s.push(4);s.push(5);s.push(-3);s.push(-2);s.push(10);s.push(11);s.push(5);s.push(6);// s.push(20);if (pairWiseConsecutive(s)) document.write( \"Yes\" + \"<br>\");else document.write( \"No\" + \"<br>\");document.write( \"Stack content (from top)\"+ \" after function call<br>\");while (s.length!=0) { document.write( s[s.length-1] + \" \"); s.pop();} </script>", "e": 34944, "s": 33588, "text": null }, { "code": null, "e": 35013, "s": 34944, "text": "Yes\nStack content (from top) after function call\n6 5 11 10 -2 -3 5 4" }, { "code": null, "e": 35059, "s": 35015, "text": "Time Complexity: O(N)Auxiliary Space: O(N) " }, { "code": null, "e": 35073, "s": 35059, "text": "princiraj1992" }, { "code": null, "e": 35085, "s": 35073, "text": "sanjeev2552" }, { "code": null, "e": 35095, "s": 35085, "text": "rutvik_56" }, { "code": null, "e": 35111, "s": 35095, "text": "pankajsharmagfg" }, { "code": null, "e": 35121, "s": 35111, "text": "cpp-stack" }, { "code": null, "e": 35145, "s": 35121, "text": "Technical Scripter 2018" }, { "code": null, "e": 35161, "s": 35145, "text": "Data Structures" }, { "code": null, "e": 35167, "s": 35161, "text": "Stack" }, { "code": null, "e": 35183, "s": 35167, "text": "Data Structures" }, { "code": null, "e": 35189, "s": 35183, "text": "Stack" }, { "code": null, "e": 35287, "s": 35189, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35314, "s": 35287, "text": "How to Start Learning DSA?" }, { "code": null, "e": 35350, "s": 35314, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 35409, "s": 35350, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 35457, "s": 35409, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 35515, "s": 35457, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 35563, "s": 35515, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 35583, "s": 35563, "text": "Stack Class in Java" }, { "code": null, "e": 35599, "s": 35583, "text": "Stack in Python" }, { "code": null, "e": 35674, "s": 35599, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Python | sympy.coeff(x, n) method - GeeksforGeeks
18 Jun, 2019 With the help of sympy.coeff(x, n) method, we are able to find the coefficient of variables in mathematical expressions. Syntax : sympy.coeff(x, n)Return : Return the coefficient of variables. Example #1 :In this example, we can see that by using sympy.coeff(x, n) method, we can find the coefficient of mathematical expression. # import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = x * y + x - 3 + 2 * x**2 - z * x**2 + x**3 # Using sympy.coeff(x, n) methodgfg_exp = gfg_exp.coeff(x, 2) print(gfg_exp) Output : 2 – z Example #2 : # import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = z * x + x - 3 + 2 * x**2 - y * x**2 + y**3 # Using sympy.coeff(x, n) methodgfg_exp = gfg_exp.coeff(y, 1) print(gfg_exp) Output : -x**2 SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26037, "s": 26009, "text": "\n18 Jun, 2019" }, { "code": null, "e": 26158, "s": 26037, "text": "With the help of sympy.coeff(x, n) method, we are able to find the coefficient of variables in mathematical expressions." }, { "code": null, "e": 26230, "s": 26158, "text": "Syntax : sympy.coeff(x, n)Return : Return the coefficient of variables." }, { "code": null, "e": 26366, "s": 26230, "text": "Example #1 :In this example, we can see that by using sympy.coeff(x, n) method, we can find the coefficient of mathematical expression." }, { "code": "# import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = x * y + x - 3 + 2 * x**2 - z * x**2 + x**3 # Using sympy.coeff(x, n) methodgfg_exp = gfg_exp.coeff(x, 2) print(gfg_exp)", "e": 26558, "s": 26366, "text": null }, { "code": null, "e": 26567, "s": 26558, "text": "Output :" }, { "code": null, "e": 26573, "s": 26567, "text": "2 – z" }, { "code": null, "e": 26586, "s": 26573, "text": "Example #2 :" }, { "code": "# import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = z * x + x - 3 + 2 * x**2 - y * x**2 + y**3 # Using sympy.coeff(x, n) methodgfg_exp = gfg_exp.coeff(y, 1) print(gfg_exp)", "e": 26778, "s": 26586, "text": null }, { "code": null, "e": 26787, "s": 26778, "text": "Output :" }, { "code": null, "e": 26793, "s": 26787, "text": "-x**2" }, { "code": null, "e": 26799, "s": 26793, "text": "SymPy" }, { "code": null, "e": 26806, "s": 26799, "text": "Python" }, { "code": null, "e": 26904, "s": 26806, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26922, "s": 26904, "text": "Python Dictionary" }, { "code": null, "e": 26957, "s": 26922, "text": "Read a file line by line in Python" }, { "code": null, "e": 26989, "s": 26957, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27011, "s": 26989, "text": "Enumerate() in Python" }, { "code": null, "e": 27053, "s": 27011, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27083, "s": 27053, "text": "Iterate over a list in Python" }, { "code": null, "e": 27109, "s": 27083, "text": "Python String | replace()" }, { "code": null, "e": 27138, "s": 27109, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27182, "s": 27138, "text": "Reading and Writing to text files in Python" } ]
n'th multiple of a number in Fibonacci Series - GeeksforGeeks
07 Jan, 2022 Given two integers n and k. Find position the n’th multiple of K in the Fibonacci series. Examples : Input : k = 2, n = 3 Output : 9 3'rd multiple of 2 in Fibonacci Series is 34 which appears at position 9. Input : k = 4, n = 5 Output : 30 4'th multiple of 5 in Fibonacci Series is 832040 which appears at position 30. Fibonacci Series(F) : 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040... (neglecting the first 0).A Simple Solution is to traverse Fibonacci numbers starting from first number. While traversing, keep track of counts of multiples of k. Whenever the count becomes n, return the position.An Efficient Solution is based on below interesting property. Fibonacci series is always periodic under modular representation. Below are examples. F (mod 2) = 1,1,0,1,1,0,1,1,0,1,1,0,1,1,0, 1,1,0,1,1,0,1,1,0,1,1,0,1,1,0 Here 0 is repeating at every 3rd index and the cycle repeats at every 3rd index. F (mod 3) = 1,1,2,0,2,2,1,0,1,1,2,0,2,2,1,0 ,1,1,2,0,2,2,1,0,1,1,2,0,2,2 Here 0 is repeating at every 4th index and the cycle repeats at every 8th index. F (mod 4) = 1,1,2,3,1,0,1,1,2,3,1,0,1,1,2,3, 1,0,1,1,2,3,1,0,1,1,2,3,1,0 Here 0 is repeating at every 6th index and the cycle repeats at every 6th index. F (mod 5) = 1,1,2,3,0,3,3,1,4,0,4,4,3,2,0, 2,2,4,1,0,1,1,2,3,0,3,3,1,4,0 Here 0 is repeating at every 5th index and the cycle repeats at every 20th index. F (mod 6) = 1,1,2,3,5,2,1,3,4,1,5,0,5,5,4, 3,1,4,5,3,2,5,1,0,1,1,2,3,5,2 Here 0 is repeating at every 12th index and the cycle repeats at every 24th index. F (mod 7) = 1,1,2,3,5,1,6,0,6,6,5,4,2,6,1, 0,1,1,2,3,5,1,6,0,6,6,5,4,2,6 Here 0 is repeating at every 8th index and the cycle repeats at every 16th index. F (mod 8) = 1,1,2,3,5,0,5,5,2,7,1,0,1,1,2, 3,5,0,5,5,2,7,1,0,1,1,2,3,5,0 Here 0 is repeating at every 6th index and the cycle repeats at every 12th index. F (mod 9) = 1,1,2,3,5,8,4,3,7,1,8,0,8,8,7, 6,4,1,5,6,2,8,1,0,1,1,2,3,5,8 Here 0 is repeating at every 12th index and the cycle repeats at every 24th index. F (mod 10) = 1,1,2,3,5,8,3,1,4,5,9,4,3,7,0, 7,7,4,1,5,6,1,7,8,5,3,8,1,9,0. Here 0 is repeating at every 15th index and the cycle repeats at every 60th index. Why is Fibonacci Series Periodic under Modulo? Under modular representation, we know that each Fibonacci number will be represented as some residue 0 ? F (mod m) < m. Thus, there are only m possible values for any given F (mod m) and hence m*m = m^2 possible pairs of consecutive terms within the sequence. Since m^2 is finite, we know that some pair of terms must eventually repeat itself. Also, as any pair of terms in the Fibonacci sequence determines the rest of the sequence, we see that the Fibonacci series modulo m must repeat itself at some point, and thus must be periodic. Source : https://www.whitman.edu/Documents/Academics/Mathematics/clancy.pdfBased on above fact, we can quickly find position of n’th multiple of K by simply finding first multiple. If position of first multiple is i, we return position as n*i.Below is the implementation : C++ Java Python3 C# PHP Javascript // C++ program to find position// of n'th multiple of a number// k in Fibonacci Series# include <bits/stdc++.h>using namespace std; const int MAX = 1000; // Returns position of n'th multiple// of k in Fibonacci Seriesint findPosition(int k, int n){ // Iterate through all // fibonacci numbers unsigned long long int f1 = 0, f2 = 1, f3; for (int i = 2; i <= MAX; i++) { f3 = f1 + f2; f1 = f2; f2 = f3; // Found first multiple of // k at position i if (f2 % k == 0) // n'th multiple would be at // position n*i using Periodic // property of Fibonacci numbers // under modulo. return n * i; }} // Driver Codeint main (){ int n = 5, k = 4; cout << "Position of n'th multiple of k" <<" in Fibonacci Series is " << findPosition(k, n) << endl; return 0;} // Java Program to find position// of n'th multiple of a number// k in Fibonacci Series class GFG{ public static int findPosition(int k, int n) { long f1 = 0, f2 = 1, f3; int i = 2; while(i != 0) { f3 = f1 + f2; f1 = f2; f2 = f3; if(f2 % k == 0) { return n * i; } i++; } return 0; } // Driver Code public static void main(String[] args) { // Multiple no. int n = 5; // Number of whose multiple // we are finding int k = 4; System.out.print("Position of n'th multiple" + " of k in Fibonacci Series is "); System.out.println(findPosition(k, n)); }} // This code is contributed// by Mohit Gupta_OMG # Python Program to find position# of n'th multiple of a number k# in Fibonacci Series def findPosition(k, n): f1 = 0 f2 = 1 i = 2; while i != 0: f3 = f1 + f2; f1 = f2; f2 = f3; if f2 % k == 0: return n * i i += 1 return # Multiple no.n = 5;# Number of whose multiple# we are findingk = 4; print("Position of n'th multiple of k in" "Fibonacci Series is", findPosition(k, n)); # This code is contributed# by Mohit Gupta_OMG // C# Program to find position of// n'th multiple of a number k in// Fibonacci Seriesusing System; class GFG{ static int findPosition(int k, int n) { long f1 = 0, f2 = 1, f3; int i = 2; while(i!=0) { f3 = f1 + f2; f1 = f2; f2 = f3; if(f2 % k == 0) { return n * i; } i++; } return 0; } // Driver code public static void Main() { // Multiple no. int n = 5; // Number of whose multiple // we are finding int k = 4; Console.Write("Position of n'th multiple " + "of k in Fibonacci Series is "); // Function calling Console.WriteLine(findPosition(k, n)); }} // This code is contributed by Sam007 <?php// PHP program to find position// of n'th multiple of a number// k in Fibonacci Series$MAX = 1000; // Returns position of n'th multiple// of k in Fibonacci Seriesfunction findPosition($k, $n){ global $MAX; // Iterate through all // fibonacci numbers $f1 = 0; $f2 = 1; $f3; for ($i = 2; $i <= $MAX; $i++) { $f3 = $f1 + $f2; $f1 = $f2; $f2 = $f3; // Found first multiple of // k at position i if ($f2 % $k == 0) // n'th multiple would be at // position n*i using Periodic // property of Fibonacci numbers // under modulo return $n * $i; }} // Driver Code$n = 5; $k = 4;echo("Position of n'th multiple of k" . " in Fibonacci Series is " . findPosition($k, $n)); // This code is contributed by Ajit.?> <script> // Javascript program to find position// of n'th multiple of a number// k in Fibonacci Serieslet MAX = 1000; // Returns position of n'th multiple// of k in Fibonacci Seriesfunction findPosition(k, n){ // Iterate through all // fibonacci numbers let f1 = 0; let f2 = 1; let f3; for (let i = 2; i <= MAX; i++) { f3 = f1 + f2; f1 = f2; f2 = f3; // Found first multiple of // k at position i if (f2 % k == 0) // n'th multiple would be at // position n*i using Periodic // property of Fibonacci numbers // under modulo return n * i; }} // Driver Codelet n = 5;let k = 4;document.write("Position of n'th multiple of k" + " in Fibonacci Series is " + findPosition(k, n)); // This code is contributed by _saurabh_jaiswal </script> Output : Position of n'th multiple of k in Fibonacci Series is 30 This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 jit_t omkarkhedkar _saurabh_jaiswal simmytarika5 surindertarika1234 sagar0719kumar Fibonacci Mathematical Mathematical Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Check if a number is Palindrome Program to multiply two matrices Merge two sorted arrays with O(1) extra space Generate all permutation of a set in Python Count ways to reach the n'th stair
[ { "code": null, "e": 25963, "s": 25935, "text": "\n07 Jan, 2022" }, { "code": null, "e": 26054, "s": 25963, "text": "Given two integers n and k. Find position the n’th multiple of K in the Fibonacci series. " }, { "code": null, "e": 26067, "s": 26054, "text": "Examples : " }, { "code": null, "e": 26290, "s": 26067, "text": "Input : k = 2, n = 3\nOutput : 9\n3'rd multiple of 2 in Fibonacci Series is 34 \nwhich appears at position 9.\n\nInput : k = 4, n = 5 \nOutput : 30\n4'th multiple of 5 in Fibonacci Series is 832040 \nwhich appears at position 30." }, { "code": null, "e": 26840, "s": 26292, "text": "Fibonacci Series(F) : 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040... (neglecting the first 0).A Simple Solution is to traverse Fibonacci numbers starting from first number. While traversing, keep track of counts of multiples of k. Whenever the count becomes n, return the position.An Efficient Solution is based on below interesting property. Fibonacci series is always periodic under modular representation. Below are examples. " }, { "code": null, "e": 28366, "s": 26840, "text": "F (mod 2) = 1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,\n 1,1,0,1,1,0,1,1,0,1,1,0,1,1,0 \nHere 0 is repeating at every 3rd index and \nthe cycle repeats at every 3rd index. \n\nF (mod 3) = 1,1,2,0,2,2,1,0,1,1,2,0,2,2,1,0\n ,1,1,2,0,2,2,1,0,1,1,2,0,2,2\nHere 0 is repeating at every 4th index and \nthe cycle repeats at every 8th index.\n\nF (mod 4) = 1,1,2,3,1,0,1,1,2,3,1,0,1,1,2,3,\n 1,0,1,1,2,3,1,0,1,1,2,3,1,0 \nHere 0 is repeating at every 6th index and \nthe cycle repeats at every 6th index.\n\nF (mod 5) = 1,1,2,3,0,3,3,1,4,0,4,4,3,2,0,\n 2,2,4,1,0,1,1,2,3,0,3,3,1,4,0\nHere 0 is repeating at every 5th index and\nthe cycle repeats at every 20th index.\n\nF (mod 6) = 1,1,2,3,5,2,1,3,4,1,5,0,5,5,4,\n 3,1,4,5,3,2,5,1,0,1,1,2,3,5,2\nHere 0 is repeating at every 12th index and \nthe cycle repeats at every 24th index.\n\nF (mod 7) = 1,1,2,3,5,1,6,0,6,6,5,4,2,6,1,\n 0,1,1,2,3,5,1,6,0,6,6,5,4,2,6 \nHere 0 is repeating at every 8th index and \nthe cycle repeats at every 16th index.\n\nF (mod 8) = 1,1,2,3,5,0,5,5,2,7,1,0,1,1,2,\n 3,5,0,5,5,2,7,1,0,1,1,2,3,5,0 \nHere 0 is repeating at every 6th index and \nthe cycle repeats at every 12th index.\n\nF (mod 9) = 1,1,2,3,5,8,4,3,7,1,8,0,8,8,7,\n 6,4,1,5,6,2,8,1,0,1,1,2,3,5,8 \nHere 0 is repeating at every 12th index and \nthe cycle repeats at every 24th index.\n\nF (mod 10) = 1,1,2,3,5,8,3,1,4,5,9,4,3,7,0,\n 7,7,4,1,5,6,1,7,8,5,3,8,1,9,0.\nHere 0 is repeating at every 15th index and\nthe cycle repeats at every 60th index." }, { "code": null, "e": 29224, "s": 28366, "text": "Why is Fibonacci Series Periodic under Modulo? Under modular representation, we know that each Fibonacci number will be represented as some residue 0 ? F (mod m) < m. Thus, there are only m possible values for any given F (mod m) and hence m*m = m^2 possible pairs of consecutive terms within the sequence. Since m^2 is finite, we know that some pair of terms must eventually repeat itself. Also, as any pair of terms in the Fibonacci sequence determines the rest of the sequence, we see that the Fibonacci series modulo m must repeat itself at some point, and thus must be periodic. Source : https://www.whitman.edu/Documents/Academics/Mathematics/clancy.pdfBased on above fact, we can quickly find position of n’th multiple of K by simply finding first multiple. If position of first multiple is i, we return position as n*i.Below is the implementation : " }, { "code": null, "e": 29228, "s": 29224, "text": "C++" }, { "code": null, "e": 29233, "s": 29228, "text": "Java" }, { "code": null, "e": 29241, "s": 29233, "text": "Python3" }, { "code": null, "e": 29244, "s": 29241, "text": "C#" }, { "code": null, "e": 29248, "s": 29244, "text": "PHP" }, { "code": null, "e": 29259, "s": 29248, "text": "Javascript" }, { "code": "// C++ program to find position// of n'th multiple of a number// k in Fibonacci Series# include <bits/stdc++.h>using namespace std; const int MAX = 1000; // Returns position of n'th multiple// of k in Fibonacci Seriesint findPosition(int k, int n){ // Iterate through all // fibonacci numbers unsigned long long int f1 = 0, f2 = 1, f3; for (int i = 2; i <= MAX; i++) { f3 = f1 + f2; f1 = f2; f2 = f3; // Found first multiple of // k at position i if (f2 % k == 0) // n'th multiple would be at // position n*i using Periodic // property of Fibonacci numbers // under modulo. return n * i; }} // Driver Codeint main (){ int n = 5, k = 4; cout << \"Position of n'th multiple of k\" <<\" in Fibonacci Series is \" << findPosition(k, n) << endl; return 0;}", "e": 30179, "s": 29259, "text": null }, { "code": "// Java Program to find position// of n'th multiple of a number// k in Fibonacci Series class GFG{ public static int findPosition(int k, int n) { long f1 = 0, f2 = 1, f3; int i = 2; while(i != 0) { f3 = f1 + f2; f1 = f2; f2 = f3; if(f2 % k == 0) { return n * i; } i++; } return 0; } // Driver Code public static void main(String[] args) { // Multiple no. int n = 5; // Number of whose multiple // we are finding int k = 4; System.out.print(\"Position of n'th multiple\" + \" of k in Fibonacci Series is \"); System.out.println(findPosition(k, n)); }} // This code is contributed// by Mohit Gupta_OMG", "e": 31040, "s": 30179, "text": null }, { "code": "# Python Program to find position# of n'th multiple of a number k# in Fibonacci Series def findPosition(k, n): f1 = 0 f2 = 1 i = 2; while i != 0: f3 = f1 + f2; f1 = f2; f2 = f3; if f2 % k == 0: return n * i i += 1 return # Multiple no.n = 5;# Number of whose multiple# we are findingk = 4; print(\"Position of n'th multiple of k in\" \"Fibonacci Series is\", findPosition(k, n)); # This code is contributed# by Mohit Gupta_OMG", "e": 31541, "s": 31040, "text": null }, { "code": "// C# Program to find position of// n'th multiple of a number k in// Fibonacci Seriesusing System; class GFG{ static int findPosition(int k, int n) { long f1 = 0, f2 = 1, f3; int i = 2; while(i!=0) { f3 = f1 + f2; f1 = f2; f2 = f3; if(f2 % k == 0) { return n * i; } i++; } return 0; } // Driver code public static void Main() { // Multiple no. int n = 5; // Number of whose multiple // we are finding int k = 4; Console.Write(\"Position of n'th multiple \" + \"of k in Fibonacci Series is \"); // Function calling Console.WriteLine(findPosition(k, n)); }} // This code is contributed by Sam007", "e": 32381, "s": 31541, "text": null }, { "code": "<?php// PHP program to find position// of n'th multiple of a number// k in Fibonacci Series$MAX = 1000; // Returns position of n'th multiple// of k in Fibonacci Seriesfunction findPosition($k, $n){ global $MAX; // Iterate through all // fibonacci numbers $f1 = 0; $f2 = 1; $f3; for ($i = 2; $i <= $MAX; $i++) { $f3 = $f1 + $f2; $f1 = $f2; $f2 = $f3; // Found first multiple of // k at position i if ($f2 % $k == 0) // n'th multiple would be at // position n*i using Periodic // property of Fibonacci numbers // under modulo return $n * $i; }} // Driver Code$n = 5; $k = 4;echo(\"Position of n'th multiple of k\" . \" in Fibonacci Series is \" . findPosition($k, $n)); // This code is contributed by Ajit.?>", "e": 33215, "s": 32381, "text": null }, { "code": "<script> // Javascript program to find position// of n'th multiple of a number// k in Fibonacci Serieslet MAX = 1000; // Returns position of n'th multiple// of k in Fibonacci Seriesfunction findPosition(k, n){ // Iterate through all // fibonacci numbers let f1 = 0; let f2 = 1; let f3; for (let i = 2; i <= MAX; i++) { f3 = f1 + f2; f1 = f2; f2 = f3; // Found first multiple of // k at position i if (f2 % k == 0) // n'th multiple would be at // position n*i using Periodic // property of Fibonacci numbers // under modulo return n * i; }} // Driver Codelet n = 5;let k = 4;document.write(\"Position of n'th multiple of k\" + \" in Fibonacci Series is \" + findPosition(k, n)); // This code is contributed by _saurabh_jaiswal </script>", "e": 34082, "s": 33215, "text": null }, { "code": null, "e": 34092, "s": 34082, "text": "Output : " }, { "code": null, "e": 34149, "s": 34092, "text": "Position of n'th multiple of k in Fibonacci Series is 30" }, { "code": null, "e": 34541, "s": 34149, "text": "This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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": 34548, "s": 34541, "text": "Sam007" }, { "code": null, "e": 34554, "s": 34548, "text": "jit_t" }, { "code": null, "e": 34567, "s": 34554, "text": "omkarkhedkar" }, { "code": null, "e": 34584, "s": 34567, "text": "_saurabh_jaiswal" }, { "code": null, "e": 34597, "s": 34584, "text": "simmytarika5" }, { "code": null, "e": 34616, "s": 34597, "text": "surindertarika1234" }, { "code": null, "e": 34631, "s": 34616, "text": "sagar0719kumar" }, { "code": null, "e": 34641, "s": 34631, "text": "Fibonacci" }, { "code": null, "e": 34654, "s": 34641, "text": "Mathematical" }, { "code": null, "e": 34667, "s": 34654, "text": "Mathematical" }, { "code": null, "e": 34677, "s": 34667, "text": "Fibonacci" }, { "code": null, "e": 34775, "s": 34677, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34819, "s": 34775, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 34861, "s": 34819, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 34892, "s": 34861, "text": "Modular multiplicative inverse" }, { "code": null, "e": 34963, "s": 34892, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 34988, "s": 34963, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 35020, "s": 34988, "text": "Check if a number is Palindrome" }, { "code": null, "e": 35053, "s": 35020, "text": "Program to multiply two matrices" }, { "code": null, "e": 35099, "s": 35053, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 35143, "s": 35099, "text": "Generate all permutation of a set in Python" } ]
Create Directory or Folder with C/C++ Program - GeeksforGeeks
31 May, 2020 Problem: Write a C/C++ program to create a folder in a specific directory path. This task can be accomplished by using the mkdir() function. Directories are created with this function. (There is also a shell command mkdir which does the same thing). The mkdir() function creates a new, empty directory with name filename. // mkdir() function int mkdir (char *filename) Note: A return value of 0 indicates successful completion, and -1 indicates failure. Program to create a directory in Windows using Turbo C compiler:// C program to create a folder#include <conio.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h> void main(){ int check; char* dirname = "geeskforgeeks"; clrscr(); check = mkdir(dirname,0777); // check if directory is created or not if (!check) printf("Directory created\n"); else { printf("Unable to create directory\n"); exit(1); } getch(); system("dir"); getch();}Output:Directory created. a.out geeskforgeeks main.c // C program to create a folder#include <conio.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h> void main(){ int check; char* dirname = "geeskforgeeks"; clrscr(); check = mkdir(dirname,0777); // check if directory is created or not if (!check) printf("Directory created\n"); else { printf("Unable to create directory\n"); exit(1); } getch(); system("dir"); getch();} Output: Directory created. a.out geeskforgeeks main.c Program to create a directory in Linux/Unix using GCC/G++ compiler:// C++ program to create a directory in Linux#include <bits/stdc++.h>#include <iostream>#include <sys/stat.h>#include <sys/types.h>using namespace std; int main() { // Creating a directory if (mkdir("geeksforgeeks", 0777) == -1) cerr << "Error : " << strerror(errno) << endl; else cout << "Directory created";}Output:Directory created. // C++ program to create a directory in Linux#include <bits/stdc++.h>#include <iostream>#include <sys/stat.h>#include <sys/types.h>using namespace std; int main() { // Creating a directory if (mkdir("geeksforgeeks", 0777) == -1) cerr << "Error : " << strerror(errno) << endl; else cout << "Directory created";} Output: Directory created. Note: Above source codes would not run on online IDEs as the program requires the directory path in the system itself. This article is contributed by Rishav Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. santoshbommanalli C Programs C++ Programs Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File How to Append a Character to a String in C C program to sort an array in ascending order time() function in C C Program to Swap two Numbers C++ Program for QuickSort Sorting a Map by value in C++ STL Shallow Copy and Deep Copy in C++ C++ program for hashing with chaining delete keyword in C++
[ { "code": null, "e": 25688, "s": 25660, "text": "\n31 May, 2020" }, { "code": null, "e": 25768, "s": 25688, "text": "Problem: Write a C/C++ program to create a folder in a specific directory path." }, { "code": null, "e": 26010, "s": 25768, "text": "This task can be accomplished by using the mkdir() function. Directories are created with this function. (There is also a shell command mkdir which does the same thing). The mkdir() function creates a new, empty directory with name filename." }, { "code": null, "e": 26058, "s": 26010, "text": "// mkdir() function\nint mkdir (char *filename)\n" }, { "code": null, "e": 26143, "s": 26058, "text": "Note: A return value of 0 indicates successful completion, and -1 indicates failure." }, { "code": null, "e": 26746, "s": 26143, "text": "Program to create a directory in Windows using Turbo C compiler:// C program to create a folder#include <conio.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h> void main(){ int check; char* dirname = \"geeskforgeeks\"; clrscr(); check = mkdir(dirname,0777); // check if directory is created or not if (!check) printf(\"Directory created\\n\"); else { printf(\"Unable to create directory\\n\"); exit(1); } getch(); system(\"dir\"); getch();}Output:Directory created.\na.out geeskforgeeks main.c \n" }, { "code": "// C program to create a folder#include <conio.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h> void main(){ int check; char* dirname = \"geeskforgeeks\"; clrscr(); check = mkdir(dirname,0777); // check if directory is created or not if (!check) printf(\"Directory created\\n\"); else { printf(\"Unable to create directory\\n\"); exit(1); } getch(); system(\"dir\"); getch();}", "e": 27229, "s": 26746, "text": null }, { "code": null, "e": 27237, "s": 27229, "text": "Output:" }, { "code": null, "e": 27287, "s": 27237, "text": "Directory created.\na.out geeskforgeeks main.c \n" }, { "code": null, "e": 27722, "s": 27287, "text": "Program to create a directory in Linux/Unix using GCC/G++ compiler:// C++ program to create a directory in Linux#include <bits/stdc++.h>#include <iostream>#include <sys/stat.h>#include <sys/types.h>using namespace std; int main() { // Creating a directory if (mkdir(\"geeksforgeeks\", 0777) == -1) cerr << \"Error : \" << strerror(errno) << endl; else cout << \"Directory created\";}Output:Directory created.\n\n" }, { "code": "// C++ program to create a directory in Linux#include <bits/stdc++.h>#include <iostream>#include <sys/stat.h>#include <sys/types.h>using namespace std; int main() { // Creating a directory if (mkdir(\"geeksforgeeks\", 0777) == -1) cerr << \"Error : \" << strerror(errno) << endl; else cout << \"Directory created\";}", "e": 28063, "s": 27722, "text": null }, { "code": null, "e": 28071, "s": 28063, "text": "Output:" }, { "code": null, "e": 28092, "s": 28071, "text": "Directory created.\n\n" }, { "code": null, "e": 28211, "s": 28092, "text": "Note: Above source codes would not run on online IDEs as the program requires the directory path in the system itself." }, { "code": null, "e": 28509, "s": 28211, "text": "This article is contributed by Rishav Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28634, "s": 28509, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28652, "s": 28634, "text": "santoshbommanalli" }, { "code": null, "e": 28663, "s": 28652, "text": "C Programs" }, { "code": null, "e": 28676, "s": 28663, "text": "C++ Programs" }, { "code": null, "e": 28687, "s": 28676, "text": "Linux-Unix" }, { "code": null, "e": 28785, "s": 28687, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28826, "s": 28785, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28869, "s": 28826, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 28915, "s": 28869, "text": "C program to sort an array in ascending order" }, { "code": null, "e": 28936, "s": 28915, "text": "time() function in C" }, { "code": null, "e": 28966, "s": 28936, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 28992, "s": 28966, "text": "C++ Program for QuickSort" }, { "code": null, "e": 29026, "s": 28992, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 29060, "s": 29026, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 29098, "s": 29060, "text": "C++ program for hashing with chaining" } ]
CSS | -moz-outline-radius property - GeeksforGeeks
23 Jan, 2020 The -moz-outline-radius property is used to specify the radius of an outline. It is used to give rounded corners to outlines. This property is only supported in Firefox. Syntax: -moz-outline-radius: <length> {1-4} | <percentage> (1-4} | initial | inherit Property Values: length: This is used to set the outline radius in length units. The default value of this property is 0.The value can be specified in 4 formats.When one value is specified then the radius would be applied to all the corners of the element.When two values are specified, then the first applies to the top-left and bottom-right corners and the second value applies to the top-left and bottom-right corners.When three values are specified, the first one applies to the top-left corner, the second one applies to the top-right and bottom-left corners and the third one applies to the bottom-right corner.When four values are specified, the first one applies to the top-left corner, the second one applies to the top-right corner, the third one applies to the bottom-right corner and the fourth one applies to the bottom-left corner.Example:<!DOCTYPE html><html lang="en"><head> <title> -moz-outline-radius property </title> <style> .elem-1 { outline: dotted; -moz-outline-radius: 5px; width: 300px; padding: 20px; margin: 15px; } .elem-2 { outline: dotted; -moz-outline-radius: 5px 50px; width: 300px; padding: 20px; margin: 15px; } .elem-3 { outline: dotted; -moz-outline-radius: 5px 50px 20px; width: 300px; padding: 20px; margin: 15px; } .elem-4 { outline: dotted; -moz-outline-radius: 5px 50px 20px 100px; width: 300px; padding: 20px; margin: 15px; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> -moz-outline-radius </b> <div class="elem-1"> This div has an outline-radius of 5px. </div> <div class="elem-2"> This div has an outline-radius of 5px 50px. </div> <div class="elem-3"> This div has an outline-radius of 5px 50px 20px. </div> <div class="elem-4"> This div has an outline-radius of 5px 50px 20px 100px; </div></body></html>Output: When one value is specified then the radius would be applied to all the corners of the element. When two values are specified, then the first applies to the top-left and bottom-right corners and the second value applies to the top-left and bottom-right corners. When three values are specified, the first one applies to the top-left corner, the second one applies to the top-right and bottom-left corners and the third one applies to the bottom-right corner. When four values are specified, the first one applies to the top-left corner, the second one applies to the top-right corner, the third one applies to the bottom-right corner and the fourth one applies to the bottom-left corner. Example: <!DOCTYPE html><html lang="en"><head> <title> -moz-outline-radius property </title> <style> .elem-1 { outline: dotted; -moz-outline-radius: 5px; width: 300px; padding: 20px; margin: 15px; } .elem-2 { outline: dotted; -moz-outline-radius: 5px 50px; width: 300px; padding: 20px; margin: 15px; } .elem-3 { outline: dotted; -moz-outline-radius: 5px 50px 20px; width: 300px; padding: 20px; margin: 15px; } .elem-4 { outline: dotted; -moz-outline-radius: 5px 50px 20px 100px; width: 300px; padding: 20px; margin: 15px; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> -moz-outline-radius </b> <div class="elem-1"> This div has an outline-radius of 5px. </div> <div class="elem-2"> This div has an outline-radius of 5px 50px. </div> <div class="elem-3"> This div has an outline-radius of 5px 50px 20px. </div> <div class="elem-4"> This div has an outline-radius of 5px 50px 20px 100px; </div></body></html> Output: percentage: This is used to set the outline radius in percentage values. The values are applied in a similar format as in the length values. The default value of this property is 0.Example:<!DOCTYPE html><html lang="en"> <head> <title> -moz-outline-radius property </title> <style> .elem-1 { outline: dotted; -moz-outline-radius: 10%; width: 300px; padding: 20px; margin: 15px; } .elem-2 { outline: dotted; -moz-outline-radius: 10% 50%; width: 300px; padding: 20px; margin: 15px; } .elem-3 { outline: dotted; -moz-outline-radius: 10% 50% 25%; width: 300px; padding: 20px; margin: 15px; } .elem-4 { outline: dotted; -moz-outline-radius: 10% 50% 25% 75%; width: 300px; padding: 20px; margin: 15px; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> -moz-outline-radius </b> <div class="elem-1"> This div has an outline-radius of 10%. </div> <div class="elem-2"> This div has an outline-radius of 10% 50%. </div> <div class="elem-3"> This div has an outline-radius of 10% 50% 25%. </div> <div class="elem-4"> This div has an outline-radius of 10% 50% 25% 75%; </div></body></html>Output: Example: <!DOCTYPE html><html lang="en"> <head> <title> -moz-outline-radius property </title> <style> .elem-1 { outline: dotted; -moz-outline-radius: 10%; width: 300px; padding: 20px; margin: 15px; } .elem-2 { outline: dotted; -moz-outline-radius: 10% 50%; width: 300px; padding: 20px; margin: 15px; } .elem-3 { outline: dotted; -moz-outline-radius: 10% 50% 25%; width: 300px; padding: 20px; margin: 15px; } .elem-4 { outline: dotted; -moz-outline-radius: 10% 50% 25% 75%; width: 300px; padding: 20px; margin: 15px; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> -moz-outline-radius </b> <div class="elem-1"> This div has an outline-radius of 10%. </div> <div class="elem-2"> This div has an outline-radius of 10% 50%. </div> <div class="elem-3"> This div has an outline-radius of 10% 50% 25%. </div> <div class="elem-4"> This div has an outline-radius of 10% 50% 25% 75%; </div></body></html> Output: initial: This is used to set the property to its default value. inherit: This is used to inherit the property from its parent. Supported Browsers: The browser supported by -moz-outline-radius property are listed below: Firefox 1.5 CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? Design a web page using HTML and CSS 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": 26233, "s": 26205, "text": "\n23 Jan, 2020" }, { "code": null, "e": 26403, "s": 26233, "text": "The -moz-outline-radius property is used to specify the radius of an outline. It is used to give rounded corners to outlines. This property is only supported in Firefox." }, { "code": null, "e": 26411, "s": 26403, "text": "Syntax:" }, { "code": null, "e": 26489, "s": 26411, "text": "-moz-outline-radius: <length> {1-4} \n| <percentage> (1-4} | initial | inherit" }, { "code": null, "e": 26506, "s": 26489, "text": "Property Values:" }, { "code": null, "e": 28461, "s": 26506, "text": "length: This is used to set the outline radius in length units. The default value of this property is 0.The value can be specified in 4 formats.When one value is specified then the radius would be applied to all the corners of the element.When two values are specified, then the first applies to the top-left and bottom-right corners and the second value applies to the top-left and bottom-right corners.When three values are specified, the first one applies to the top-left corner, the second one applies to the top-right and bottom-left corners and the third one applies to the bottom-right corner.When four values are specified, the first one applies to the top-left corner, the second one applies to the top-right corner, the third one applies to the bottom-right corner and the fourth one applies to the bottom-left corner.Example:<!DOCTYPE html><html lang=\"en\"><head> <title> -moz-outline-radius property </title> <style> .elem-1 { outline: dotted; -moz-outline-radius: 5px; width: 300px; padding: 20px; margin: 15px; } .elem-2 { outline: dotted; -moz-outline-radius: 5px 50px; width: 300px; padding: 20px; margin: 15px; } .elem-3 { outline: dotted; -moz-outline-radius: 5px 50px 20px; width: 300px; padding: 20px; margin: 15px; } .elem-4 { outline: dotted; -moz-outline-radius: 5px 50px 20px 100px; width: 300px; padding: 20px; margin: 15px; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> -moz-outline-radius </b> <div class=\"elem-1\"> This div has an outline-radius of 5px. </div> <div class=\"elem-2\"> This div has an outline-radius of 5px 50px. </div> <div class=\"elem-3\"> This div has an outline-radius of 5px 50px 20px. </div> <div class=\"elem-4\"> This div has an outline-radius of 5px 50px 20px 100px; </div></body></html>Output:" }, { "code": null, "e": 28557, "s": 28461, "text": "When one value is specified then the radius would be applied to all the corners of the element." }, { "code": null, "e": 28723, "s": 28557, "text": "When two values are specified, then the first applies to the top-left and bottom-right corners and the second value applies to the top-left and bottom-right corners." }, { "code": null, "e": 28920, "s": 28723, "text": "When three values are specified, the first one applies to the top-left corner, the second one applies to the top-right and bottom-left corners and the third one applies to the bottom-right corner." }, { "code": null, "e": 29149, "s": 28920, "text": "When four values are specified, the first one applies to the top-left corner, the second one applies to the top-right corner, the third one applies to the bottom-right corner and the fourth one applies to the bottom-left corner." }, { "code": null, "e": 29158, "s": 29149, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title> -moz-outline-radius property </title> <style> .elem-1 { outline: dotted; -moz-outline-radius: 5px; width: 300px; padding: 20px; margin: 15px; } .elem-2 { outline: dotted; -moz-outline-radius: 5px 50px; width: 300px; padding: 20px; margin: 15px; } .elem-3 { outline: dotted; -moz-outline-radius: 5px 50px 20px; width: 300px; padding: 20px; margin: 15px; } .elem-4 { outline: dotted; -moz-outline-radius: 5px 50px 20px 100px; width: 300px; padding: 20px; margin: 15px; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> -moz-outline-radius </b> <div class=\"elem-1\"> This div has an outline-radius of 5px. </div> <div class=\"elem-2\"> This div has an outline-radius of 5px 50px. </div> <div class=\"elem-3\"> This div has an outline-radius of 5px 50px 20px. </div> <div class=\"elem-4\"> This div has an outline-radius of 5px 50px 20px 100px; </div></body></html>", "e": 30270, "s": 29158, "text": null }, { "code": null, "e": 30278, "s": 30270, "text": "Output:" }, { "code": null, "e": 31574, "s": 30278, "text": "percentage: This is used to set the outline radius in percentage values. The values are applied in a similar format as in the length values. The default value of this property is 0.Example:<!DOCTYPE html><html lang=\"en\"> <head> <title> -moz-outline-radius property </title> <style> .elem-1 { outline: dotted; -moz-outline-radius: 10%; width: 300px; padding: 20px; margin: 15px; } .elem-2 { outline: dotted; -moz-outline-radius: 10% 50%; width: 300px; padding: 20px; margin: 15px; } .elem-3 { outline: dotted; -moz-outline-radius: 10% 50% 25%; width: 300px; padding: 20px; margin: 15px; } .elem-4 { outline: dotted; -moz-outline-radius: 10% 50% 25% 75%; width: 300px; padding: 20px; margin: 15px; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> -moz-outline-radius </b> <div class=\"elem-1\"> This div has an outline-radius of 10%. </div> <div class=\"elem-2\"> This div has an outline-radius of 10% 50%. </div> <div class=\"elem-3\"> This div has an outline-radius of 10% 50% 25%. </div> <div class=\"elem-4\"> This div has an outline-radius of 10% 50% 25% 75%; </div></body></html>Output:" }, { "code": null, "e": 31583, "s": 31574, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> -moz-outline-radius property </title> <style> .elem-1 { outline: dotted; -moz-outline-radius: 10%; width: 300px; padding: 20px; margin: 15px; } .elem-2 { outline: dotted; -moz-outline-radius: 10% 50%; width: 300px; padding: 20px; margin: 15px; } .elem-3 { outline: dotted; -moz-outline-radius: 10% 50% 25%; width: 300px; padding: 20px; margin: 15px; } .elem-4 { outline: dotted; -moz-outline-radius: 10% 50% 25% 75%; width: 300px; padding: 20px; margin: 15px; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> -moz-outline-radius </b> <div class=\"elem-1\"> This div has an outline-radius of 10%. </div> <div class=\"elem-2\"> This div has an outline-radius of 10% 50%. </div> <div class=\"elem-3\"> This div has an outline-radius of 10% 50% 25%. </div> <div class=\"elem-4\"> This div has an outline-radius of 10% 50% 25% 75%; </div></body></html>", "e": 32683, "s": 31583, "text": null }, { "code": null, "e": 32691, "s": 32683, "text": "Output:" }, { "code": null, "e": 32755, "s": 32691, "text": "initial: This is used to set the property to its default value." }, { "code": null, "e": 32818, "s": 32755, "text": "inherit: This is used to inherit the property from its parent." }, { "code": null, "e": 32910, "s": 32818, "text": "Supported Browsers: The browser supported by -moz-outline-radius property are listed below:" }, { "code": null, "e": 32922, "s": 32910, "text": "Firefox 1.5" }, { "code": null, "e": 32937, "s": 32922, "text": "CSS-Properties" }, { "code": null, "e": 32944, "s": 32937, "text": "Picked" }, { "code": null, "e": 32948, "s": 32944, "text": "CSS" }, { "code": null, "e": 32965, "s": 32948, "text": "Web Technologies" }, { "code": null, "e": 33063, "s": 32965, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33118, "s": 33063, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 33155, "s": 33118, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 33219, "s": 33155, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 33258, "s": 33219, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 33295, "s": 33258, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 33335, "s": 33295, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33368, "s": 33335, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33413, "s": 33368, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33456, "s": 33413, "text": "How to fetch data from an API in ReactJS ?" } ]
Finding Median of unsorted Array in linear time using C++ STL - GeeksforGeeks
07 Aug, 2020 Given an unsorted array arr[] having N elements, the task is to find out the median of the array in linear time complexity. Examples: Input: N = 5, arr[] = {4, 1, 2, 6, 5}Output: 4Explanation:Since N = 5, which is odd, therefore the median is the 3rd element in the sorted array.The 3rd element in the sorted arr[] is 4.Hence the median is 4. Input: N = 8, arr[] = {1, 3, 4, 2, 6, 5, 8, 7}Output: 4.5Explanation:Since N = 8, which is even, therefore median is the average of 4th and 5th element in the sorted array.The 4th and 5th element in the sorted array is 4 and 5 respectively.Hence the median is (4+5)/2 = 4.5. Approach: The idea is to use nth_element() function in C++ STL. If the number of element in the array is odd, then find the (N/2)th element using nth_element() function as illustrated below and then the value at index (N/2) is the median of the given array.nth_element(arr.begin(), arr.begin() + N/2, arr.end())Else find the (N/2)th and ((N – 1)/2)th element using nth_element() function as illustrated below and find the average of the values at index (N/2) and ((N – 1)/2) is the median of the given array.nth_element(arr.begin(), arr.begin() + N/2, arr.end())nth_element(arr.begin(), arr.begin() + (N – 1)/2, arr.end()) If the number of element in the array is odd, then find the (N/2)th element using nth_element() function as illustrated below and then the value at index (N/2) is the median of the given array.nth_element(arr.begin(), arr.begin() + N/2, arr.end()) nth_element(arr.begin(), arr.begin() + N/2, arr.end()) Else find the (N/2)th and ((N – 1)/2)th element using nth_element() function as illustrated below and find the average of the values at index (N/2) and ((N – 1)/2) is the median of the given array.nth_element(arr.begin(), arr.begin() + N/2, arr.end())nth_element(arr.begin(), arr.begin() + (N – 1)/2, arr.end()) nth_element(arr.begin(), arr.begin() + N/2, arr.end())nth_element(arr.begin(), arr.begin() + (N – 1)/2, arr.end()) Below is the implementation of the above approach: // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function for calculating// the mediandouble findMedian(vector<int> a, int n){ // If size of the arr[] is even if (n % 2 == 0) { // Applying nth_element // on n/2th index nth_element(a.begin(), a.begin() + n / 2, a.end()); // Applying nth_element // on (n-1)/2 th index nth_element(a.begin(), a.begin() + (n - 1) / 2, a.end()); // Find the average of value at // index N/2 and (N-1)/2 return (double)(a[(n - 1) / 2] + a[n / 2]) / 2.0; } // If size of the arr[] is odd else { // Applying nth_element // on n/2 nth_element(a.begin(), a.begin() + n / 2, a.end()); // Value at index (N/2)th // is the median return (double)a[n / 2]; }} // Driver Codeint main(){ // Given array arr[] vector<int> arr = { 1, 3, 4, 2, 7, 5, 8, 6 }; // Function Call cout << "Median = " << findMedian(arr, arr.size()) << endl; return 0;} Median = 4.5 Time Complexity: O(N)Auxiliary Space Complexity: O(1) nidhi_biet median-finding STL Algorithms Arrays C++ C++ Programs Competitive Programming Mathematical Write From Home Arrays Mathematical STL Algorithms CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Difference between Algorithm, Pseudocode and Program K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 25943, "s": 25915, "text": "\n07 Aug, 2020" }, { "code": null, "e": 26067, "s": 25943, "text": "Given an unsorted array arr[] having N elements, the task is to find out the median of the array in linear time complexity." }, { "code": null, "e": 26077, "s": 26067, "text": "Examples:" }, { "code": null, "e": 26286, "s": 26077, "text": "Input: N = 5, arr[] = {4, 1, 2, 6, 5}Output: 4Explanation:Since N = 5, which is odd, therefore the median is the 3rd element in the sorted array.The 3rd element in the sorted arr[] is 4.Hence the median is 4." }, { "code": null, "e": 26561, "s": 26286, "text": "Input: N = 8, arr[] = {1, 3, 4, 2, 6, 5, 8, 7}Output: 4.5Explanation:Since N = 8, which is even, therefore median is the average of 4th and 5th element in the sorted array.The 4th and 5th element in the sorted array is 4 and 5 respectively.Hence the median is (4+5)/2 = 4.5." }, { "code": null, "e": 26625, "s": 26561, "text": "Approach: The idea is to use nth_element() function in C++ STL." }, { "code": null, "e": 27184, "s": 26625, "text": "If the number of element in the array is odd, then find the (N/2)th element using nth_element() function as illustrated below and then the value at index (N/2) is the median of the given array.nth_element(arr.begin(), arr.begin() + N/2, arr.end())Else find the (N/2)th and ((N – 1)/2)th element using nth_element() function as illustrated below and find the average of the values at index (N/2) and ((N – 1)/2) is the median of the given array.nth_element(arr.begin(), arr.begin() + N/2, arr.end())nth_element(arr.begin(), arr.begin() + (N – 1)/2, arr.end())" }, { "code": null, "e": 27432, "s": 27184, "text": "If the number of element in the array is odd, then find the (N/2)th element using nth_element() function as illustrated below and then the value at index (N/2) is the median of the given array.nth_element(arr.begin(), arr.begin() + N/2, arr.end())" }, { "code": null, "e": 27487, "s": 27432, "text": "nth_element(arr.begin(), arr.begin() + N/2, arr.end())" }, { "code": null, "e": 27799, "s": 27487, "text": "Else find the (N/2)th and ((N – 1)/2)th element using nth_element() function as illustrated below and find the average of the values at index (N/2) and ((N – 1)/2) is the median of the given array.nth_element(arr.begin(), arr.begin() + N/2, arr.end())nth_element(arr.begin(), arr.begin() + (N – 1)/2, arr.end())" }, { "code": null, "e": 27914, "s": 27799, "text": "nth_element(arr.begin(), arr.begin() + N/2, arr.end())nth_element(arr.begin(), arr.begin() + (N – 1)/2, arr.end())" }, { "code": null, "e": 27965, "s": 27914, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function for calculating// the mediandouble findMedian(vector<int> a, int n){ // If size of the arr[] is even if (n % 2 == 0) { // Applying nth_element // on n/2th index nth_element(a.begin(), a.begin() + n / 2, a.end()); // Applying nth_element // on (n-1)/2 th index nth_element(a.begin(), a.begin() + (n - 1) / 2, a.end()); // Find the average of value at // index N/2 and (N-1)/2 return (double)(a[(n - 1) / 2] + a[n / 2]) / 2.0; } // If size of the arr[] is odd else { // Applying nth_element // on n/2 nth_element(a.begin(), a.begin() + n / 2, a.end()); // Value at index (N/2)th // is the median return (double)a[n / 2]; }} // Driver Codeint main(){ // Given array arr[] vector<int> arr = { 1, 3, 4, 2, 7, 5, 8, 6 }; // Function Call cout << \"Median = \" << findMedian(arr, arr.size()) << endl; return 0;}", "e": 29227, "s": 27965, "text": null }, { "code": null, "e": 29241, "s": 29227, "text": "Median = 4.5\n" }, { "code": null, "e": 29295, "s": 29241, "text": "Time Complexity: O(N)Auxiliary Space Complexity: O(1)" }, { "code": null, "e": 29306, "s": 29295, "text": "nidhi_biet" }, { "code": null, "e": 29321, "s": 29306, "text": "median-finding" }, { "code": null, "e": 29325, "s": 29321, "text": "STL" }, { "code": null, "e": 29336, "s": 29325, "text": "Algorithms" }, { "code": null, "e": 29343, "s": 29336, "text": "Arrays" }, { "code": null, "e": 29347, "s": 29343, "text": "C++" }, { "code": null, "e": 29360, "s": 29347, "text": "C++ Programs" }, { "code": null, "e": 29384, "s": 29360, "text": "Competitive Programming" }, { "code": null, "e": 29397, "s": 29384, "text": "Mathematical" }, { "code": null, "e": 29413, "s": 29397, "text": "Write From Home" }, { "code": null, "e": 29420, "s": 29413, "text": "Arrays" }, { "code": null, "e": 29433, "s": 29420, "text": "Mathematical" }, { "code": null, "e": 29437, "s": 29433, "text": "STL" }, { "code": null, "e": 29448, "s": 29437, "text": "Algorithms" }, { "code": null, "e": 29452, "s": 29448, "text": "CPP" }, { "code": null, "e": 29550, "s": 29452, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29575, "s": 29550, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 29602, "s": 29575, "text": "How to Start Learning DSA?" }, { "code": null, "e": 29655, "s": 29602, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 29689, "s": 29655, "text": "K means Clustering - Introduction" }, { "code": null, "e": 29756, "s": 29689, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 29771, "s": 29756, "text": "Arrays in Java" }, { "code": null, "e": 29787, "s": 29771, "text": "Arrays in C/C++" }, { "code": null, "e": 29855, "s": 29787, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 29901, "s": 29855, "text": "Write a program to reverse an array or string" } ]
How to Use setwd and getwd in R? - GeeksforGeeks
19 Dec, 2021 In this article, we will discuss how to use setwd and getwd in the R programming language. getwd() stands forget working directory. It is used to get the current working directory of the environment. Syntax: getwd() We can also see the total number of files in the present working directory. For that, we have to use the length function. Syntax: length(list.files()) If we have to use the display the filenames, then the command is list.files() Example : In this example, we will be using the getwd() function to get the current working directory. R getwd() Output: "C:/Users/Ramu/saisri" Example : Here, we will be using the getwd() function to get the length of the list of the files present in the working directory of the R console. R # get total file countprint(length(list.files())) # get file namesprint(list.files()) Output: [1] 2 [1] "ai.R" "ramu.R" setwd() stands for set working directory. This is used to set the working environment. Syntax: setwd('path') Example: Here, we will be using the setwd() function to set the working directory. R setwd('C:/Ramu/saisri/') Picked R-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? R - if statement Time Series Analysis in R How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n19 Dec, 2021" }, { "code": null, "e": 26578, "s": 26487, "text": "In this article, we will discuss how to use setwd and getwd in the R programming language." }, { "code": null, "e": 26687, "s": 26578, "text": "getwd() stands forget working directory. It is used to get the current working directory of the environment." }, { "code": null, "e": 26695, "s": 26687, "text": "Syntax:" }, { "code": null, "e": 26703, "s": 26695, "text": "getwd()" }, { "code": null, "e": 26825, "s": 26703, "text": "We can also see the total number of files in the present working directory. For that, we have to use the length function." }, { "code": null, "e": 26833, "s": 26825, "text": "Syntax:" }, { "code": null, "e": 26854, "s": 26833, "text": "length(list.files())" }, { "code": null, "e": 26920, "s": 26854, "text": "If we have to use the display the filenames, then the command is " }, { "code": null, "e": 26933, "s": 26920, "text": "list.files()" }, { "code": null, "e": 26943, "s": 26933, "text": "Example :" }, { "code": null, "e": 27036, "s": 26943, "text": "In this example, we will be using the getwd() function to get the current working directory." }, { "code": null, "e": 27038, "s": 27036, "text": "R" }, { "code": "getwd()", "e": 27046, "s": 27038, "text": null }, { "code": null, "e": 27054, "s": 27046, "text": "Output:" }, { "code": null, "e": 27077, "s": 27054, "text": "\"C:/Users/Ramu/saisri\"" }, { "code": null, "e": 27087, "s": 27077, "text": "Example :" }, { "code": null, "e": 27225, "s": 27087, "text": "Here, we will be using the getwd() function to get the length of the list of the files present in the working directory of the R console." }, { "code": null, "e": 27227, "s": 27225, "text": "R" }, { "code": "# get total file countprint(length(list.files())) # get file namesprint(list.files())", "e": 27314, "s": 27227, "text": null }, { "code": null, "e": 27322, "s": 27314, "text": "Output:" }, { "code": null, "e": 27350, "s": 27322, "text": "[1] 2\n[1] \"ai.R\" \"ramu.R\"" }, { "code": null, "e": 27437, "s": 27350, "text": "setwd() stands for set working directory. This is used to set the working environment." }, { "code": null, "e": 27445, "s": 27437, "text": "Syntax:" }, { "code": null, "e": 27459, "s": 27445, "text": "setwd('path')" }, { "code": null, "e": 27468, "s": 27459, "text": "Example:" }, { "code": null, "e": 27542, "s": 27468, "text": "Here, we will be using the setwd() function to set the working directory." }, { "code": null, "e": 27544, "s": 27542, "text": "R" }, { "code": "setwd('C:/Ramu/saisri/')", "e": 27569, "s": 27544, "text": null }, { "code": null, "e": 27576, "s": 27569, "text": "Picked" }, { "code": null, "e": 27588, "s": 27576, "text": "R-Functions" }, { "code": null, "e": 27599, "s": 27588, "text": "R Language" }, { "code": null, "e": 27697, "s": 27599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27749, "s": 27697, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27784, "s": 27749, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27822, "s": 27784, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27880, "s": 27822, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27923, "s": 27880, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27972, "s": 27923, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28009, "s": 27972, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 28026, "s": 28009, "text": "R - if statement" }, { "code": null, "e": 28052, "s": 28026, "text": "Time Series Analysis in R" } ]
Tuple Division in Python - GeeksforGeeks
26 Nov, 2019 Sometimes, while working with records, we can have a problem in which we may need to perform mathematical division operation across tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1 : Using zip() + generator expressionThe combination of above functions can be used to perform this task. In this, we perform the task of division using generator expression and mapping index of each tuple is done by zip(). # Python3 code to demonstrate working of # Tuple division# using zip() + generator expression # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Tuple division # using zip() + generator expression res = tuple(ele1 // ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) # printing result print("The divided tuple : " + str(res)) The original tuple 1 : (10, 4, 6, 9) The original tuple 2 : (5, 2, 3, 3) The divided tuple : (2, 2, 2, 3) Method #2 : Using map() + floordivThe combination of above functionalities can also perform this task. In this, we perform the task of extending logic of division using floordiv and mapping is done by map(). # Python3 code to demonstrate working of # Tuple division # using map() + floordiv from operator import floordiv # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Tuple division# using map() + floordiv res = tuple(map(floordiv, test_tup1, test_tup2)) # printing result print("The divided tuple : " + str(res)) The original tuple 1 : (10, 4, 6, 9) The original tuple 2 : (5, 2, 3, 3) The divided tuple : (2, 2, 2, 3) Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n26 Nov, 2019" }, { "code": null, "e": 25788, "s": 25537, "text": "Sometimes, while working with records, we can have a problem in which we may need to perform mathematical division operation across tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26021, "s": 25788, "text": "Method #1 : Using zip() + generator expressionThe combination of above functions can be used to perform this task. In this, we perform the task of division using generator expression and mapping index of each tuple is done by zip()." }, { "code": "# Python3 code to demonstrate working of # Tuple division# using zip() + generator expression # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print(\"The original tuple 1 : \" + str(test_tup1)) print(\"The original tuple 2 : \" + str(test_tup2)) # Tuple division # using zip() + generator expression res = tuple(ele1 // ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) # printing result print(\"The divided tuple : \" + str(res)) ", "e": 26505, "s": 26021, "text": null }, { "code": null, "e": 26612, "s": 26505, "text": "The original tuple 1 : (10, 4, 6, 9)\nThe original tuple 2 : (5, 2, 3, 3)\nThe divided tuple : (2, 2, 2, 3)\n" }, { "code": null, "e": 26822, "s": 26614, "text": "Method #2 : Using map() + floordivThe combination of above functionalities can also perform this task. In this, we perform the task of extending logic of division using floordiv and mapping is done by map()." }, { "code": "# Python3 code to demonstrate working of # Tuple division # using map() + floordiv from operator import floordiv # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print(\"The original tuple 1 : \" + str(test_tup1)) print(\"The original tuple 2 : \" + str(test_tup2)) # Tuple division# using map() + floordiv res = tuple(map(floordiv, test_tup1, test_tup2)) # printing result print(\"The divided tuple : \" + str(res))", "e": 27289, "s": 26822, "text": null }, { "code": null, "e": 27396, "s": 27289, "text": "The original tuple 1 : (10, 4, 6, 9)\nThe original tuple 2 : (5, 2, 3, 3)\nThe divided tuple : (2, 2, 2, 3)\n" }, { "code": null, "e": 27418, "s": 27396, "text": "Python tuple-programs" }, { "code": null, "e": 27425, "s": 27418, "text": "Python" }, { "code": null, "e": 27441, "s": 27425, "text": "Python Programs" }, { "code": null, "e": 27539, "s": 27441, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27571, "s": 27539, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27613, "s": 27571, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27655, "s": 27613, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27682, "s": 27655, "text": "Python Classes and Objects" }, { "code": null, "e": 27738, "s": 27682, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27760, "s": 27738, "text": "Defaultdict in Python" }, { "code": null, "e": 27799, "s": 27760, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27845, "s": 27799, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27883, "s": 27845, "text": "Python | Convert a list to dictionary" } ]
Tryit Editor v3.7
Tryit: The video element
[]
Context-specific Pre-processing for NLP with spaCy: Tweets | by Wei-Ting Yap | Towards Data Science
Natural Language Processing is a field of machine learning concerned with understanding human language. As opposed to numerical data, NLP works primarily with text. Exploring and pre-processing text data requires different techniques and libraries, and this tutorial demonstrates the basics. However, pre-processing is not an algorithmic procedure. With data science tasks, often the context of the data determines what aspects of the data are valuable, and what aspects are irrelevant or unreliable. In this tutorial, we explore text pre-processing in the context of tweets, or more generally, social media. Kaggle’s 9-year-old Getting Started Real or Not? NLP with Disaster Tweets competition presents a reasonably-sized dataset (around 7500 tweets in the training set) for practice. The challenge is to classify tweets, given their text, keyword and location, into whether they are really about disasters or not. The code for this tutorial can be followed at this notebook and repository. Before we get started, download the nlp-getting-started data from Kaggle. In my project directory, I put train.csv, test.csv, and sample_submission.csv under a data subdirectory. Let’s start by importing typical and useful data science libraries and creating a dataframe out of train.csv. I won’t delve into the details of libraries that are not NLP-specific. import pandas as pdimport numpy as npimport matplotlib.pyplot as pltdata = pd.read_csv('data/train.csv', index_col='id')data.head()keyword location text targetid 1 NaN NaN Our Deeds are the Reason of this #earthquake M... 14 NaN NaN Forest fire near La Ronge Sask. Canada 15 NaN NaN All residents asked to 'shelter in place' are ... 16 NaN NaN 13,000 people receive #wildfires evacuation or... 17 NaN NaN Just got sent this photo from Ruby #Alaska as ... Our data comprises 4 columns, keyword, location, text and target. Quoting the data description on Kaggle: id - a unique identifier for each tweet text - the text of the tweet location - the location the tweet was sent from (may be blank) keyword - a particular keyword from the tweet (may be blank) target - in train.csv only, this denotes whether a tweet is about a real disaster (1) or not (0) To ensure integrity with the number of rows and columns in our dataset, as well as make judgements on the generalizability of our training set, let’s understand the size of our training data. data.shape(7613, 4) Examining closer, we find there are 52 duplicate rows (different id’s, but same keyword, location, text and target. np.sum(data.duplicated()) # 52 duplicates So let’s drop the duplicate rows. The index (set as id) remains intact. After removing duplicate rows, we are left with 7561 tweets (integrity check, as mentioned earlier), a manageable amount for this tutorial. However, 7561 data points is still relatively little for NLP, especially if we are using deep learning models. Given that there are probably close to a million tweets each day, I doubt a model trained on just 7561 data points is generalizable enough. # let's drop the duplicates! df = datadf = data.drop_duplicates()df.shape Our output: (7561, 4) Aside from training size, the balance of classes (target) in training set is also important. A training set with all target value = 0 will leave the model classifying every tweet as not about a disaster. The vice versa situation is also true. Ideally, the training set should have all classes represented equally. We can use panda’s dataframe value_counts() method to count the number of rows for each class. With 4322 tweets not about disasters (target=0) and 3239 tweets about disasters (target=1), we have a 4:3 class balance. That's not perfectly balanced, but it's not disastrously imbalanced. # target 1 refers to disaster tweet, 0 is not a disaster tweetdf['target'].value_counts() Our output: 0 43221 3239Name: target, dtype: int64 Let’s also look into the completeness of data. Using we can sum up the series returned by panda’s dataframe isna() method to count the number of na entries for each column. # checking for completeness of dataprint(f"{np.sum(df['keyword'].isna())} rows have no keywords")print(f"{np.sum(df['location'].isna())} rows have no location")print(f"{np.sum(df['text'].isna())} rows have no text")print(f"{np.sum(df['text'].isna())} rows have no target") Our output: 61 rows have no keywords 2533 rows have no location 0 rows have no text 0 rows have no target Ideally, we would further characterize and explore the data by analyzing the word lengths, sentence lengths, word frequencies and more. While that’s out of scope for this tutorial, you can learn more about it here. Now that we have explored the data, let’s pre-process the tweets and represent them in a form our models can take as input. The most common numerical representation for texts is the bag-of-words representation. Bag of words is a way to represent text data numerically. Text data is essentially split into words (or more accurately, tokens), which are features. The frequency of each word in each text data is are the corresponding feature values. For example, we might represent "I love cake very very much" as a bag of words dictionary: {'I':1,'love':1,'cake':1,'very':2,'much':1} Tokenization breaks text data up into its tokens at the level of NLP (word, phrase, sentence). The lowest (and most common) is words, which fits perfectly with our bag of words representation. However, these tokens could also include punctuation, stop words, and other custom tokens. We’ll consider these in the context of tweets and the challenge in the next session. Stemming refers to truncating words of their affixes (prefixes or suffixes) to approximate them to their root form. This is often done with a lookup dictionary of prefixes and suffixes, making it computationally fast. However, there is a performance trade-off. In the English language, some affixes change the meaning of the word completely, resulting in inaccurate feature representation. The alternative to stemming is lemmatization, where words are reduced to their lemmas, or root form. This is done using a lookup dictionary of words and their lemmas, hence resulting in it being more computationally expensive. However, performance is often better, since features are represented more accurately. Given the relatively smaller size of our dataset, we will use lemmatization. Getting from tweets to their bag of words representation is less straightforward. What about: words of different cases e.g. cake vs Cake, punctuation, stopwords, numbers, mentions, hashtags, and URLs? When deciding what we want to do with these elements, we have to consider the context of the data and reconcile that with the challenge. In internet lingo, different cases could communicate different sentiments (e.g. danger vs DANGER!) or different parts of speech (e.g. start of the sentence, or a pronoun like The Fight Club). By changing all tokens to upper- or lower- case, we could be losing data helpful for classification. However, since we have a small dataset (7500 tweets), there is unlikely to be sufficient data of each upper-/lower-case variant, let’s go with lower-case. Tweets are undoubtedly going to contain punctuations, which can convey different sentiments or emotions too. Consider, in internet lingo, the difference between: Help needed? Help needed! We’ll consider punctuations each as their own tokens, with special cases like ‘...’ being a separate token from ‘.’. So we don’t lose data, we can disregard them (and even tune which punctuations to ignore) when tuning our hyper-parameters. Stop words are essentially words so common that they have little significant contribution to the meaning of the text. These words include articles (the, a, that) and other commonly used words (what, how, many). Stop word tokens are often ignored in NLP processing. Plus, the character limit of a tweet (280 characters) often results in grammatically incorrect tweets, where articles are missed. However, rather than ignore stop words from the start, let’s disregard them (and even tune which stop words to ignore) when tuning our hyper-parameters so we don’t lose data. Numbers in tweets can convey the quantity of literal objects, but can also convey the scale of something (e.g. 7.9 Richter scale earthquake) or the year (e.g. 2005 Hurricane Katrina). In the latter two cases, such numerical information may be valuable depending on the level of NLP we choose to do later down the road (word-level vs phrase- or sentence- level), or if we want to filter tweets about historical disasters vs current disasters. As such, we will retain numbers as tokens, with the option of ignoring them (or even only counting numbers that are years) when tuning our hyper-parameters. On Twitter, mentions allows users to address each other through a tweet. While mentions between personal accounts may be less significant, mentions to authorities to alert them of disasters (consider @policeauthorities, gun shooting down brick lane right now!). Let’s tokenize mentions along with their usernames, but also count the number of mentions, which could convey a conversation. Hashtags on Twitter allow users to discover content related to a specific theme or topic. When it comes to natural disasters, hashtags like #prayforCountryX and #RIPxyzShootings can differentiate tweets about disasters from everyday tweets. As such, let’s tokenize hashtags with their content, but also count the number of hashtags. The number of hashtags could flag sensationalized social media marketing tweets (e.g. This beat drop is the bomb! #edm #music #dubstep #newrelease) that use disaster keywords. Disaster tweets could include URLs to news articles, relief efforts, or images. However, the same can be said of everyday tweets. Since we’re unsure if disaster tweets are more likely to have URLs or a certain type of URL, let’s keep URLs as tokens and the number of URLs as a feature. This challenge’s dataset features tweets with Twitter-shortened URLs (http://t.co), but more current tweet data could include the domains, which can then be extracted (I imagine the red cross domain would be highly correlated with disaster tweets). For more complicated algorithms, one can also consider visiting the shortened URL and scraping web page elements. spaCy is an open-source python library for natural language processing. It integrates well with the rest of the python machine learning libraries (scikit-learn, TensorFlow, PyTorch) and more, and uses a object-oriented approach to keep its interface readable and easy to use. Notably, it its model returns Document type data, which consists of tokens with various useful annotations (e.g. its lemma, whether it's a stopword) as attributes. Let’s import spaCy, download the model for American English, and load the relevant spaCy model. # download spaCy model for American English!python3 -m spacy download en_core_web_smimport spacy import en_core_web_smnlp = en_core_web_sm.load() Before we customize spaCy, we can take a look at how the out-of-the-box model tokenizes tweets with its default rules. I created a tweet that included a number, a contraction, a hashtag, a mention and a link. As shown below, out-of-the-box spaCy already breaks up contractions and gives us the relevant lemmas. It also recognizes numbers, mentions and URLs as their own tokens according to the default rules. That leaves us with hashtags, which are split into a ‘#’ punctuation and hashtag content, instead of it staying as a whole token. # Let's see what spaCy does with numbers, contractions, #hashtags, @mentions and URLss = "2020 can't get any worse #ihate2020 @bestfriend <https://t.co>"doc = nlp(s)# Let's look at the lemmas and is stopword of each tokenprint(f"Token\\t\\tLemma\\t\\tStopword")print("="*40)for token in doc: print(f"{token}\\t\\t{token.lemma_}\\t\\t{token.is_stop}" This prints: Token Lemma Stopword========================================2020 2020 Falseca can Truen't not Trueget get Trueany any Trueworse bad False# # Falseihate2020 ihate2020 False@bestfriend @bestfriend False<https://t.co> <https://t.co> False We can modify spaCy’s model to recognize hashtags as entire tokens. spaCy’s tokenizer can be modified (you can also build a custom tokenizer if you want!) by redefining its default rules. spaCy’s tokenizer prioritizes rules in the following order: token match pattern, prefix, suffix, infixes, URL, special cases (see How spaCy’s Tokenizer Works). In our case, we’ll modify the tokenizer’s pattern matching regex pattern (read more about regex here: A simple intro to Regex with Python) by appending '#\\w+', which is a pattern for the hash symbol and a word. # We want to also keep #hashtags as a token, so we will modify the spaCy model's token_matchimport re# Retrieve the default token-matching regex patternre_token_match = spacy.tokenizer._get_regex_pattern(nlp.Defaults.token_match)# Add #hashtag patternre_token_match = f"({re_token_match}|#\\w+)"nlp.tokenizer.token_match = re.compile(re_token_match).match# Now let's try agains = "2020 can't get any worse #ihate2020 @bestfriend <https://t.co>"doc = nlp(s)# Let's look at the lemmas and is stopword of each tokenprint(f"Token\\t\\tLemma\\t\\tStopword")print("="*40)for token in doc: print(f"{token}\\t\\t{token.lemma_}\\t\\t{token.is_stop}") Our code prints: Token Lemma Stopword========================================2020 2020 Falseca can Truen't not Trueget get Trueany any Trueworse bad False#ihate2020 #ihate2020 False@bestfriend @bestfriend False<https://t.co> <https://t.co> False We can then proceed to create a preprocessing algorithm, and put it in a function so it can be called on every tweet in the training set. In the following preprocess function, each tweet: Is changed to lower case Is tokenized with our modified spaCy model Has its lemmas of tokens set unioned with our features set Has its bag-of-words representation constructed in a dictionary freq Has its hashtags, mentions and URLs counted # Create a pre-process function for each tweetdef preprocess(s, nlp, features): """ Given string s, spaCy model nlp, and set features (lemmas encountered), pre-process s and return updated features and bag-of-words representation dict freq - changes s to lower-case - tokenize s using nlp to create a doc - update features with lemmas encountered in s - create bag-of-words representation in dict type freq, including counts for hashtags, mentions and URLs """# To lowercase s = s.lower()# Creating a doc with spaCy doc = nlp(s) lemmas = [] for token in doc: lemmas.append(token.lemma_)# Union between lemmas and our features set features |= set(lemmas)# Constructing a bag of words for the tweet freq = {'#':0,'@':0,'URL':0} for word in lemmas: freq[str(word)] = 0 for token in doc: if '#' in str(token): freq['#'] += 1 # Count number of hashtags, regardless of hashtag if '@' in str(token): freq['@'] += 1 # Count number of mentions, regardless of mention if 'http://' in str(token): freq['URL'] += 1 # Count number of URLs, regardless of URL freq[str(token.lemma_)] += 1 return features, freq We’ll create a copy our de-duplicated data as a best practice, so that any pre-processing changes does not affect the original state of our training data. Then, we will initialize a python set features, which will contain all features of each tweet. In addition to all lemmas encountered via tokenization of each tweet, features will include number of hashtags (#), number of mentions (@), and number of URLs (URL). preprocess_df = df # Duplicate for preprocessingfeatures = set({'#','@','URL'}) # Using set feature to contain all words (lemmas) seen Using our preprocess function, we'll preprocess every tweet, updating features each time with new lemmas seen. With each tweet, the tweet's bag of words representation freq is also appended to an array of bag of words for each tweet (bow_array). # Array bow_array of bow representations for each tweet;# bow_array[i] is the bow representation for tweet id (i+1)bow_array = [] for i in range(len(preprocess_df)): features, freq = preprocess(preprocess_df.iloc[i]['text'],nlp,features) bow_array.append(freq)len(bow_array) # 7561 With all lemmas encountered across all tweets collected in features, we can create a dataframe bow to represent the features of all the tweets. # Create dataframe for bag of words representation for each tweetbow = pd.DataFrame('0', columns=features,index=range(len(preprocess_df)))bow['id']=preprocess_df.indexbow.set_index('id',drop=True,inplace=True) Now, let’s update our dataframe with the feature values of each tweet. # Update bow[i] with bag-of-words freq of the tweet id (i+1)for i in range(len(preprocess_df)): freq = bow_array[i] for f in freq: bow.loc[i+1,f]=freq[f] Finally, we will join our training data dataframe with our bag-of-words. pandas Dataframe’s join method allows us to add columns from one dataframe to another for rows where the index matches. Note that we append '_data' as a suffix to all columns from the 'left' dataframe, which is preprocess_df. This is to avoid conflicts between the keyword given as part of the training data, and 'keyword' as a lemma-token-feature. Remember to save the preprocessed .csv file for easier next steps! # Join bag-of-words representation to train dataframe# Append _data suffix to 'keyword','location','text','target' for features that are not lemma tokenspreprocess_df = preprocess_df.join(bow,lsuffix='_data')# Saving bag-of-words representation for collaboratorspreprocess_df.to_csv("data/train_preprocessed.csv",index=True,index_label='id') Now that we’ve pre-processed our data, there’s just one last step before we can jump into using it to train our model of choice. We have split it, stratified according to the distribution of classes, into training and validation sets. Using train_test_split from sklearn.model_selection: from sklearn.model_selection import train_test_split# stratify=y creates a balanced validation sety = preprocess_df['target_data']df_train, df_val = train_test_split(preprocess_df, test_size=0.10, random_state=101, stratify=y)# Saving csv files for collaboratorsdf_train.to_csv("data/train_preprocessed_split.csv",index=True)df_val.to_csv("data/val_preprocessed_split.csv",index=True)print(df_train.shape, df_val.shape)(6851, 21330) (762, 21330) Just to be sure, we can check our balance. # Checking balanceprint(f"""Ratio of target=1 to target=0 tweets in:\\n Original data set = {np.sum(preprocess_df['target_data']==1)/np.sum(preprocess_df['target_data']==0)},\\nTraining data set = {np.sum(df_train['target_data']==1)/np.sum(df_train['target_data']==0)},\\nValidation data set = {np.sum(df_val['target_data']==1)/np.sum(df_val['target_data']==0)}""") This prints: Ratio of target=1 to target=0 tweets in: Original data set = 0.7533394748963611,Training data set = 0.7535193242897363,Validation data set = 0.7517241379310344 If you have seen other NLP pre-processing tutorials, you’ll find that a lot of their steps have been included as considerations, but not implemented here. These include removing punctuations, numbers, and stop words. However, our training dataset is small, and these steps could remove information valuable in the context of tweets and the challenge. Hence, rather than eliminate these data at the pre-processing stage, we have left them as possible ways to tune the hyper-parameters of our model. Through this tutorial, we have pre-processed tweets into their bag-of-words representation. However, you may choose to go a few steps further with Term Frequency — Inverse Document Frequency (TFIDF). TF-IDF stands for “Term,Information Retrieval and Text Mining, which penalizes terms that appear too often (as they become less discriminatory as features), or word vectors, which also numerically account for the word’s context and semantics. Word vectors encoding will result in better performance than TFIDF encoding, which will result in better performance than bag-of-words encoding. We have ignored location and keyword in this tutorial, focusing entirely on tweets. You could consider encoding location by similarity, accounting for different spellings of the same place (e.g. USA vs U.S.), and missing values. You can also weight keywords heavier and see how that affects the performance of your model. Lastly, there may be valuable information in the URLs that we are missing out. Given that they are in shortened form, we are unable to extract the domain name or page content from the text data alone. You could consider building an algorithm to visit the site and extract the domain name, as well as scrape relevant elements on the page (e.g. page title). Now that we have performed basic pre-processing our dataset, we can move forward in two possible directions. You can either continue on to advanced pre-processing by performing spell checks and correction with Pyspellchecker and Mordecai, or try out and evaluate candidate machine learning models! Possible models for such classification problems include logistic regression, neural networks, and SVMs. [1] Kaggle, Disaster tweets classification challenge on Kaggle (2020), Kaggle [2] D. Becker and M. Leonard, Intro to NLP (n.d.), Natural Language Processing Course on Kaggle [3] D. Becker and M. Leonard, Text Classification with SpaCy (n.d.), Natural Language Processing Course on Kaggle [4] Yse, D. L. Your Guide to Natural Language Processing (2019), Towards Data Science [5] Explosion AI, spaCy’s 101: Everything you need to know (n.d.), spaCy
[ { "code": null, "e": 464, "s": 172, "text": "Natural Language Processing is a field of machine learning concerned with understanding human language. As opposed to numerical data, NLP works primarily with text. Exploring and pre-processing text data requires different techniques and libraries, and this tutorial demonstrates the basics." }, { "code": null, "e": 781, "s": 464, "text": "However, pre-processing is not an algorithmic procedure. With data science tasks, often the context of the data determines what aspects of the data are valuable, and what aspects are irrelevant or unreliable. In this tutorial, we explore text pre-processing in the context of tweets, or more generally, social media." }, { "code": null, "e": 1088, "s": 781, "text": "Kaggle’s 9-year-old Getting Started Real or Not? NLP with Disaster Tweets competition presents a reasonably-sized dataset (around 7500 tweets in the training set) for practice. The challenge is to classify tweets, given their text, keyword and location, into whether they are really about disasters or not." }, { "code": null, "e": 1164, "s": 1088, "text": "The code for this tutorial can be followed at this notebook and repository." }, { "code": null, "e": 1343, "s": 1164, "text": "Before we get started, download the nlp-getting-started data from Kaggle. In my project directory, I put train.csv, test.csv, and sample_submission.csv under a data subdirectory." }, { "code": null, "e": 1524, "s": 1343, "text": "Let’s start by importing typical and useful data science libraries and creating a dataframe out of train.csv. I won’t delve into the details of libraries that are not NLP-specific." }, { "code": null, "e": 1982, "s": 1524, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltdata = pd.read_csv('data/train.csv', index_col='id')data.head()keyword\tlocation\ttext\ttargetid\t\t\t\t1\tNaN\tNaN\tOur Deeds are the Reason of this #earthquake M...\t14\tNaN\tNaN\tForest fire near La Ronge Sask. Canada\t15\tNaN\tNaN\tAll residents asked to 'shelter in place' are ...\t16\tNaN\tNaN\t13,000 people receive #wildfires evacuation or...\t17\tNaN\tNaN\tJust got sent this photo from Ruby #Alaska as ..." }, { "code": null, "e": 2088, "s": 1982, "text": "Our data comprises 4 columns, keyword, location, text and target. Quoting the data description on Kaggle:" }, { "code": null, "e": 2128, "s": 2088, "text": "id - a unique identifier for each tweet" }, { "code": null, "e": 2157, "s": 2128, "text": "text - the text of the tweet" }, { "code": null, "e": 2220, "s": 2157, "text": "location - the location the tweet was sent from (may be blank)" }, { "code": null, "e": 2281, "s": 2220, "text": "keyword - a particular keyword from the tweet (may be blank)" }, { "code": null, "e": 2378, "s": 2281, "text": "target - in train.csv only, this denotes whether a tweet is about a real disaster (1) or not (0)" }, { "code": null, "e": 2570, "s": 2378, "text": "To ensure integrity with the number of rows and columns in our dataset, as well as make judgements on the generalizability of our training set, let’s understand the size of our training data." }, { "code": null, "e": 2590, "s": 2570, "text": "data.shape(7613, 4)" }, { "code": null, "e": 2706, "s": 2590, "text": "Examining closer, we find there are 52 duplicate rows (different id’s, but same keyword, location, text and target." }, { "code": null, "e": 2748, "s": 2706, "text": "np.sum(data.duplicated()) # 52 duplicates" }, { "code": null, "e": 2960, "s": 2748, "text": "So let’s drop the duplicate rows. The index (set as id) remains intact. After removing duplicate rows, we are left with 7561 tweets (integrity check, as mentioned earlier), a manageable amount for this tutorial." }, { "code": null, "e": 3211, "s": 2960, "text": "However, 7561 data points is still relatively little for NLP, especially if we are using deep learning models. Given that there are probably close to a million tweets each day, I doubt a model trained on just 7561 data points is generalizable enough." }, { "code": null, "e": 3285, "s": 3211, "text": "# let's drop the duplicates! df = datadf = data.drop_duplicates()df.shape" }, { "code": null, "e": 3297, "s": 3285, "text": "Our output:" }, { "code": null, "e": 3307, "s": 3297, "text": "(7561, 4)" }, { "code": null, "e": 3621, "s": 3307, "text": "Aside from training size, the balance of classes (target) in training set is also important. A training set with all target value = 0 will leave the model classifying every tweet as not about a disaster. The vice versa situation is also true. Ideally, the training set should have all classes represented equally." }, { "code": null, "e": 3906, "s": 3621, "text": "We can use panda’s dataframe value_counts() method to count the number of rows for each class. With 4322 tweets not about disasters (target=0) and 3239 tweets about disasters (target=1), we have a 4:3 class balance. That's not perfectly balanced, but it's not disastrously imbalanced." }, { "code": null, "e": 3996, "s": 3906, "text": "# target 1 refers to disaster tweet, 0 is not a disaster tweetdf['target'].value_counts()" }, { "code": null, "e": 4008, "s": 3996, "text": "Our output:" }, { "code": null, "e": 4053, "s": 4008, "text": "0 43221 3239Name: target, dtype: int64" }, { "code": null, "e": 4226, "s": 4053, "text": "Let’s also look into the completeness of data. Using we can sum up the series returned by panda’s dataframe isna() method to count the number of na entries for each column." }, { "code": null, "e": 4499, "s": 4226, "text": "# checking for completeness of dataprint(f\"{np.sum(df['keyword'].isna())} rows have no keywords\")print(f\"{np.sum(df['location'].isna())} rows have no location\")print(f\"{np.sum(df['text'].isna())} rows have no text\")print(f\"{np.sum(df['text'].isna())} rows have no target\")" }, { "code": null, "e": 4511, "s": 4499, "text": "Our output:" }, { "code": null, "e": 4605, "s": 4511, "text": "61 rows have no keywords 2533 rows have no location 0 rows have no text 0 rows have no target" }, { "code": null, "e": 4820, "s": 4605, "text": "Ideally, we would further characterize and explore the data by analyzing the word lengths, sentence lengths, word frequencies and more. While that’s out of scope for this tutorial, you can learn more about it here." }, { "code": null, "e": 4944, "s": 4820, "text": "Now that we have explored the data, let’s pre-process the tweets and represent them in a form our models can take as input." }, { "code": null, "e": 5031, "s": 4944, "text": "The most common numerical representation for texts is the bag-of-words representation." }, { "code": null, "e": 5358, "s": 5031, "text": "Bag of words is a way to represent text data numerically. Text data is essentially split into words (or more accurately, tokens), which are features. The frequency of each word in each text data is are the corresponding feature values. For example, we might represent \"I love cake very very much\" as a bag of words dictionary:" }, { "code": null, "e": 5402, "s": 5358, "text": "{'I':1,'love':1,'cake':1,'very':2,'much':1}" }, { "code": null, "e": 5771, "s": 5402, "text": "Tokenization breaks text data up into its tokens at the level of NLP (word, phrase, sentence). The lowest (and most common) is words, which fits perfectly with our bag of words representation. However, these tokens could also include punctuation, stop words, and other custom tokens. We’ll consider these in the context of tweets and the challenge in the next session." }, { "code": null, "e": 5989, "s": 5771, "text": "Stemming refers to truncating words of their affixes (prefixes or suffixes) to approximate them to their root form. This is often done with a lookup dictionary of prefixes and suffixes, making it computationally fast." }, { "code": null, "e": 6161, "s": 5989, "text": "However, there is a performance trade-off. In the English language, some affixes change the meaning of the word completely, resulting in inaccurate feature representation." }, { "code": null, "e": 6474, "s": 6161, "text": "The alternative to stemming is lemmatization, where words are reduced to their lemmas, or root form. This is done using a lookup dictionary of words and their lemmas, hence resulting in it being more computationally expensive. However, performance is often better, since features are represented more accurately." }, { "code": null, "e": 6551, "s": 6474, "text": "Given the relatively smaller size of our dataset, we will use lemmatization." }, { "code": null, "e": 6645, "s": 6551, "text": "Getting from tweets to their bag of words representation is less straightforward. What about:" }, { "code": null, "e": 6689, "s": 6645, "text": "words of different cases e.g. cake vs Cake," }, { "code": null, "e": 6702, "s": 6689, "text": "punctuation," }, { "code": null, "e": 6713, "s": 6702, "text": "stopwords," }, { "code": null, "e": 6722, "s": 6713, "text": "numbers," }, { "code": null, "e": 6732, "s": 6722, "text": "mentions," }, { "code": null, "e": 6746, "s": 6732, "text": "hashtags, and" }, { "code": null, "e": 6752, "s": 6746, "text": "URLs?" }, { "code": null, "e": 6889, "s": 6752, "text": "When deciding what we want to do with these elements, we have to consider the context of the data and reconcile that with the challenge." }, { "code": null, "e": 7182, "s": 6889, "text": "In internet lingo, different cases could communicate different sentiments (e.g. danger vs DANGER!) or different parts of speech (e.g. start of the sentence, or a pronoun like The Fight Club). By changing all tokens to upper- or lower- case, we could be losing data helpful for classification." }, { "code": null, "e": 7337, "s": 7182, "text": "However, since we have a small dataset (7500 tweets), there is unlikely to be sufficient data of each upper-/lower-case variant, let’s go with lower-case." }, { "code": null, "e": 7499, "s": 7337, "text": "Tweets are undoubtedly going to contain punctuations, which can convey different sentiments or emotions too. Consider, in internet lingo, the difference between:" }, { "code": null, "e": 7512, "s": 7499, "text": "Help needed?" }, { "code": null, "e": 7525, "s": 7512, "text": "Help needed!" }, { "code": null, "e": 7766, "s": 7525, "text": "We’ll consider punctuations each as their own tokens, with special cases like ‘...’ being a separate token from ‘.’. So we don’t lose data, we can disregard them (and even tune which punctuations to ignore) when tuning our hyper-parameters." }, { "code": null, "e": 7977, "s": 7766, "text": "Stop words are essentially words so common that they have little significant contribution to the meaning of the text. These words include articles (the, a, that) and other commonly used words (what, how, many)." }, { "code": null, "e": 8161, "s": 7977, "text": "Stop word tokens are often ignored in NLP processing. Plus, the character limit of a tweet (280 characters) often results in grammatically incorrect tweets, where articles are missed." }, { "code": null, "e": 8336, "s": 8161, "text": "However, rather than ignore stop words from the start, let’s disregard them (and even tune which stop words to ignore) when tuning our hyper-parameters so we don’t lose data." }, { "code": null, "e": 8520, "s": 8336, "text": "Numbers in tweets can convey the quantity of literal objects, but can also convey the scale of something (e.g. 7.9 Richter scale earthquake) or the year (e.g. 2005 Hurricane Katrina)." }, { "code": null, "e": 8778, "s": 8520, "text": "In the latter two cases, such numerical information may be valuable depending on the level of NLP we choose to do later down the road (word-level vs phrase- or sentence- level), or if we want to filter tweets about historical disasters vs current disasters." }, { "code": null, "e": 8935, "s": 8778, "text": "As such, we will retain numbers as tokens, with the option of ignoring them (or even only counting numbers that are years) when tuning our hyper-parameters." }, { "code": null, "e": 9197, "s": 8935, "text": "On Twitter, mentions allows users to address each other through a tweet. While mentions between personal accounts may be less significant, mentions to authorities to alert them of disasters (consider @policeauthorities, gun shooting down brick lane right now!)." }, { "code": null, "e": 9323, "s": 9197, "text": "Let’s tokenize mentions along with their usernames, but also count the number of mentions, which could convey a conversation." }, { "code": null, "e": 9564, "s": 9323, "text": "Hashtags on Twitter allow users to discover content related to a specific theme or topic. When it comes to natural disasters, hashtags like #prayforCountryX and #RIPxyzShootings can differentiate tweets about disasters from everyday tweets." }, { "code": null, "e": 9832, "s": 9564, "text": "As such, let’s tokenize hashtags with their content, but also count the number of hashtags. The number of hashtags could flag sensationalized social media marketing tweets (e.g. This beat drop is the bomb! #edm #music #dubstep #newrelease) that use disaster keywords." }, { "code": null, "e": 10118, "s": 9832, "text": "Disaster tweets could include URLs to news articles, relief efforts, or images. However, the same can be said of everyday tweets. Since we’re unsure if disaster tweets are more likely to have URLs or a certain type of URL, let’s keep URLs as tokens and the number of URLs as a feature." }, { "code": null, "e": 10481, "s": 10118, "text": "This challenge’s dataset features tweets with Twitter-shortened URLs (http://t.co), but more current tweet data could include the domains, which can then be extracted (I imagine the red cross domain would be highly correlated with disaster tweets). For more complicated algorithms, one can also consider visiting the shortened URL and scraping web page elements." }, { "code": null, "e": 10921, "s": 10481, "text": "spaCy is an open-source python library for natural language processing. It integrates well with the rest of the python machine learning libraries (scikit-learn, TensorFlow, PyTorch) and more, and uses a object-oriented approach to keep its interface readable and easy to use. Notably, it its model returns Document type data, which consists of tokens with various useful annotations (e.g. its lemma, whether it's a stopword) as attributes." }, { "code": null, "e": 11017, "s": 10921, "text": "Let’s import spaCy, download the model for American English, and load the relevant spaCy model." }, { "code": null, "e": 11163, "s": 11017, "text": "# download spaCy model for American English!python3 -m spacy download en_core_web_smimport spacy import en_core_web_smnlp = en_core_web_sm.load()" }, { "code": null, "e": 11372, "s": 11163, "text": "Before we customize spaCy, we can take a look at how the out-of-the-box model tokenizes tweets with its default rules. I created a tweet that included a number, a contraction, a hashtag, a mention and a link." }, { "code": null, "e": 11702, "s": 11372, "text": "As shown below, out-of-the-box spaCy already breaks up contractions and gives us the relevant lemmas. It also recognizes numbers, mentions and URLs as their own tokens according to the default rules. That leaves us with hashtags, which are split into a ‘#’ punctuation and hashtag content, instead of it staying as a whole token." }, { "code": null, "e": 12055, "s": 11702, "text": "# Let's see what spaCy does with numbers, contractions, #hashtags, @mentions and URLss = \"2020 can't get any worse #ihate2020 @bestfriend <https://t.co>\"doc = nlp(s)# Let's look at the lemmas and is stopword of each tokenprint(f\"Token\\\\t\\\\tLemma\\\\t\\\\tStopword\")print(\"=\"*40)for token in doc: print(f\"{token}\\\\t\\\\t{token.lemma_}\\\\t\\\\t{token.is_stop}\"" }, { "code": null, "e": 12068, "s": 12055, "text": "This prints:" }, { "code": null, "e": 12326, "s": 12068, "text": "Token\t\tLemma\t\tStopword========================================2020\t\t2020\t\tFalseca\t\tcan\t\tTruen't\t\tnot\t\tTrueget\t\tget\t\tTrueany\t\tany\t\tTrueworse\t\tbad\t\tFalse#\t\t#\t\tFalseihate2020\t\tihate2020\t\tFalse@bestfriend\t\t@bestfriend\t\tFalse<https://t.co>\t\t<https://t.co>\t\tFalse" }, { "code": null, "e": 12394, "s": 12326, "text": "We can modify spaCy’s model to recognize hashtags as entire tokens." }, { "code": null, "e": 12674, "s": 12394, "text": "spaCy’s tokenizer can be modified (you can also build a custom tokenizer if you want!) by redefining its default rules. spaCy’s tokenizer prioritizes rules in the following order: token match pattern, prefix, suffix, infixes, URL, special cases (see How spaCy’s Tokenizer Works)." }, { "code": null, "e": 12886, "s": 12674, "text": "In our case, we’ll modify the tokenizer’s pattern matching regex pattern (read more about regex here: A simple intro to Regex with Python) by appending '#\\\\w+', which is a pattern for the hash symbol and a word." }, { "code": null, "e": 13531, "s": 12886, "text": "# We want to also keep #hashtags as a token, so we will modify the spaCy model's token_matchimport re# Retrieve the default token-matching regex patternre_token_match = spacy.tokenizer._get_regex_pattern(nlp.Defaults.token_match)# Add #hashtag patternre_token_match = f\"({re_token_match}|#\\\\w+)\"nlp.tokenizer.token_match = re.compile(re_token_match).match# Now let's try agains = \"2020 can't get any worse #ihate2020 @bestfriend <https://t.co>\"doc = nlp(s)# Let's look at the lemmas and is stopword of each tokenprint(f\"Token\\\\t\\\\tLemma\\\\t\\\\tStopword\")print(\"=\"*40)for token in doc: print(f\"{token}\\\\t\\\\t{token.lemma_}\\\\t\\\\t{token.is_stop}\")" }, { "code": null, "e": 13548, "s": 13531, "text": "Our code prints:" }, { "code": null, "e": 13797, "s": 13548, "text": "Token\t\tLemma\t\tStopword========================================2020\t\t2020\t\tFalseca\t\tcan\t\tTruen't\t\tnot\t\tTrueget\t\tget\t\tTrueany\t\tany\t\tTrueworse\t\tbad\t\tFalse#ihate2020\t\t#ihate2020\t\tFalse@bestfriend\t\t@bestfriend\t\tFalse<https://t.co>\t\t<https://t.co>\t\tFalse" }, { "code": null, "e": 13985, "s": 13797, "text": "We can then proceed to create a preprocessing algorithm, and put it in a function so it can be called on every tweet in the training set. In the following preprocess function, each tweet:" }, { "code": null, "e": 14010, "s": 13985, "text": "Is changed to lower case" }, { "code": null, "e": 14053, "s": 14010, "text": "Is tokenized with our modified spaCy model" }, { "code": null, "e": 14112, "s": 14053, "text": "Has its lemmas of tokens set unioned with our features set" }, { "code": null, "e": 14181, "s": 14112, "text": "Has its bag-of-words representation constructed in a dictionary freq" }, { "code": null, "e": 14225, "s": 14181, "text": "Has its hashtags, mentions and URLs counted" }, { "code": null, "e": 15423, "s": 14225, "text": "# Create a pre-process function for each tweetdef preprocess(s, nlp, features): \"\"\" Given string s, spaCy model nlp, and set features (lemmas encountered), pre-process s and return updated features and bag-of-words representation dict freq - changes s to lower-case - tokenize s using nlp to create a doc - update features with lemmas encountered in s - create bag-of-words representation in dict type freq, including counts for hashtags, mentions and URLs \"\"\"# To lowercase s = s.lower()# Creating a doc with spaCy doc = nlp(s) lemmas = [] for token in doc: lemmas.append(token.lemma_)# Union between lemmas and our features set features |= set(lemmas)# Constructing a bag of words for the tweet freq = {'#':0,'@':0,'URL':0} for word in lemmas: freq[str(word)] = 0 for token in doc: if '#' in str(token): freq['#'] += 1 # Count number of hashtags, regardless of hashtag if '@' in str(token): freq['@'] += 1 # Count number of mentions, regardless of mention if 'http://' in str(token): freq['URL'] += 1 # Count number of URLs, regardless of URL freq[str(token.lemma_)] += 1 return features, freq" }, { "code": null, "e": 15839, "s": 15423, "text": "We’ll create a copy our de-duplicated data as a best practice, so that any pre-processing changes does not affect the original state of our training data. Then, we will initialize a python set features, which will contain all features of each tweet. In addition to all lemmas encountered via tokenization of each tweet, features will include number of hashtags (#), number of mentions (@), and number of URLs (URL)." }, { "code": null, "e": 15974, "s": 15839, "text": "preprocess_df = df # Duplicate for preprocessingfeatures = set({'#','@','URL'}) # Using set feature to contain all words (lemmas) seen" }, { "code": null, "e": 16220, "s": 15974, "text": "Using our preprocess function, we'll preprocess every tweet, updating features each time with new lemmas seen. With each tweet, the tweet's bag of words representation freq is also appended to an array of bag of words for each tweet (bow_array)." }, { "code": null, "e": 16508, "s": 16220, "text": "# Array bow_array of bow representations for each tweet;# bow_array[i] is the bow representation for tweet id (i+1)bow_array = [] for i in range(len(preprocess_df)): features, freq = preprocess(preprocess_df.iloc[i]['text'],nlp,features) bow_array.append(freq)len(bow_array) # 7561" }, { "code": null, "e": 16652, "s": 16508, "text": "With all lemmas encountered across all tweets collected in features, we can create a dataframe bow to represent the features of all the tweets." }, { "code": null, "e": 16862, "s": 16652, "text": "# Create dataframe for bag of words representation for each tweetbow = pd.DataFrame('0', columns=features,index=range(len(preprocess_df)))bow['id']=preprocess_df.indexbow.set_index('id',drop=True,inplace=True)" }, { "code": null, "e": 16933, "s": 16862, "text": "Now, let’s update our dataframe with the feature values of each tweet." }, { "code": null, "e": 17100, "s": 16933, "text": "# Update bow[i] with bag-of-words freq of the tweet id (i+1)for i in range(len(preprocess_df)): freq = bow_array[i] for f in freq: bow.loc[i+1,f]=freq[f]" }, { "code": null, "e": 17589, "s": 17100, "text": "Finally, we will join our training data dataframe with our bag-of-words. pandas Dataframe’s join method allows us to add columns from one dataframe to another for rows where the index matches. Note that we append '_data' as a suffix to all columns from the 'left' dataframe, which is preprocess_df. This is to avoid conflicts between the keyword given as part of the training data, and 'keyword' as a lemma-token-feature. Remember to save the preprocessed .csv file for easier next steps!" }, { "code": null, "e": 17931, "s": 17589, "text": "# Join bag-of-words representation to train dataframe# Append _data suffix to 'keyword','location','text','target' for features that are not lemma tokenspreprocess_df = preprocess_df.join(bow,lsuffix='_data')# Saving bag-of-words representation for collaboratorspreprocess_df.to_csv(\"data/train_preprocessed.csv\",index=True,index_label='id')" }, { "code": null, "e": 18219, "s": 17931, "text": "Now that we’ve pre-processed our data, there’s just one last step before we can jump into using it to train our model of choice. We have split it, stratified according to the distribution of classes, into training and validation sets. Using train_test_split from sklearn.model_selection:" }, { "code": null, "e": 18665, "s": 18219, "text": "from sklearn.model_selection import train_test_split# stratify=y creates a balanced validation sety = preprocess_df['target_data']df_train, df_val = train_test_split(preprocess_df, test_size=0.10, random_state=101, stratify=y)# Saving csv files for collaboratorsdf_train.to_csv(\"data/train_preprocessed_split.csv\",index=True)df_val.to_csv(\"data/val_preprocessed_split.csv\",index=True)print(df_train.shape, df_val.shape)(6851, 21330) (762, 21330)" }, { "code": null, "e": 18708, "s": 18665, "text": "Just to be sure, we can check our balance." }, { "code": null, "e": 19074, "s": 18708, "text": "# Checking balanceprint(f\"\"\"Ratio of target=1 to target=0 tweets in:\\\\n Original data set = {np.sum(preprocess_df['target_data']==1)/np.sum(preprocess_df['target_data']==0)},\\\\nTraining data set = {np.sum(df_train['target_data']==1)/np.sum(df_train['target_data']==0)},\\\\nValidation data set = {np.sum(df_val['target_data']==1)/np.sum(df_val['target_data']==0)}\"\"\")" }, { "code": null, "e": 19087, "s": 19074, "text": "This prints:" }, { "code": null, "e": 19247, "s": 19087, "text": "Ratio of target=1 to target=0 tweets in: Original data set = 0.7533394748963611,Training data set = 0.7535193242897363,Validation data set = 0.7517241379310344" }, { "code": null, "e": 19745, "s": 19247, "text": "If you have seen other NLP pre-processing tutorials, you’ll find that a lot of their steps have been included as considerations, but not implemented here. These include removing punctuations, numbers, and stop words. However, our training dataset is small, and these steps could remove information valuable in the context of tweets and the challenge. Hence, rather than eliminate these data at the pre-processing stage, we have left them as possible ways to tune the hyper-parameters of our model." }, { "code": null, "e": 20333, "s": 19745, "text": "Through this tutorial, we have pre-processed tweets into their bag-of-words representation. However, you may choose to go a few steps further with Term Frequency — Inverse Document Frequency (TFIDF). TF-IDF stands for “Term,Information Retrieval and Text Mining, which penalizes terms that appear too often (as they become less discriminatory as features), or word vectors, which also numerically account for the word’s context and semantics. Word vectors encoding will result in better performance than TFIDF encoding, which will result in better performance than bag-of-words encoding." }, { "code": null, "e": 20655, "s": 20333, "text": "We have ignored location and keyword in this tutorial, focusing entirely on tweets. You could consider encoding location by similarity, accounting for different spellings of the same place (e.g. USA vs U.S.), and missing values. You can also weight keywords heavier and see how that affects the performance of your model." }, { "code": null, "e": 21011, "s": 20655, "text": "Lastly, there may be valuable information in the URLs that we are missing out. Given that they are in shortened form, we are unable to extract the domain name or page content from the text data alone. You could consider building an algorithm to visit the site and extract the domain name, as well as scrape relevant elements on the page (e.g. page title)." }, { "code": null, "e": 21414, "s": 21011, "text": "Now that we have performed basic pre-processing our dataset, we can move forward in two possible directions. You can either continue on to advanced pre-processing by performing spell checks and correction with Pyspellchecker and Mordecai, or try out and evaluate candidate machine learning models! Possible models for such classification problems include logistic regression, neural networks, and SVMs." }, { "code": null, "e": 21492, "s": 21414, "text": "[1] Kaggle, Disaster tweets classification challenge on Kaggle (2020), Kaggle" }, { "code": null, "e": 21588, "s": 21492, "text": "[2] D. Becker and M. Leonard, Intro to NLP (n.d.), Natural Language Processing Course on Kaggle" }, { "code": null, "e": 21702, "s": 21588, "text": "[3] D. Becker and M. Leonard, Text Classification with SpaCy (n.d.), Natural Language Processing Course on Kaggle" }, { "code": null, "e": 21788, "s": 21702, "text": "[4] Yse, D. L. Your Guide to Natural Language Processing (2019), Towards Data Science" } ]
TensorFlow - TFLearn And Its Installation
TFLearn can be defined as a modular and transparent deep learning aspect used in TensorFlow framework. The main motive of TFLearn is to provide a higher level API to TensorFlow for facilitating and showing up new experiments. Consider the following important features of TFLearn − TFLearn is easy to use and understand. TFLearn is easy to use and understand. It includes easy concepts to build highly modular network layers, optimizers and various metrics embedded within them. It includes easy concepts to build highly modular network layers, optimizers and various metrics embedded within them. It includes full transparency with TensorFlow work system. It includes full transparency with TensorFlow work system. It includes powerful helper functions to train the built in tensors which accept multiple inputs, outputs and optimizers. It includes powerful helper functions to train the built in tensors which accept multiple inputs, outputs and optimizers. It includes easy and beautiful graph visualization. It includes easy and beautiful graph visualization. The graph visualization includes various details of weights, gradients and activations. The graph visualization includes various details of weights, gradients and activations. Install TFLearn by executing the following command − pip install tflearn Upon execution of the above code, the following output will be generated − The following illustration shows the implementation of TFLearn with Random Forest classifier − from __future__ import division, print_function, absolute_import #TFLearn module implementation import tflearn from tflearn.estimators import RandomForestClassifier # Data loading and pre-processing with respect to dataset import tflearn.datasets.mnist as mnist X, Y, testX, testY = mnist.load_data(one_hot = False) m = RandomForestClassifier(n_estimators = 100, max_nodes = 1000) m.fit(X, Y, batch_size = 10000, display_step = 10) print("Compute the accuracy on train data:") print(m.evaluate(X, Y, tflearn.accuracy_op)) print("Compute the accuracy on test set:") print(m.evaluate(testX, testY, tflearn.accuracy_op)) print("Digits for test images id 0 to 5:") print(m.predict(testX[:5])) print("True digits:") print(testY[:5]) 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 29 Lectures 3.5 hours Mohammad Nauman 82 Lectures 4 hours Anis Koubaa Print Add Notes Bookmark this page
[ { "code": null, "e": 2541, "s": 2315, "text": "TFLearn can be defined as a modular and transparent deep learning aspect used in TensorFlow framework. The main motive of TFLearn is to provide a higher level API to TensorFlow for facilitating and showing up new experiments." }, { "code": null, "e": 2596, "s": 2541, "text": "Consider the following important features of TFLearn −" }, { "code": null, "e": 2635, "s": 2596, "text": "TFLearn is easy to use and understand." }, { "code": null, "e": 2674, "s": 2635, "text": "TFLearn is easy to use and understand." }, { "code": null, "e": 2793, "s": 2674, "text": "It includes easy concepts to build highly modular network layers, optimizers and various metrics embedded within them." }, { "code": null, "e": 2912, "s": 2793, "text": "It includes easy concepts to build highly modular network layers, optimizers and various metrics embedded within them." }, { "code": null, "e": 2971, "s": 2912, "text": "It includes full transparency with TensorFlow work system." }, { "code": null, "e": 3030, "s": 2971, "text": "It includes full transparency with TensorFlow work system." }, { "code": null, "e": 3152, "s": 3030, "text": "It includes powerful helper functions to train the built in tensors which accept multiple inputs, outputs and optimizers." }, { "code": null, "e": 3274, "s": 3152, "text": "It includes powerful helper functions to train the built in tensors which accept multiple inputs, outputs and optimizers." }, { "code": null, "e": 3326, "s": 3274, "text": "It includes easy and beautiful graph visualization." }, { "code": null, "e": 3378, "s": 3326, "text": "It includes easy and beautiful graph visualization." }, { "code": null, "e": 3466, "s": 3378, "text": "The graph visualization includes various details of weights, gradients and activations." }, { "code": null, "e": 3554, "s": 3466, "text": "The graph visualization includes various details of weights, gradients and activations." }, { "code": null, "e": 3607, "s": 3554, "text": "Install TFLearn by executing the following command −" }, { "code": null, "e": 3628, "s": 3607, "text": "pip install tflearn\n" }, { "code": null, "e": 3703, "s": 3628, "text": "Upon execution of the above code, the following output will be generated −" }, { "code": null, "e": 3798, "s": 3703, "text": "The following illustration shows the implementation of TFLearn with Random Forest classifier −" }, { "code": null, "e": 4533, "s": 3798, "text": "from __future__ import division, print_function, absolute_import\n\n#TFLearn module implementation\nimport tflearn\nfrom tflearn.estimators import RandomForestClassifier\n\n# Data loading and pre-processing with respect to dataset\nimport tflearn.datasets.mnist as mnist\nX, Y, testX, testY = mnist.load_data(one_hot = False)\n\nm = RandomForestClassifier(n_estimators = 100, max_nodes = 1000)\nm.fit(X, Y, batch_size = 10000, display_step = 10)\n\nprint(\"Compute the accuracy on train data:\")\nprint(m.evaluate(X, Y, tflearn.accuracy_op))\n\nprint(\"Compute the accuracy on test set:\")\nprint(m.evaluate(testX, testY, tflearn.accuracy_op))\n\nprint(\"Digits for test images id 0 to 5:\")\nprint(m.predict(testX[:5]))\n\nprint(\"True digits:\")\nprint(testY[:5])" }, { "code": null, "e": 4566, "s": 4533, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 4588, "s": 4566, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4621, "s": 4588, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 4643, "s": 4621, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4676, "s": 4643, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 4698, "s": 4676, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4731, "s": 4698, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 4753, "s": 4731, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4788, "s": 4753, "text": "\n 29 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4805, "s": 4788, "text": " Mohammad Nauman" }, { "code": null, "e": 4838, "s": 4805, "text": "\n 82 Lectures \n 4 hours \n" }, { "code": null, "e": 4851, "s": 4838, "text": " Anis Koubaa" }, { "code": null, "e": 4858, "s": 4851, "text": " Print" }, { "code": null, "e": 4869, "s": 4858, "text": " Add Notes" } ]
Create and customize boxplots with Python’s Matplotlib to get lots of insights from your data | by Carolina Bento | Towards Data Science
Boxplots are underrated. They are jam-packed with insights about the underlying distribution, because they condense lots of information about your data into a small visualization. In this article you see how Boxplots are great tools to: Understand the spread of the data. Spot outliers. Compare distributions, and how small tweaks in the boxplot visualization make it easier spot differences between distributions. During exploratory data analysis, boxplots can be a great complement to histograms. With histograms it’s easy to see the shape and trends in a distribution. Because histograms highlight how frequently each data point occurs in the distribution. Boxplots don’t focus directly on frequency, but instead on the range of values in the distribution. We are used to think in terms of frequency and comparing proportions. That’s why we’re so comfortable interpreting the insights of an histogram, where we can spot the values where most data is concentrated around, and we can see the shape of the distribution. With a boxplot, we can extract the same insights as with an histogram. And while we can visualize the shape of the distribution with an histogram, a boxplot highlights the summary metrics that give the distribution its shape. The summary metrics we can extract from a boxplot are: Quantiles, specifically the first and third quantiles, which correspond to the 25th and 75th percentiles. Median, the mid-point in the distribution, which also corresponds to the 50th percentile. Interquartile range (IQR), the width between the third and first quantiles. Expressed mathematically, we have IQR = Q3 — Q1. Min, minimum value in the dataset excluding outliers, which corresponds to Q1–1.5xIQR. Max, maximum value in the dataset, excluding outliers, which corresponds to Q3+ 1.5xIQR. Visualized in a boxplot outliers typically show up as circles. But as you’ll see in the next section, you can customize how outliers are represented 😀 If your dataset has outliers, it will be easy to spot them with a boxplot. There are different methods to determine that a data point is an outlier. The most widely known is the 1.5xIQR rule. Outliers are extreme observations in the dataset. So a rule of thumb to determine if a data point is extreme is to compare it against the interquartile range. It makes sense to use the interquartile range (IQR) to spot outliers. The IQR is the range of values between the first and third quartiles, i.e., 25th and 75th percentiles, so it will include the majority of the data points in the dataset. But why 1.5 times the interquartile range? This is related to an important characteristic of the Normal Distribution known as the 68–95–99 rule. With the 68–95–99 rule, we know that: 68% of the data is within one standard deviation above or below the mean, 95% of the data is within two standard deviations from the mean, 99.7% of the data is within three standard deviations from the mean. Only very few data points will be beyond three standard deviations from the mean, more precisely, only 0.3% of the data points. So any data point that is seen farther than three standard deviations is considered extreme. To check if a data point is an outlier and check if it falls farther than three standard deviations, we calculate: Q1–1.5xIQR, Q3 + 1.5xIQR. These represent the lower and upper bounds of the area in the distribution that is not considered extreme. Which ends up being approximately 3 standard deviations from the mean. The multiplying factor is 1.5, because any number greater than that would result in a range bigger than 3 standard deviations. So, mathematicians settled in a number in the middle. Any data point lower than the lower bound or greater than the upper bound is an outlier: (data point value) < Q1–1.5xIQR, then it’s an outlier. (data point value) > Q3 + 1.5xIQR, then it’s an outlier. Boxplots are also a great tool to compare different distributions. Let’s compare the distributions of petal length for flowers in the Iris dataset. Here’s how you can create this plot. import numpy as npimport pandas as pdfrom sklearn import datasetsimport matplotlib.pyplot as plt# Load Iris datasetiris = datasets.load_iris()# Preparing Iris datasetiris_data = pd.DataFrame(data=iris.data, columns=['sepal_length', 'sepal_width', 'petal_length', 'petal_width'])iris_target = pd.DataFrame(data=iris.target, columns=['species'])iris_df = pd.concat([iris_data, iris_target], axis=1)# Add species nameiris_df['species_name'] = np.where(iris_df['species'] == 0, 'Setosa', None)iris_df['species_name'] = np.where(iris_df['species'] == 1, 'Versicolor', iris_df['species_name'])iris_df['species_name'] = np.where(iris_df['species'] == 2, 'Virginica', iris_df['species_name'])# Prepare petal length by species datasetssetosa_petal_length = iris_df[iris_df['species_name'] == 'Setosa']['petal_length']versicolor_petal_length = iris_df[iris_df['species_name'] == 'Versicolor']['petal_length']virginica_petal_length = iris_df[iris_df['species_name'] == 'Virginica']['petal_length']# Visualize petal length distribution for all speciesfig, ax = plt.subplots(figsize=(12, 7))# Remove top and right borderax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)# Remove y-axis tick marksax.yaxis.set_ticks_position('none')# Add major gridlines in the y-axisax.grid(color='grey', axis='y', linestyle='-', linewidth=0.25, alpha=0.5)# Set plot titleax.set_title('Distribution of petal length by species')# Set species names as labels for the boxplotdataset = [setosa_petal_length, versicolor_petal_length, virginica_petal_length]labels = iris_df['species_name'].unique()ax.boxplot(dataset, labels=labels)plt.show() We can extract a few insights from this plot: Iris Setosa has a much smaller petal length than Iris Versicolor and Virginica. It ranges from approximately 1 to 2 centimeters. The range of petal length of Iris Virginica is bigger than both the ranges of values for Iris Setosa and Versicolor. We can see that from how tall the box is for Iris Virginica compared to the other two. Both Iris Setosa and Veriscolor have outliers. We can also confirm these insights by looking at the summary metrics of each distribution. And here’s how you can compute these metrics. def get_summary_statistics(dataset): mean = np.round(np.mean(dataset), 2) median = np.round(np.median(dataset), 2) min_value = np.round(dataset.min(), 2) max_value = np.round(dataset.max(), 2) quartile_1 = np.round(dataset.quantile(0.25), 2) quartile_3 = np.round(dataset.quantile(0.75), 2) # Interquartile range iqr = np.round(quartile_3 - quartile_1, 2) print('Min: %s' % min_value) print('Mean: %s' % mean) print('Max: %s' % max_value) print('25th percentile: %s' % quartile_1) print('Median: %s' % median) print('75th percentile: %s' % quartile_3) print('Interquartile range (IQR): %s' % iqr) print('Setosa summary statistics')print('\n\nSetosa summary statistics')get_summary_statistics(setosa_petal_length)print('\n\nVersicolor summary statistics')get_summary_statistics(versicolor_petal_length)print('\n\nVirginica summary statistics')get_summary_statistics(virginica_petal_length) At first glance, it’s hard to distinguish between the boxplots of the different species. The labels at the bottom are the only visual clue that we’re comparing distributions. We can use the properties of the boxplot to customize each box. Since properties are applies to all the data that is given to the boxplot method, we can’t take the approach of the last plot and use an array with the petal length for each species as an input. We’ll have to plot the petal length for each species and applies properties to each one of them. We’re going to use the following parameters: positions: position of the boxplot in the plot area. We don’t want to plot each species’ boxplot on top of each other, so we use this to set the position in the x-axis where each boxplot will be drawn. medianprops: dictionary of properties applied to median line inside the boxplot. whiskerprops: dictionary of properties applied to the whiskers. capprops: dictionary of properties applied to the caps on the whiskers. flierprops: dictionary of properties applied to outliers. There are other several properties we can customize. In this example I’m going to just add a different color for each of the boxplots, so it’s easier to see that we’re visualizing different distributions. fig, ax = plt.subplots(figsize=(12, 7))# Remove top and right borderax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)# Remove y-axis tick marksax.yaxis.set_ticks_position('none')# Set plot titleax.set_title('Distribution of petal length by species')# Add major gridlines in the y-axisax.grid(color='grey', axis='y', linestyle='-', linewidth=0.25, alpha=0.5)# Set species names as labels for the boxplotdataset = [setosa_petal_length, versicolor_petal_length, virginica_petal_length]labels = iris_df['species_name'].unique()# Set the colors for each distributioncolors = ['#73020C', '#426A8C', '#D94D1A']colors_setosa = dict(color=colors[0])colors_versicolor = dict(color=colors[1])colors_virginica = dict(color=colors[2])# We want to apply different properties to each species, so we're going to plot one boxplot# for each species and set their properties individually# positions: position of the boxplot in the plot area# medianprops: dictionary of properties applied to median line# whiskerprops: dictionary of properties applied to the whiskers# capprops: dictionary of properties applied to the caps on the whiskers# flierprops: dictionary of properties applied to outliersax.boxplot(dataset[0], positions=[1], labels=[labels[0]], boxprops=colors_setosa, medianprops=colors_setosa, whiskerprops=colors_setosa, capprops=colors_setosa, flierprops=dict(markeredgecolor=colors[0]))ax.boxplot(dataset[1], positions=[2], labels=[labels[1]], boxprops=colors_versicolor, medianprops=colors_versicolor, whiskerprops=colors_versicolor, capprops=colors_versicolor, flierprops=dict(markeredgecolor=colors[1]))ax.boxplot(dataset[2], positions=[3], labels=[labels[2]], boxprops=colors_virginica, medianprops=colors_virginica, whiskerprops=colors_virginica, capprops=colors_virginica, flierprops=dict(markeredgecolor=colors[2]))plt.show() That’s it! You can use boxplots to explore your data and customize your visualizations so it’s easier to extract insights. Thanks for reading!
[ { "code": null, "e": 351, "s": 171, "text": "Boxplots are underrated. They are jam-packed with insights about the underlying distribution, because they condense lots of information about your data into a small visualization." }, { "code": null, "e": 408, "s": 351, "text": "In this article you see how Boxplots are great tools to:" }, { "code": null, "e": 443, "s": 408, "text": "Understand the spread of the data." }, { "code": null, "e": 458, "s": 443, "text": "Spot outliers." }, { "code": null, "e": 586, "s": 458, "text": "Compare distributions, and how small tweaks in the boxplot visualization make it easier spot differences between distributions." }, { "code": null, "e": 670, "s": 586, "text": "During exploratory data analysis, boxplots can be a great complement to histograms." }, { "code": null, "e": 831, "s": 670, "text": "With histograms it’s easy to see the shape and trends in a distribution. Because histograms highlight how frequently each data point occurs in the distribution." }, { "code": null, "e": 931, "s": 831, "text": "Boxplots don’t focus directly on frequency, but instead on the range of values in the distribution." }, { "code": null, "e": 1191, "s": 931, "text": "We are used to think in terms of frequency and comparing proportions. That’s why we’re so comfortable interpreting the insights of an histogram, where we can spot the values where most data is concentrated around, and we can see the shape of the distribution." }, { "code": null, "e": 1472, "s": 1191, "text": "With a boxplot, we can extract the same insights as with an histogram. And while we can visualize the shape of the distribution with an histogram, a boxplot highlights the summary metrics that give the distribution its shape. The summary metrics we can extract from a boxplot are:" }, { "code": null, "e": 1578, "s": 1472, "text": "Quantiles, specifically the first and third quantiles, which correspond to the 25th and 75th percentiles." }, { "code": null, "e": 1668, "s": 1578, "text": "Median, the mid-point in the distribution, which also corresponds to the 50th percentile." }, { "code": null, "e": 1793, "s": 1668, "text": "Interquartile range (IQR), the width between the third and first quantiles. Expressed mathematically, we have IQR = Q3 — Q1." }, { "code": null, "e": 1880, "s": 1793, "text": "Min, minimum value in the dataset excluding outliers, which corresponds to Q1–1.5xIQR." }, { "code": null, "e": 1969, "s": 1880, "text": "Max, maximum value in the dataset, excluding outliers, which corresponds to Q3+ 1.5xIQR." }, { "code": null, "e": 2120, "s": 1969, "text": "Visualized in a boxplot outliers typically show up as circles. But as you’ll see in the next section, you can customize how outliers are represented 😀" }, { "code": null, "e": 2312, "s": 2120, "text": "If your dataset has outliers, it will be easy to spot them with a boxplot. There are different methods to determine that a data point is an outlier. The most widely known is the 1.5xIQR rule." }, { "code": null, "e": 2471, "s": 2312, "text": "Outliers are extreme observations in the dataset. So a rule of thumb to determine if a data point is extreme is to compare it against the interquartile range." }, { "code": null, "e": 2711, "s": 2471, "text": "It makes sense to use the interquartile range (IQR) to spot outliers. The IQR is the range of values between the first and third quartiles, i.e., 25th and 75th percentiles, so it will include the majority of the data points in the dataset." }, { "code": null, "e": 2856, "s": 2711, "text": "But why 1.5 times the interquartile range? This is related to an important characteristic of the Normal Distribution known as the 68–95–99 rule." }, { "code": null, "e": 2894, "s": 2856, "text": "With the 68–95–99 rule, we know that:" }, { "code": null, "e": 2968, "s": 2894, "text": "68% of the data is within one standard deviation above or below the mean," }, { "code": null, "e": 3033, "s": 2968, "text": "95% of the data is within two standard deviations from the mean," }, { "code": null, "e": 3102, "s": 3033, "text": "99.7% of the data is within three standard deviations from the mean." }, { "code": null, "e": 3323, "s": 3102, "text": "Only very few data points will be beyond three standard deviations from the mean, more precisely, only 0.3% of the data points. So any data point that is seen farther than three standard deviations is considered extreme." }, { "code": null, "e": 3438, "s": 3323, "text": "To check if a data point is an outlier and check if it falls farther than three standard deviations, we calculate:" }, { "code": null, "e": 3450, "s": 3438, "text": "Q1–1.5xIQR," }, { "code": null, "e": 3464, "s": 3450, "text": "Q3 + 1.5xIQR." }, { "code": null, "e": 3642, "s": 3464, "text": "These represent the lower and upper bounds of the area in the distribution that is not considered extreme. Which ends up being approximately 3 standard deviations from the mean." }, { "code": null, "e": 3823, "s": 3642, "text": "The multiplying factor is 1.5, because any number greater than that would result in a range bigger than 3 standard deviations. So, mathematicians settled in a number in the middle." }, { "code": null, "e": 3912, "s": 3823, "text": "Any data point lower than the lower bound or greater than the upper bound is an outlier:" }, { "code": null, "e": 3967, "s": 3912, "text": "(data point value) < Q1–1.5xIQR, then it’s an outlier." }, { "code": null, "e": 4024, "s": 3967, "text": "(data point value) > Q3 + 1.5xIQR, then it’s an outlier." }, { "code": null, "e": 4091, "s": 4024, "text": "Boxplots are also a great tool to compare different distributions." }, { "code": null, "e": 4172, "s": 4091, "text": "Let’s compare the distributions of petal length for flowers in the Iris dataset." }, { "code": null, "e": 4209, "s": 4172, "text": "Here’s how you can create this plot." }, { "code": null, "e": 5875, "s": 4209, "text": "import numpy as npimport pandas as pdfrom sklearn import datasetsimport matplotlib.pyplot as plt# Load Iris datasetiris = datasets.load_iris()# Preparing Iris datasetiris_data = pd.DataFrame(data=iris.data, columns=['sepal_length', 'sepal_width', 'petal_length', 'petal_width'])iris_target = pd.DataFrame(data=iris.target, columns=['species'])iris_df = pd.concat([iris_data, iris_target], axis=1)# Add species nameiris_df['species_name'] = np.where(iris_df['species'] == 0, 'Setosa', None)iris_df['species_name'] = np.where(iris_df['species'] == 1, 'Versicolor', iris_df['species_name'])iris_df['species_name'] = np.where(iris_df['species'] == 2, 'Virginica', iris_df['species_name'])# Prepare petal length by species datasetssetosa_petal_length = iris_df[iris_df['species_name'] == 'Setosa']['petal_length']versicolor_petal_length = iris_df[iris_df['species_name'] == 'Versicolor']['petal_length']virginica_petal_length = iris_df[iris_df['species_name'] == 'Virginica']['petal_length']# Visualize petal length distribution for all speciesfig, ax = plt.subplots(figsize=(12, 7))# Remove top and right borderax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)# Remove y-axis tick marksax.yaxis.set_ticks_position('none')# Add major gridlines in the y-axisax.grid(color='grey', axis='y', linestyle='-', linewidth=0.25, alpha=0.5)# Set plot titleax.set_title('Distribution of petal length by species')# Set species names as labels for the boxplotdataset = [setosa_petal_length, versicolor_petal_length, virginica_petal_length]labels = iris_df['species_name'].unique()ax.boxplot(dataset, labels=labels)plt.show()" }, { "code": null, "e": 5921, "s": 5875, "text": "We can extract a few insights from this plot:" }, { "code": null, "e": 6050, "s": 5921, "text": "Iris Setosa has a much smaller petal length than Iris Versicolor and Virginica. It ranges from approximately 1 to 2 centimeters." }, { "code": null, "e": 6254, "s": 6050, "text": "The range of petal length of Iris Virginica is bigger than both the ranges of values for Iris Setosa and Versicolor. We can see that from how tall the box is for Iris Virginica compared to the other two." }, { "code": null, "e": 6301, "s": 6254, "text": "Both Iris Setosa and Veriscolor have outliers." }, { "code": null, "e": 6392, "s": 6301, "text": "We can also confirm these insights by looking at the summary metrics of each distribution." }, { "code": null, "e": 6438, "s": 6392, "text": "And here’s how you can compute these metrics." }, { "code": null, "e": 7379, "s": 6438, "text": "def get_summary_statistics(dataset): mean = np.round(np.mean(dataset), 2) median = np.round(np.median(dataset), 2) min_value = np.round(dataset.min(), 2) max_value = np.round(dataset.max(), 2) quartile_1 = np.round(dataset.quantile(0.25), 2) quartile_3 = np.round(dataset.quantile(0.75), 2) # Interquartile range iqr = np.round(quartile_3 - quartile_1, 2) print('Min: %s' % min_value) print('Mean: %s' % mean) print('Max: %s' % max_value) print('25th percentile: %s' % quartile_1) print('Median: %s' % median) print('75th percentile: %s' % quartile_3) print('Interquartile range (IQR): %s' % iqr) print('Setosa summary statistics')print('\\n\\nSetosa summary statistics')get_summary_statistics(setosa_petal_length)print('\\n\\nVersicolor summary statistics')get_summary_statistics(versicolor_petal_length)print('\\n\\nVirginica summary statistics')get_summary_statistics(virginica_petal_length)" }, { "code": null, "e": 7554, "s": 7379, "text": "At first glance, it’s hard to distinguish between the boxplots of the different species. The labels at the bottom are the only visual clue that we’re comparing distributions." }, { "code": null, "e": 7813, "s": 7554, "text": "We can use the properties of the boxplot to customize each box. Since properties are applies to all the data that is given to the boxplot method, we can’t take the approach of the last plot and use an array with the petal length for each species as an input." }, { "code": null, "e": 7910, "s": 7813, "text": "We’ll have to plot the petal length for each species and applies properties to each one of them." }, { "code": null, "e": 7955, "s": 7910, "text": "We’re going to use the following parameters:" }, { "code": null, "e": 8157, "s": 7955, "text": "positions: position of the boxplot in the plot area. We don’t want to plot each species’ boxplot on top of each other, so we use this to set the position in the x-axis where each boxplot will be drawn." }, { "code": null, "e": 8238, "s": 8157, "text": "medianprops: dictionary of properties applied to median line inside the boxplot." }, { "code": null, "e": 8302, "s": 8238, "text": "whiskerprops: dictionary of properties applied to the whiskers." }, { "code": null, "e": 8374, "s": 8302, "text": "capprops: dictionary of properties applied to the caps on the whiskers." }, { "code": null, "e": 8432, "s": 8374, "text": "flierprops: dictionary of properties applied to outliers." }, { "code": null, "e": 8637, "s": 8432, "text": "There are other several properties we can customize. In this example I’m going to just add a different color for each of the boxplots, so it’s easier to see that we’re visualizing different distributions." }, { "code": null, "e": 10524, "s": 8637, "text": "fig, ax = plt.subplots(figsize=(12, 7))# Remove top and right borderax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)# Remove y-axis tick marksax.yaxis.set_ticks_position('none')# Set plot titleax.set_title('Distribution of petal length by species')# Add major gridlines in the y-axisax.grid(color='grey', axis='y', linestyle='-', linewidth=0.25, alpha=0.5)# Set species names as labels for the boxplotdataset = [setosa_petal_length, versicolor_petal_length, virginica_petal_length]labels = iris_df['species_name'].unique()# Set the colors for each distributioncolors = ['#73020C', '#426A8C', '#D94D1A']colors_setosa = dict(color=colors[0])colors_versicolor = dict(color=colors[1])colors_virginica = dict(color=colors[2])# We want to apply different properties to each species, so we're going to plot one boxplot# for each species and set their properties individually# positions: position of the boxplot in the plot area# medianprops: dictionary of properties applied to median line# whiskerprops: dictionary of properties applied to the whiskers# capprops: dictionary of properties applied to the caps on the whiskers# flierprops: dictionary of properties applied to outliersax.boxplot(dataset[0], positions=[1], labels=[labels[0]], boxprops=colors_setosa, medianprops=colors_setosa, whiskerprops=colors_setosa, capprops=colors_setosa, flierprops=dict(markeredgecolor=colors[0]))ax.boxplot(dataset[1], positions=[2], labels=[labels[1]], boxprops=colors_versicolor, medianprops=colors_versicolor, whiskerprops=colors_versicolor, capprops=colors_versicolor, flierprops=dict(markeredgecolor=colors[1]))ax.boxplot(dataset[2], positions=[3], labels=[labels[2]], boxprops=colors_virginica, medianprops=colors_virginica, whiskerprops=colors_virginica, capprops=colors_virginica, flierprops=dict(markeredgecolor=colors[2]))plt.show()" }, { "code": null, "e": 10647, "s": 10524, "text": "That’s it! You can use boxplots to explore your data and customize your visualizations so it’s easier to extract insights." } ]
Getting Started with Facebook Prophet | by Greg Rafferty | Towards Data Science
This post contains an excerpt from my new book all about Facebook Prophet. The book is available for purchase on Amazon. The full contents of the book are listed at the end of this post! If you find this article useful and would like to use Prophet to improve your forecasts, please consider buying the full book at https://amzn.to/373oIcf. The longest record of direct measurements of CO­2 in the atmosphere was started in March of 1958 by Charles David Keeling of the Scripps Institution of Oceanography. Keeling was based in La Jolla, California, but had received permission from the National Oceanic and Atmospheric Administration (NOAA) to use their facility located two miles above sea level on the northern slope of Mauna Loa, a volcano on the island of Hawaii, to collect carbon dioxide samples. At that elevation, Keeling’s measurements would be unaffected by local releases of CO2 such as by nearby factories. In 1961, Keeling published the data he had collected thus far, establishing that there was strong seasonal variation in CO2 levels and that they were rising steadily, a trend that later became known as the Keeling Curve. By May 1974, the NOAA began their own parallel measurements and have continued since then. The keeling curve graph is as follows: With its seasonality and increasing trend, this curve makes a good candidate to try out Prophet. This data set contains over 19,000 daily observations across 53 years. The unit of measurement for CO2 is PPM, or parts per million, a measure of CO2 molecules per million molecules of air. To begin our model, we need to import the necessary libraries, pandas and Matplotlib, and import the Prophet class from the fbprophet package. import pandas as pdimport matplotlib.pyplot as pltfrom fbprophet import Prophet As input, Prophet always requires a pandas DataFrame with two columns: ds, for datestamp, should be a datestamp or timestamp column in a format expected by pandas. y, a numeric column containing the measurement we wish to forecast. Here, we use pandas to import the data, in this case a csv file [Note: This csv can be downloaded at https://git.io/JYG6T], and then load it into a DataFrame. Note that we also convert the ds column to a pandas datetime format, to ensure that Pandas is correctly identifying it as dates and not simply loading it as an alphanumeric string. df = pd.read_csv(‘co2-ppm-daily_csv.csv’)df[‘date’] = pd.to_datetime(df[‘date’])df.columns = [‘ds’, ‘y’] If you’re familiar with the scikit-learn (sklearn) package, you’ll feel right at home in Prophet because it was designed to operate in a similar way. Prophet follows the sklearn paradigm of first creating an instance of the model class before calling the fit and predict methods. model = Prophet()model.fit(df) In that single fit command, Prophet analyzed the data and isolated both the seasonality and trend without requiring us to specify any additional parameters. It has not yet made any future forecast though. To do that, we need to first make a DataFrame of future dates and then call the predict method. The make_future_dataframe method requires us to specify the number of days we intend to forecast out. In this case, we will choose ten years, or 365 days times 10. future = model.make_future_dataframe(periods=365 * 10)forecast = model.predict(future) At this point, the forecast DataFrame contains Prophet’s prediction for CO2 concentrations going ten years into the future. We will explore that DataFrame in a moment, but first let’s plot the data using Prophet’s plot functionality. The plot method is built upon Matplotlib; it requires a DataFrame output from the predict method (our forecast DataFrame in this example). We’re labeling the axes with the optional xlabel and ylabel arguments, but just sticking with the default for the optional figsize argument. Note that I am also adding a title using raw Matplotlib syntax; because the Prophet plot is built upon Matplotlib, anything you can do to a Matplotlib figure can be performed here as well. Also, don’t be confused by the odd ylabel text with the dollar signs; that just tells Matplotlib to use its own TeX-like engine to make the subscript in CO2. fig = model.plot(forecast, xlabel=’Date’, ylabel=r’CO$_2$ PPM’)plt.title(‘Daily Carbon Dioxide Levels Measured at Mauna Loa’)plt.show() The graph is as follows: And that’s it! In those 12 lines of code, we have arrived at our ten year forecast. Now, let’s take a look at that forecast DataFrame by displaying the first three rows (I’ve transposed it here, in order to better see the column names on the page) and learn how these values were used in the above chart: forecast.head(3).T After running that command, you should see the following table print out: The following is a description of each of the columns in the forecast DataFrame: ‘ds’ — Datestamp or timestamp which values in that row pertain to ‘trend’ — Value of the trend component alone ‘yhat_lower’ — Lower bound of the uncertainty interval around the final prediction ‘yhat_upper’ — Upper bound of the uncertainty interval around the final prediction ‘trend_lower’ — Lower bound of the uncertainty interval around the trend component ‘trend_upper’ — Upper bound of the uncertainty interval around the trend component ‘additive_terms’ — Combined value of all additive seasonalities ‘additive_terms_lower’ — Lower bound of the uncertainty interval around the additive seasonalities ‘additive_terms_upper’ — Upper bound of the uncertainty interval around the additive seasonalities ‘weekly’ — Value of the weekly seasonality component ‘weekly_lower’ — Lower bound of the uncertainty interval around the weekly component ‘weekly_upper’ — Upper bound of the uncertainty interval around the weekly component ‘yearly’ — Value of the yearly seasonality component ‘yearly_lower’ — Lower bound of the uncertainty interval around the yearly component ‘yearly_upper’ — Upper bound of the uncertainty interval around the yearly component ‘multiplicative_terms’ — Combined value of all multiplicative seasonalities ‘multiplicative_terms_lower’ — Lower bound of the uncertainty interval around the multiplicative seasonalities ‘multiplicative_terms_upper’ — Upper bound of the uncertainty interval around the multiplicative seasonalities ‘yhat’ — Final predicted value; a combination of ‘trend’, ‘multiplicative_terms’, and ‘additive_terms’ If the data contains a daily seasonality, then columns for ‘daily’, ‘daily_upper’, and ‘daily_lower’ will also be included, following the pattern established with the ‘weekly’ and ‘yearly’ columns. Later chapters will include discussion and examples of both the additive/multiplicative seasonalities and of the uncertainty intervals. In the forecast plot above, the black dots represent the actual recorded y values we fit on (those in the df[‘y’] column) whereas the solid line represents the calculated yhat values (the forecast[‘yhat’] column). Note that the solid line extends beyond the range of the black dots where we have forecasted into the future. The lighter shading notable around the solid line in the forecasted region represents the uncertainty interval, bound by forecast[‘yhat_lower’] and forecast[‘yhat_upper’]. Now let’s break down that forecast into its components. In Chapter 1, History and Development of Time Series Forecasting, Prophet was introduced as an additive regression model. Figures 1.4 and 1.5 showed how individual component curves for the trend and the different seasonalities are added together to create a more complex curve. The Prophet algorithm essentially does this in reverse; it takes a complex curve and decomposes it into its constituent parts. The first step towards greater control of a Prophet forecast is to understand these components so that they can be manipulated individually. Prophet provides a method plot_components to visualize these. Continuing on with our progress on the Mauna Loa model, plotting the components is as simple as running these commands: fig2 = model.plot_components(forecast)plt.show() As you can see in the output plot, Prophet has isolated three components in this data set: the trend, a weekly seasonality, and a yearly seasonality: The trend constantly increases but seems to have a steepening slope as time progresses — an acceleration of CO2 concentration in the atmosphere. The trend line also shows slim uncertainty intervals in the forecasted year. From this curve, we learn that atmospheric CO2 concentrations were about 320 PPM in 1965. This grew to about 400 by 2015 and we expect about 430 PPM by 2030. However, these exact numbers will vary depending upon the day of the week and the time of year, due to the existence of the seasonality effects. The weekly seasonality shows that by days of the week, values will vary by about 0.01 PPM — an insignificant amount and most likely due purely to noise and random chance. Indeed, intuition tells us that carbon dioxide levels (when measured far enough away from human activity, as they are on the high slopes of Mauna Loa) do not care much what day of the week it is and are unaffected by it. We will learn in Chapter 4, Seasonality, how to instruct Prophet not to fit a weekly seasonality, as is prudent in this case. In Chapter 10, Uncertainty Intervals, we will learn how to plot uncertainty for seasonality and ensure that a seasonality such as this can be ignored. Now looking at the yearly seasonality reveals that carbon dioxide rises throughout the winter and peaks in May or so, while falling in the summer with a trough in October. Measurements of carbon dioxide can be 3 PPM above or 3 PPM below what the trend alone would predict, based upon the time of year. If you refer back to the original data, in the Keeling Curve, you will be reminded that there was a very obvious cyclic nature to the curve, captured with this yearly seasonality. As simple as that model was, that is often all you need to make very accurate forecasts with Prophet! We used no additional parameters than the defaults and yet achieved very good results. This excerpt is from chapter 2 of Forecasting Time Series Data with Facebook Prophet available now on Amazon. The book has more than 250 pages of examples, lessons, and descriptions of every single aspect of Prophet and more than 10 instructive datasets are provided to help you learn how to perfect your forecasts by demonstrating Prophet functionality from the simple to the advanced with fully working code. The full book contains the following chapters: The History and Development of Time Series ForecastingGetting Started with Facebook ProphetNon-Daily DataSeasonalityHolidaysGrowth ModesTrend ChangepointsAdditional RegressorsOutliers and Special EventsUncertainty IntervalsCross-ValidationPerformance MetricsProductionalizing Prophet The History and Development of Time Series Forecasting Getting Started with Facebook Prophet Non-Daily Data Seasonality Holidays Growth Modes Trend Changepoints Additional Regressors Outliers and Special Events Uncertainty Intervals Cross-Validation Performance Metrics Productionalizing Prophet If you enjoyed this Medium post, please consider ordering it here: https://amzn.to/373oIcf. If you do read the book, I would be thrilled to hear your thoughts!
[ { "code": null, "e": 359, "s": 172, "text": "This post contains an excerpt from my new book all about Facebook Prophet. The book is available for purchase on Amazon. The full contents of the book are listed at the end of this post!" }, { "code": null, "e": 513, "s": 359, "text": "If you find this article useful and would like to use Prophet to improve your forecasts, please consider buying the full book at https://amzn.to/373oIcf." }, { "code": null, "e": 1092, "s": 513, "text": "The longest record of direct measurements of CO­2 in the atmosphere was started in March of 1958 by Charles David Keeling of the Scripps Institution of Oceanography. Keeling was based in La Jolla, California, but had received permission from the National Oceanic and Atmospheric Administration (NOAA) to use their facility located two miles above sea level on the northern slope of Mauna Loa, a volcano on the island of Hawaii, to collect carbon dioxide samples. At that elevation, Keeling’s measurements would be unaffected by local releases of CO2 such as by nearby factories." }, { "code": null, "e": 1443, "s": 1092, "text": "In 1961, Keeling published the data he had collected thus far, establishing that there was strong seasonal variation in CO2 levels and that they were rising steadily, a trend that later became known as the Keeling Curve. By May 1974, the NOAA began their own parallel measurements and have continued since then. The keeling curve graph is as follows:" }, { "code": null, "e": 1730, "s": 1443, "text": "With its seasonality and increasing trend, this curve makes a good candidate to try out Prophet. This data set contains over 19,000 daily observations across 53 years. The unit of measurement for CO2 is PPM, or parts per million, a measure of CO2 molecules per million molecules of air." }, { "code": null, "e": 1873, "s": 1730, "text": "To begin our model, we need to import the necessary libraries, pandas and Matplotlib, and import the Prophet class from the fbprophet package." }, { "code": null, "e": 1953, "s": 1873, "text": "import pandas as pdimport matplotlib.pyplot as pltfrom fbprophet import Prophet" }, { "code": null, "e": 2024, "s": 1953, "text": "As input, Prophet always requires a pandas DataFrame with two columns:" }, { "code": null, "e": 2117, "s": 2024, "text": "ds, for datestamp, should be a datestamp or timestamp column in a format expected by pandas." }, { "code": null, "e": 2185, "s": 2117, "text": "y, a numeric column containing the measurement we wish to forecast." }, { "code": null, "e": 2525, "s": 2185, "text": "Here, we use pandas to import the data, in this case a csv file [Note: This csv can be downloaded at https://git.io/JYG6T], and then load it into a DataFrame. Note that we also convert the ds column to a pandas datetime format, to ensure that Pandas is correctly identifying it as dates and not simply loading it as an alphanumeric string." }, { "code": null, "e": 2630, "s": 2525, "text": "df = pd.read_csv(‘co2-ppm-daily_csv.csv’)df[‘date’] = pd.to_datetime(df[‘date’])df.columns = [‘ds’, ‘y’]" }, { "code": null, "e": 2910, "s": 2630, "text": "If you’re familiar with the scikit-learn (sklearn) package, you’ll feel right at home in Prophet because it was designed to operate in a similar way. Prophet follows the sklearn paradigm of first creating an instance of the model class before calling the fit and predict methods." }, { "code": null, "e": 2941, "s": 2910, "text": "model = Prophet()model.fit(df)" }, { "code": null, "e": 3406, "s": 2941, "text": "In that single fit command, Prophet analyzed the data and isolated both the seasonality and trend without requiring us to specify any additional parameters. It has not yet made any future forecast though. To do that, we need to first make a DataFrame of future dates and then call the predict method. The make_future_dataframe method requires us to specify the number of days we intend to forecast out. In this case, we will choose ten years, or 365 days times 10." }, { "code": null, "e": 3493, "s": 3406, "text": "future = model.make_future_dataframe(periods=365 * 10)forecast = model.predict(future)" }, { "code": null, "e": 3866, "s": 3493, "text": "At this point, the forecast DataFrame contains Prophet’s prediction for CO2 concentrations going ten years into the future. We will explore that DataFrame in a moment, but first let’s plot the data using Prophet’s plot functionality. The plot method is built upon Matplotlib; it requires a DataFrame output from the predict method (our forecast DataFrame in this example)." }, { "code": null, "e": 4354, "s": 3866, "text": "We’re labeling the axes with the optional xlabel and ylabel arguments, but just sticking with the default for the optional figsize argument. Note that I am also adding a title using raw Matplotlib syntax; because the Prophet plot is built upon Matplotlib, anything you can do to a Matplotlib figure can be performed here as well. Also, don’t be confused by the odd ylabel text with the dollar signs; that just tells Matplotlib to use its own TeX-like engine to make the subscript in CO2." }, { "code": null, "e": 4490, "s": 4354, "text": "fig = model.plot(forecast, xlabel=’Date’, ylabel=r’CO$_2$ PPM’)plt.title(‘Daily Carbon Dioxide Levels Measured at Mauna Loa’)plt.show()" }, { "code": null, "e": 4515, "s": 4490, "text": "The graph is as follows:" }, { "code": null, "e": 4599, "s": 4515, "text": "And that’s it! In those 12 lines of code, we have arrived at our ten year forecast." }, { "code": null, "e": 4820, "s": 4599, "text": "Now, let’s take a look at that forecast DataFrame by displaying the first three rows (I’ve transposed it here, in order to better see the column names on the page) and learn how these values were used in the above chart:" }, { "code": null, "e": 4839, "s": 4820, "text": "forecast.head(3).T" }, { "code": null, "e": 4913, "s": 4839, "text": "After running that command, you should see the following table print out:" }, { "code": null, "e": 4994, "s": 4913, "text": "The following is a description of each of the columns in the forecast DataFrame:" }, { "code": null, "e": 5060, "s": 4994, "text": "‘ds’ — Datestamp or timestamp which values in that row pertain to" }, { "code": null, "e": 5105, "s": 5060, "text": "‘trend’ — Value of the trend component alone" }, { "code": null, "e": 5188, "s": 5105, "text": "‘yhat_lower’ — Lower bound of the uncertainty interval around the final prediction" }, { "code": null, "e": 5271, "s": 5188, "text": "‘yhat_upper’ — Upper bound of the uncertainty interval around the final prediction" }, { "code": null, "e": 5354, "s": 5271, "text": "‘trend_lower’ — Lower bound of the uncertainty interval around the trend component" }, { "code": null, "e": 5437, "s": 5354, "text": "‘trend_upper’ — Upper bound of the uncertainty interval around the trend component" }, { "code": null, "e": 5501, "s": 5437, "text": "‘additive_terms’ — Combined value of all additive seasonalities" }, { "code": null, "e": 5600, "s": 5501, "text": "‘additive_terms_lower’ — Lower bound of the uncertainty interval around the additive seasonalities" }, { "code": null, "e": 5699, "s": 5600, "text": "‘additive_terms_upper’ — Upper bound of the uncertainty interval around the additive seasonalities" }, { "code": null, "e": 5752, "s": 5699, "text": "‘weekly’ — Value of the weekly seasonality component" }, { "code": null, "e": 5837, "s": 5752, "text": "‘weekly_lower’ — Lower bound of the uncertainty interval around the weekly component" }, { "code": null, "e": 5922, "s": 5837, "text": "‘weekly_upper’ — Upper bound of the uncertainty interval around the weekly component" }, { "code": null, "e": 5975, "s": 5922, "text": "‘yearly’ — Value of the yearly seasonality component" }, { "code": null, "e": 6060, "s": 5975, "text": "‘yearly_lower’ — Lower bound of the uncertainty interval around the yearly component" }, { "code": null, "e": 6145, "s": 6060, "text": "‘yearly_upper’ — Upper bound of the uncertainty interval around the yearly component" }, { "code": null, "e": 6221, "s": 6145, "text": "‘multiplicative_terms’ — Combined value of all multiplicative seasonalities" }, { "code": null, "e": 6332, "s": 6221, "text": "‘multiplicative_terms_lower’ — Lower bound of the uncertainty interval around the multiplicative seasonalities" }, { "code": null, "e": 6443, "s": 6332, "text": "‘multiplicative_terms_upper’ — Upper bound of the uncertainty interval around the multiplicative seasonalities" }, { "code": null, "e": 6546, "s": 6443, "text": "‘yhat’ — Final predicted value; a combination of ‘trend’, ‘multiplicative_terms’, and ‘additive_terms’" }, { "code": null, "e": 6880, "s": 6546, "text": "If the data contains a daily seasonality, then columns for ‘daily’, ‘daily_upper’, and ‘daily_lower’ will also be included, following the pattern established with the ‘weekly’ and ‘yearly’ columns. Later chapters will include discussion and examples of both the additive/multiplicative seasonalities and of the uncertainty intervals." }, { "code": null, "e": 7376, "s": 6880, "text": "In the forecast plot above, the black dots represent the actual recorded y values we fit on (those in the df[‘y’] column) whereas the solid line represents the calculated yhat values (the forecast[‘yhat’] column). Note that the solid line extends beyond the range of the black dots where we have forecasted into the future. The lighter shading notable around the solid line in the forecasted region represents the uncertainty interval, bound by forecast[‘yhat_lower’] and forecast[‘yhat_upper’]." }, { "code": null, "e": 7432, "s": 7376, "text": "Now let’s break down that forecast into its components." }, { "code": null, "e": 8040, "s": 7432, "text": "In Chapter 1, History and Development of Time Series Forecasting, Prophet was introduced as an additive regression model. Figures 1.4 and 1.5 showed how individual component curves for the trend and the different seasonalities are added together to create a more complex curve. The Prophet algorithm essentially does this in reverse; it takes a complex curve and decomposes it into its constituent parts. The first step towards greater control of a Prophet forecast is to understand these components so that they can be manipulated individually. Prophet provides a method plot_components to visualize these." }, { "code": null, "e": 8160, "s": 8040, "text": "Continuing on with our progress on the Mauna Loa model, plotting the components is as simple as running these commands:" }, { "code": null, "e": 8209, "s": 8160, "text": "fig2 = model.plot_components(forecast)plt.show()" }, { "code": null, "e": 8359, "s": 8209, "text": "As you can see in the output plot, Prophet has isolated three components in this data set: the trend, a weekly seasonality, and a yearly seasonality:" }, { "code": null, "e": 8884, "s": 8359, "text": "The trend constantly increases but seems to have a steepening slope as time progresses — an acceleration of CO2 concentration in the atmosphere. The trend line also shows slim uncertainty intervals in the forecasted year. From this curve, we learn that atmospheric CO2 concentrations were about 320 PPM in 1965. This grew to about 400 by 2015 and we expect about 430 PPM by 2030. However, these exact numbers will vary depending upon the day of the week and the time of year, due to the existence of the seasonality effects." }, { "code": null, "e": 9276, "s": 8884, "text": "The weekly seasonality shows that by days of the week, values will vary by about 0.01 PPM — an insignificant amount and most likely due purely to noise and random chance. Indeed, intuition tells us that carbon dioxide levels (when measured far enough away from human activity, as they are on the high slopes of Mauna Loa) do not care much what day of the week it is and are unaffected by it." }, { "code": null, "e": 9553, "s": 9276, "text": "We will learn in Chapter 4, Seasonality, how to instruct Prophet not to fit a weekly seasonality, as is prudent in this case. In Chapter 10, Uncertainty Intervals, we will learn how to plot uncertainty for seasonality and ensure that a seasonality such as this can be ignored." }, { "code": null, "e": 10035, "s": 9553, "text": "Now looking at the yearly seasonality reveals that carbon dioxide rises throughout the winter and peaks in May or so, while falling in the summer with a trough in October. Measurements of carbon dioxide can be 3 PPM above or 3 PPM below what the trend alone would predict, based upon the time of year. If you refer back to the original data, in the Keeling Curve, you will be reminded that there was a very obvious cyclic nature to the curve, captured with this yearly seasonality." }, { "code": null, "e": 10224, "s": 10035, "text": "As simple as that model was, that is often all you need to make very accurate forecasts with Prophet! We used no additional parameters than the defaults and yet achieved very good results." }, { "code": null, "e": 10635, "s": 10224, "text": "This excerpt is from chapter 2 of Forecasting Time Series Data with Facebook Prophet available now on Amazon. The book has more than 250 pages of examples, lessons, and descriptions of every single aspect of Prophet and more than 10 instructive datasets are provided to help you learn how to perfect your forecasts by demonstrating Prophet functionality from the simple to the advanced with fully working code." }, { "code": null, "e": 10682, "s": 10635, "text": "The full book contains the following chapters:" }, { "code": null, "e": 10966, "s": 10682, "text": "The History and Development of Time Series ForecastingGetting Started with Facebook ProphetNon-Daily DataSeasonalityHolidaysGrowth ModesTrend ChangepointsAdditional RegressorsOutliers and Special EventsUncertainty IntervalsCross-ValidationPerformance MetricsProductionalizing Prophet" }, { "code": null, "e": 11021, "s": 10966, "text": "The History and Development of Time Series Forecasting" }, { "code": null, "e": 11059, "s": 11021, "text": "Getting Started with Facebook Prophet" }, { "code": null, "e": 11074, "s": 11059, "text": "Non-Daily Data" }, { "code": null, "e": 11086, "s": 11074, "text": "Seasonality" }, { "code": null, "e": 11095, "s": 11086, "text": "Holidays" }, { "code": null, "e": 11108, "s": 11095, "text": "Growth Modes" }, { "code": null, "e": 11127, "s": 11108, "text": "Trend Changepoints" }, { "code": null, "e": 11149, "s": 11127, "text": "Additional Regressors" }, { "code": null, "e": 11177, "s": 11149, "text": "Outliers and Special Events" }, { "code": null, "e": 11199, "s": 11177, "text": "Uncertainty Intervals" }, { "code": null, "e": 11216, "s": 11199, "text": "Cross-Validation" }, { "code": null, "e": 11236, "s": 11216, "text": "Performance Metrics" }, { "code": null, "e": 11262, "s": 11236, "text": "Productionalizing Prophet" } ]
Difference between Thread.start() and Thread.run() in Java.
As we know that start() and run() are the two important methods of multithreading and one is used to create a new thread while other is used to start executing that thread. Following are the important differences between Thread.start() and Thread.run(). JavaTester.java Live Demo public class JavaTester extends Thread{ public void run(){ System.out.println("Thread is running..."); } public static void main(String args[]){ JavaTester t1=new JavaTester(); // this will call run() method t1.start(); } } Thread is running... JavaTester.java Live Demo public class JavaTester implements Runnable{ public void run(){ System.out.println("Thread is running..."); } public static void main(String args[]){ JavaTester m1=new JavaTester(); Thread t1 =new Thread(m1); // this will call run() method t1.start(); } } Thread is running...
[ { "code": null, "e": 1235, "s": 1062, "text": "As we know that start() and run() are the two important methods of multithreading and one is used to create a new thread while other is used to start executing that thread." }, { "code": null, "e": 1316, "s": 1235, "text": "Following are the important differences between Thread.start() and Thread.run()." }, { "code": null, "e": 1332, "s": 1316, "text": "JavaTester.java" }, { "code": null, "e": 1343, "s": 1332, "text": " Live Demo" }, { "code": null, "e": 1603, "s": 1343, "text": "public class JavaTester extends Thread{\n public void run(){\n System.out.println(\"Thread is running...\");\n }\n public static void main(String args[]){\n JavaTester t1=new JavaTester();\n // this will call run() method\n t1.start();\n }\n}" }, { "code": null, "e": 1624, "s": 1603, "text": "Thread is running..." }, { "code": null, "e": 1640, "s": 1624, "text": "JavaTester.java" }, { "code": null, "e": 1651, "s": 1640, "text": " Live Demo" }, { "code": null, "e": 1949, "s": 1651, "text": "public class JavaTester implements Runnable{\n public void run(){\n System.out.println(\"Thread is running...\");\n }\n public static void main(String args[]){\n JavaTester m1=new JavaTester();\n Thread t1 =new Thread(m1);\n // this will call run() method\n t1.start();\n }\n}" }, { "code": null, "e": 1970, "s": 1949, "text": "Thread is running..." } ]
Laravel - Views
In MVC framework, the letter “V” stands for Views. It separates the application logic and the presentation logic. Views are stored in resources/views directory. Generally, the view contains the HTML which will be served by the application. Observe the following example to understand more about Views − Step 1 − Copy the following code and save it at resources/views/test.php <html> <body> <h1>Hello, World</h1> </body> </html> Step 2 − Add the following line in app/Http/routes.php file to set the route for the above view. app/Http/routes.php Route::get('/test', function() { return view('test'); }); Step 3 − Visit the following URL to see the output of the view. http://localhost:8000/test Step 4 − The output will appear as shown in the following image. While building application it may be required to pass data to the views. Pass an array to view helper function. After passing an array, we can use the key to get the value of that key in the HTML file. Observe the following example to understand more about passing data to views − Step 1 − Copy the following code and save it at resources/views/test.php <html> <body> <h1><?php echo $name; ?></h1> </body> </html> Step 2 − Add the following line in app/Http/routes.php file to set the route for the above view. app/Http/routes.php Route::get('/test', function() { return view('test',[‘name’=>’Virat Gandhi’]); }); Step 3 − The value of the key name will be passed to test.php file and $name will be replaced by that value. Step 4 − Visit the following URL to see the output of the view. http://localhost:8000/test Step 5 − The output will appear as shown in the following image. We have seen how we can pass data to views but at times, there is a need to pass data to all the views. Laravel makes this simpler. There is a method called share() which can be used for this purpose. The share() method will take two arguments, key and value. Typically share() method can be called from boot method of service provider. We can use any service provider, AppServiceProvider or our own service provider. Observe the following example to understand more about sharing data with all views − Step 1 − Add the following line in app/Http/routes.php file. app/Http/routes.php Route::get('/test', function() { return view('test'); }); Route::get('/test2', function() { return view('test2'); }); Step 2 − Create two view files — test.php and test2.php with the same code. These are the two files which will share data. Copy the following code in both the files. resources/views/test.php & resources/views/test2.php <html> <body> <h1><?php echo $name; ?></h1> </body> </html> Step 3 − Change the code of boot method in the file app/Providers/AppServiceProvider.php as shown below. (Here, we have used share method and the data that we have passed will be shared with all the views.) app/Providers/AppServiceProvider.php <?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { view()->share('name', 'Virat Gandhi'); } /** * Register any application services. * * @return void */ public function register() { // } } Step 4 − Visit the following URLs. http://localhost:8000/test http://localhost:8000/test2 Step 5 − The output will appear as shown in the following image. 13 Lectures 3 hours Sebastian Sulinski 35 Lectures 3.5 hours Antonio Papa 7 Lectures 1.5 hours Sebastian Sulinski 42 Lectures 1 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 116 Lectures 13 hours Hafizullah Masoudi Print Add Notes Bookmark this page
[ { "code": null, "e": 2712, "s": 2472, "text": "In MVC framework, the letter “V” stands for Views. It separates the application logic and the presentation logic. Views are stored in resources/views directory. Generally, the view contains the HTML which will be served by the application." }, { "code": null, "e": 2775, "s": 2712, "text": "Observe the following example to understand more about Views −" }, { "code": null, "e": 2848, "s": 2775, "text": "Step 1 − Copy the following code and save it at resources/views/test.php" }, { "code": null, "e": 2912, "s": 2848, "text": "<html>\n <body>\n <h1>Hello, World</h1>\n </body>\n</html>" }, { "code": null, "e": 3009, "s": 2912, "text": "Step 2 − Add the following line in app/Http/routes.php file to set the route for the above view." }, { "code": null, "e": 3029, "s": 3009, "text": "app/Http/routes.php" }, { "code": null, "e": 3091, "s": 3029, "text": "Route::get('/test', function() {\n return view('test');\n});\n" }, { "code": null, "e": 3155, "s": 3091, "text": "Step 3 − Visit the following URL to see the output of the view." }, { "code": null, "e": 3183, "s": 3155, "text": "http://localhost:8000/test\n" }, { "code": null, "e": 3248, "s": 3183, "text": "Step 4 − The output will appear as shown in the following image." }, { "code": null, "e": 3450, "s": 3248, "text": "While building application it may be required to pass data to the views. Pass an array to view helper function. After passing an array, we can use the key to get the value of that key in the HTML file." }, { "code": null, "e": 3529, "s": 3450, "text": "Observe the following example to understand more about passing data to views −" }, { "code": null, "e": 3602, "s": 3529, "text": "Step 1 − Copy the following code and save it at resources/views/test.php" }, { "code": null, "e": 3674, "s": 3602, "text": "<html>\n <body>\n <h1><?php echo $name; ?></h1>\n </body>\n</html>" }, { "code": null, "e": 3771, "s": 3674, "text": "Step 2 − Add the following line in app/Http/routes.php file to set the route for the above view." }, { "code": null, "e": 3791, "s": 3771, "text": "app/Http/routes.php" }, { "code": null, "e": 3878, "s": 3791, "text": "Route::get('/test', function() {\n return view('test',[‘name’=>’Virat Gandhi’]);\n});\n" }, { "code": null, "e": 3987, "s": 3878, "text": "Step 3 − The value of the key name will be passed to test.php file and $name will be replaced by that value." }, { "code": null, "e": 4051, "s": 3987, "text": "Step 4 − Visit the following URL to see the output of the view." }, { "code": null, "e": 4079, "s": 4051, "text": "http://localhost:8000/test\n" }, { "code": null, "e": 4144, "s": 4079, "text": "Step 5 − The output will appear as shown in the following image." }, { "code": null, "e": 4562, "s": 4144, "text": "We have seen how we can pass data to views but at times, there is a need to pass data to all the views. Laravel makes this simpler. There is a method called share() which can be used for this purpose. The share() method will take two arguments, key and value. Typically share() method can be called from boot method of service provider. We can use any service provider, AppServiceProvider or our own service provider." }, { "code": null, "e": 4647, "s": 4562, "text": "Observe the following example to understand more about sharing data with all views −" }, { "code": null, "e": 4708, "s": 4647, "text": "Step 1 − Add the following line in app/Http/routes.php file." }, { "code": null, "e": 4728, "s": 4708, "text": "app/Http/routes.php" }, { "code": null, "e": 4854, "s": 4728, "text": "Route::get('/test', function() {\n return view('test');\n});\n\nRoute::get('/test2', function() {\n return view('test2');\n});\n" }, { "code": null, "e": 5073, "s": 4854, "text": "Step 2 − Create two view files — test.php and test2.php with the same code. These are the two files which will share data. Copy the following code in both the files. resources/views/test.php & resources/views/test2.php" }, { "code": null, "e": 5145, "s": 5073, "text": "<html>\n <body>\n <h1><?php echo $name; ?></h1>\n </body>\n</html>" }, { "code": null, "e": 5389, "s": 5145, "text": "Step 3 − Change the code of boot method in the file app/Providers/AppServiceProvider.php as shown below. (Here, we have used share method and the data that we have passed will be shared with all the views.) app/Providers/AppServiceProvider.php" }, { "code": null, "e": 5817, "s": 5389, "text": "<?php\n\nnamespace App\\Providers;\nuse Illuminate\\Support\\ServiceProvider;\n\nclass AppServiceProvider extends ServiceProvider {\n \n /**\n * Bootstrap any application services.\n *\n * @return void\n */\n\n public function boot() {\n view()->share('name', 'Virat Gandhi');\n }\n\n /**\n * Register any application services.\n *\n * @return void\n */\n\n public function register() {\n //\n }\n}" }, { "code": null, "e": 5852, "s": 5817, "text": "Step 4 − Visit the following URLs." }, { "code": null, "e": 5908, "s": 5852, "text": "http://localhost:8000/test\nhttp://localhost:8000/test2\n" }, { "code": null, "e": 5973, "s": 5908, "text": "Step 5 − The output will appear as shown in the following image." }, { "code": null, "e": 6006, "s": 5973, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 6026, "s": 6006, "text": " Sebastian Sulinski" }, { "code": null, "e": 6061, "s": 6026, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6075, "s": 6061, "text": " Antonio Papa" }, { "code": null, "e": 6109, "s": 6075, "text": "\n 7 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6129, "s": 6109, "text": " Sebastian Sulinski" }, { "code": null, "e": 6162, "s": 6129, "text": "\n 42 Lectures \n 1 hours \n" }, { "code": null, "e": 6182, "s": 6162, "text": " Skillbakerystudios" }, { "code": null, "e": 6217, "s": 6182, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 6240, "s": 6217, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 6275, "s": 6240, "text": "\n 116 Lectures \n 13 hours \n" }, { "code": null, "e": 6295, "s": 6275, "text": " Hafizullah Masoudi" }, { "code": null, "e": 6302, "s": 6295, "text": " Print" }, { "code": null, "e": 6313, "s": 6302, "text": " Add Notes" } ]
Final Exam | Google Kickstart 2021 Round D - GeeksforGeeks
21 Sep, 2021 It’s time for the final exam in algorithms and data structures! Edsger prepared N sets of problems. Each set consists of problems in an increasing difficulty sequence; the i-th set can be described by two integers Ai and Bi (Ai≤Bi), which denotes that this set contains problems with difficulties Ai, Ai+1..., Bi. Among all problems from all sets, it is guaranteed that no two problems have the same difficulty. This semester Edsger has to test M students. He wants to test each student with exactly one problem from one of his sets. No two students can get the exact same problem, so when Edsger tests a student with some problem, he cannot use this problem anymore. Through countless lectures, exercises, and projects, Edsger has gauged student number j to have skill level Sj and wants to give that student a problem with difficulty Sj. Unfortunately, this is not always possible, as Edsger may have not prepared a problem of this difficulty, or he may have already asked this problem to some other student earlier. Therefore, Edsger will choose for the j-th student a problem of difficulty Pj, in a way that |Pj−Sj| is minimal and a question of difficulty Pj was not already given to any of the students before the j-th student. In case of ties, Edsger will always choose the easier problem. Note that the problem chosen for the j-th student may affect problems chosen for all the students tested later, so you have to process students in the same order as they appear in the input. As keeping track of all the problems can be fairly complicated, can you help Edsger and determine which problems he should give to all of his students? OR Given an array problemRange of N pairs having starting and ending values as a range of difficulty levels, and an array arr of size M indicating the difficulty level every student can attempt. The task is to assign a unique integer X from problemRange to every integer in array arr such that | arr[i] – X | is minimized. In case of a tie between two values closest to arr[i], a lesser difficulty value must be chosen. X values must be assigned to students in their order since the same value of X cannot be assigned to more than one student. Print the X value assigned to every student. Example: Input: N = 5, M = 4, arr = [14, 24, 24, 4], problemRange = [[1, 2], [6, 7], [9, 12], [24, 24], [41, 50]] Output: 12 24 11 2Explanation: values which can be assigned to the students are {1, 2}, {6, 7}, {9, 10, 11, 12}, {24}, {41, 42, 43, 44, 45, 46, 47, 48, 49, 50} 12 is assigned to first student who can attempt questions of difficulty level 14 as it is the closest to 14. 24 is closest to 24. Next student can also attempt question of 24 difficulty but 24 from the range is already chosen and the next closest is 11. 2 and 6 is closest to last student of difficulty 4, since 2 and 6 both are similarly close to 4, easier questions of difficulty level 2 is assigned. Input: N = 1, M = 1, arr = [24], problemRange = [[42, 42]]Output: 42 Approach: Given problem can be solved by following the steps below: Use a map to store the start of ranges as keys and end of ranges as values Iterate the array and for every element in it find its lower_bound in the map Two cases are possible: Lower_bound will return the iterator pointing to the key which will be equal to arr[i] or the key which is just greater than arr[i]let’s say the iterator provided by lower_bound be it and pre be an iterator just before it (pre will be equal to it when it=mp.begin())Either pre.first<=arr[i]<=pre.second or it.first<=arr[i]<=it.second will be true. arr[i] will lie in either the forward section or in the backward section of this rangeevery time value is assigned to the arr[i] previous range is deleted from the map and a new range is added as shown in the imageEither two new ranges are added or one new range is added as cases shown in the images below: let’s say the iterator provided by lower_bound be it and pre be an iterator just before it (pre will be equal to it when it=mp.begin()) Either pre.first<=arr[i]<=pre.second or it.first<=arr[i]<=it.second will be true. arr[i] will lie in either the forward section or in the backward section of this range every time value is assigned to the arr[i] previous range is deleted from the map and a new range is added as shown in the image Either two new ranges are added or one new range is added as cases shown in the images below: Only one element is present in the range so it is removed and no new range is added arr[i] is equal to either one of the range The previous range is removed and two new ranges are added in the map Below is the implementation of the above approach: C++ // C++ implementation for the above approach #include <bits/stdc++.h> using namespace std; void solve(long long int N, long long int M, vector<pair<long long int, long long int> > problemRange, vector<long long int> arr){ // Store the problem range in a map map<long long int, long long int> mp; for (long long int i = 0; i < N; i++) { long long int a, b; a = problemRange[i].first; b = problemRange[i].second; mp[a] = b; } vector<long long int> ans(M); for (long long int i = 0; i < M; i++) { auto it = mp.lower_bound(arr[i]); auto pre = it; if (it != mp.begin()) pre--; // If answer lies in a valid range if (pre->first <= arr[i] && arr[i] <= pre->second) { ans[i] = arr[i]; long long int st = pre->first, end = pre->second; mp.erase(pre); long long int left = arr[i] - 1, right = arr[i] + 1; if (st <= left) { mp[st] = left; } if (end >= right) { mp[right] = end; } } // If answer is not in a valid range else { long long int op1 = pre->second, op2 = it->first; if (abs(arr[i] - op1) <= abs(arr[i] - op2)) { ans[i] = op1; long long int st = pre->first, end = op1 - 1; mp.erase(pre); if (st <= end) mp[st] = end; } else { ans[i] = op2; long long int st = it->first + 1, end = it->second; mp.erase(it); if (st <= end) mp[st] = end; } } } for (auto it : ans) cout << it << " "; cout << endl;} // Driver codeint main(){ long long int N, M; N = 5; M = 4; // Student difficulty level vector<long long int> arr = { 14, 24, 24, 4 }; vector<pair<long long int, long long int> > problemRange = { { 1, 2 }, { 6, 7 }, { 9, 12 }, { 24, 24 }, { 41, 50 } }; solve(N, M, problemRange, arr); return 0;} 12 24 11 2 Time complexity: MLog(N)Auxiliary Space: O(N) akshaysingh98088 Google Arrays Competitive Programming Mathematical Google Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Competitive Programming - A Complete Guide Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 24429, "s": 24401, "text": "\n21 Sep, 2021" }, { "code": null, "e": 24493, "s": 24429, "text": "It’s time for the final exam in algorithms and data structures!" }, { "code": null, "e": 24841, "s": 24493, "text": "Edsger prepared N sets of problems. Each set consists of problems in an increasing difficulty sequence; the i-th set can be described by two integers Ai and Bi (Ai≤Bi), which denotes that this set contains problems with difficulties Ai, Ai+1..., Bi. Among all problems from all sets, it is guaranteed that no two problems have the same difficulty." }, { "code": null, "e": 25916, "s": 24841, "text": "This semester Edsger has to test M students. He wants to test each student with exactly one problem from one of his sets. No two students can get the exact same problem, so when Edsger tests a student with some problem, he cannot use this problem anymore. Through countless lectures, exercises, and projects, Edsger has gauged student number j to have skill level Sj and wants to give that student a problem with difficulty Sj. Unfortunately, this is not always possible, as Edsger may have not prepared a problem of this difficulty, or he may have already asked this problem to some other student earlier. Therefore, Edsger will choose for the j-th student a problem of difficulty Pj, in a way that |Pj−Sj| is minimal and a question of difficulty Pj was not already given to any of the students before the j-th student. In case of ties, Edsger will always choose the easier problem. Note that the problem chosen for the j-th student may affect problems chosen for all the students tested later, so you have to process students in the same order as they appear in the input." }, { "code": null, "e": 26068, "s": 25916, "text": "As keeping track of all the problems can be fairly complicated, can you help Edsger and determine which problems he should give to all of his students?" }, { "code": null, "e": 26158, "s": 26068, "text": " OR" }, { "code": null, "e": 26745, "s": 26158, "text": "Given an array problemRange of N pairs having starting and ending values as a range of difficulty levels, and an array arr of size M indicating the difficulty level every student can attempt. The task is to assign a unique integer X from problemRange to every integer in array arr such that | arr[i] – X | is minimized. In case of a tie between two values closest to arr[i], a lesser difficulty value must be chosen. X values must be assigned to students in their order since the same value of X cannot be assigned to more than one student. Print the X value assigned to every student. " }, { "code": null, "e": 26754, "s": 26745, "text": "Example:" }, { "code": null, "e": 27423, "s": 26754, "text": "Input: N = 5, M = 4, arr = [14, 24, 24, 4], problemRange = [[1, 2], [6, 7], [9, 12], [24, 24], [41, 50]] Output: 12 24 11 2Explanation: values which can be assigned to the students are {1, 2}, {6, 7}, {9, 10, 11, 12}, {24}, {41, 42, 43, 44, 45, 46, 47, 48, 49, 50} 12 is assigned to first student who can attempt questions of difficulty level 14 as it is the closest to 14. 24 is closest to 24. Next student can also attempt question of 24 difficulty but 24 from the range is already chosen and the next closest is 11. 2 and 6 is closest to last student of difficulty 4, since 2 and 6 both are similarly close to 4, easier questions of difficulty level 2 is assigned. " }, { "code": null, "e": 27492, "s": 27423, "text": "Input: N = 1, M = 1, arr = [24], problemRange = [[42, 42]]Output: 42" }, { "code": null, "e": 27560, "s": 27492, "text": "Approach: Given problem can be solved by following the steps below:" }, { "code": null, "e": 27635, "s": 27560, "text": "Use a map to store the start of ranges as keys and end of ranges as values" }, { "code": null, "e": 27713, "s": 27635, "text": "Iterate the array and for every element in it find its lower_bound in the map" }, { "code": null, "e": 28393, "s": 27713, "text": "Two cases are possible: Lower_bound will return the iterator pointing to the key which will be equal to arr[i] or the key which is just greater than arr[i]let’s say the iterator provided by lower_bound be it and pre be an iterator just before it (pre will be equal to it when it=mp.begin())Either pre.first<=arr[i]<=pre.second or it.first<=arr[i]<=it.second will be true. arr[i] will lie in either the forward section or in the backward section of this rangeevery time value is assigned to the arr[i] previous range is deleted from the map and a new range is added as shown in the imageEither two new ranges are added or one new range is added as cases shown in the images below:" }, { "code": null, "e": 28529, "s": 28393, "text": "let’s say the iterator provided by lower_bound be it and pre be an iterator just before it (pre will be equal to it when it=mp.begin())" }, { "code": null, "e": 28698, "s": 28529, "text": "Either pre.first<=arr[i]<=pre.second or it.first<=arr[i]<=it.second will be true. arr[i] will lie in either the forward section or in the backward section of this range" }, { "code": null, "e": 28827, "s": 28698, "text": "every time value is assigned to the arr[i] previous range is deleted from the map and a new range is added as shown in the image" }, { "code": null, "e": 28921, "s": 28827, "text": "Either two new ranges are added or one new range is added as cases shown in the images below:" }, { "code": null, "e": 29006, "s": 28921, "text": "Only one element is present in the range so it is removed and no new range is added " }, { "code": null, "e": 29049, "s": 29006, "text": "arr[i] is equal to either one of the range" }, { "code": null, "e": 29119, "s": 29049, "text": "The previous range is removed and two new ranges are added in the map" }, { "code": null, "e": 29170, "s": 29119, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29174, "s": 29170, "text": "C++" }, { "code": "// C++ implementation for the above approach #include <bits/stdc++.h> using namespace std; void solve(long long int N, long long int M, vector<pair<long long int, long long int> > problemRange, vector<long long int> arr){ // Store the problem range in a map map<long long int, long long int> mp; for (long long int i = 0; i < N; i++) { long long int a, b; a = problemRange[i].first; b = problemRange[i].second; mp[a] = b; } vector<long long int> ans(M); for (long long int i = 0; i < M; i++) { auto it = mp.lower_bound(arr[i]); auto pre = it; if (it != mp.begin()) pre--; // If answer lies in a valid range if (pre->first <= arr[i] && arr[i] <= pre->second) { ans[i] = arr[i]; long long int st = pre->first, end = pre->second; mp.erase(pre); long long int left = arr[i] - 1, right = arr[i] + 1; if (st <= left) { mp[st] = left; } if (end >= right) { mp[right] = end; } } // If answer is not in a valid range else { long long int op1 = pre->second, op2 = it->first; if (abs(arr[i] - op1) <= abs(arr[i] - op2)) { ans[i] = op1; long long int st = pre->first, end = op1 - 1; mp.erase(pre); if (st <= end) mp[st] = end; } else { ans[i] = op2; long long int st = it->first + 1, end = it->second; mp.erase(it); if (st <= end) mp[st] = end; } } } for (auto it : ans) cout << it << \" \"; cout << endl;} // Driver codeint main(){ long long int N, M; N = 5; M = 4; // Student difficulty level vector<long long int> arr = { 14, 24, 24, 4 }; vector<pair<long long int, long long int> > problemRange = { { 1, 2 }, { 6, 7 }, { 9, 12 }, { 24, 24 }, { 41, 50 } }; solve(N, M, problemRange, arr); return 0;}", "e": 31580, "s": 29174, "text": null }, { "code": null, "e": 31592, "s": 31580, "text": "12 24 11 2 " }, { "code": null, "e": 31638, "s": 31592, "text": "Time complexity: MLog(N)Auxiliary Space: O(N)" }, { "code": null, "e": 31655, "s": 31638, "text": "akshaysingh98088" }, { "code": null, "e": 31662, "s": 31655, "text": "Google" }, { "code": null, "e": 31669, "s": 31662, "text": "Arrays" }, { "code": null, "e": 31693, "s": 31669, "text": "Competitive Programming" }, { "code": null, "e": 31706, "s": 31693, "text": "Mathematical" }, { "code": null, "e": 31713, "s": 31706, "text": "Google" }, { "code": null, "e": 31720, "s": 31713, "text": "Arrays" }, { "code": null, "e": 31733, "s": 31720, "text": "Mathematical" }, { "code": null, "e": 31831, "s": 31733, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31840, "s": 31831, "text": "Comments" }, { "code": null, "e": 31853, "s": 31840, "text": "Old Comments" }, { "code": null, "e": 31874, "s": 31853, "text": "Next Greater Element" }, { "code": null, "e": 31899, "s": 31874, "text": "Window Sliding Technique" }, { "code": null, "e": 31926, "s": 31899, "text": "Count pairs with given sum" }, { "code": null, "e": 31975, "s": 31926, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32013, "s": 31975, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32056, "s": 32013, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 32097, "s": 32056, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 32124, "s": 32097, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 32167, "s": 32124, "text": "Competitive Programming - A Complete Guide" } ]
Image Processing for Python — Adjusting to the Ground Truth | by Tonichi Edeza | Towards Data Science
In this lesson we shall go over an image adjustment algorithm which may be intuitive for most readers. Unlike the other image adjustment algorithms we have discussed so far (such as RGB Channel Adjustment and Histogram Manipulation), this method will use the actual colors available in the image. Let’s get started! As always, we must import the required Python Libraries. import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.patches import Rectanglefrom skimage.io import imread, imshowimport skimage.io as skiofrom skimage import img_as_ubyte, img_as_float Great, now let us look at the image we’re working with. overcast = imread("image_overcast.PNG")plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(overcast); The image clearly has a color overcast. Now let us try to adjust it. To begin we must first select the particular ground truth patches we want the machine to work with. To do that we can use the Rectangle function available in NumPy. fig, ax = plt.subplots(1,1, figsize=(8, 6), dpi = 80)patch = Rectangle((70,175), 10, 10, edgecolor='r', facecolor='none')ax.add_patch(patch)ax.imshow(overcast); We can see the red rectangle on the upper left corner of the image. I’m sure most of you suspect that this may not be the best ground truth patch to use. The reason being that it is quite different from the rest of the image. However, for pedagogical reasons we shall use this square and adjust our image to it. Let us first get a close up view of our ground truth patch. To do that we must use the get_bbox() and get_points() functions found in NumPy. coord = Rectangle.get_bbox(patch).get_points()print(coord) We can now use this coordinate array to slice our main image. fig, ax = plt.subplots(1,1, figsize=(8, 6), dpi = 80)ax.imshow(overcast[int(coord[0][1]):int(coord[1][1]), int(coord[0][0]):int(coord[1][0])]); As we can see, the ground truth patch is far from a monotonic color. Within it are multiple shades of brown and black (a testament to the amount of details not visible to the human eye!). Now let us actually adjust our image to the patch. We shall use the Max and Mean values of the patch. image_patch = overcast[int(coord[0][1]):int(coord[1][1]), int(coord[0][0]):int(coord[1][0])]image_max = (overcast / image_patch.max(axis=(0, 1))).clip(0, 1)image_mean = ((overcast * image_patch.mean()) / overcast.mean(axis=(0, 1))).clip(0,255).astype(int)fig, ax = plt.subplots(1,2, figsize=(15, 10), dpi = 80)f_size = 19ax[0].imshow(image_max)ax[0].set_title('Max Adjusted', fontsize = f_size)ax[0].set_axis_off()ax[1].set_title('Mean Adjusted', fontsize = f_size)ax[1].imshow(image_mean);ax[1].set_axis_off()fig.tight_layout() As we can see, both adjustments are pretty terrible. Depending on your preference you could say either is better. The Max adjusted image (though clearly overexposed) does highlight the green color of the plant on the left as well as the blue cap of the carriage driver on the right. The Mean adjusted image (though extremely faded) does fair better in terms of overall clarity of the image. But I believe it is safe to say that neither of these adjustments would do. To remedy this let us go back to the selection of ground truth patches. fig, ax = plt.subplots(1,1, figsize=(8, 6), dpi = 80)patch1 = Rectangle((100,300), 10, 10, edgecolor='r', facecolor='none')patch2 = Rectangle((200,250), 10, 10, edgecolor='r', facecolor='none')patch3 = Rectangle((200,190), 10, 10, edgecolor='r', facecolor='none')ax.add_patch(patch1)ax.add_patch(patch2)ax.add_patch(patch3)ax.imshow(overcast); Though we do not have to, we can plot out the patches so that we can get an idea of what they look like. coor1 = Rectangle.get_bbox(patch1).get_points()coor2 = Rectangle.get_bbox(patch2).get_points()coor3 = Rectangle.get_bbox(patch3).get_points()image_patch1 = overcast[int(coor1[0][1]):int(coor1[1][1]), int(coor1[0][0]):int(coor1[1][0])]image_patch2 = overcast[int(coor2[0][1]):int(coor2[1][1]), int(coor2[0][0]):int(coor2[1][0])]image_patch3 = overcast[int(coor3[0][1]):int(coor3[1][1]), int(coor3[0][0]):int(coor3[1][0])]fig, ax = plt.subplots(1,3, figsize=(15, 12), dpi = 80)ax[0].imshow(image_patch1)ax[1].imshow(image_patch2)ax[2].imshow(image_patch3); Like our first patch, these patches also show an array of colors. Let us now use each one in adjusting our image. To aid in this, let us first use Python’s list comprehension capabilities to create a list of the adjusted images. patch_list = [image_patch1, image_patch2, image_patch3]image_max_list = [(overcast / patch.max(axis=(0, 1))).clip(0, 1) for patch in patch_list]image_mean_list = [((overcast * patch.mean()) / overcast.mean(axis=(0, 1))).clip(0, 255).astype(int) for patch in patch_list] Wonderful! Now we can simply call all these images. Let us begin. def patch_plotter(max_patch, mean_patch): fig, ax = plt.subplots(1,2, figsize=(15, 10), dpi = 80) f_size = 19 ax[0].imshow(max_patch) ax[0].set_title('Max Adjusted Patch', fontsize = f_size) ax[0].set_axis_off() ax[1].set_title('Mean Adjusted Patch', fontsize = f_size) ax[1].imshow(mean_patch); ax[1].set_axis_off() fig.tight_layout()for i in range(3): patch_plotter(image_max_list[i], image_mean_list[i]) We can see from the results that the Max adjusted patches perform much better than the Mean adjusted patches. Furthermore, it seems that the second patch faired the best. This seems to indicate that best batch is one that adjusts the image to a beige-like color. As a final exercise let us choose patches that fit that particular description. Also, we shall decrease the size of the patches to lessen the amount of color variety in the patches. Below is a function that can generate the ground truth adjusted images. We simply need to feed it our image, the names of the patches (for labelling purposes), and the patch coordinates. def ground_truth(image, patch_names, patch_coordinates): f_size = 25 figure_size = (17,12) patch_dict = dict(zip(patch_names, patch_coordinates)) coord = [] fig1, ax_1 = plt.subplots(1, 3, figsize = figure_size) for n, ax in enumerate(ax_1.flatten()): #Create Rectangles key = list(patch_dict.keys())[n] patch = Rectangle(patch_dict[key], 5, 5, edgecolor='r', facecolor='none') coord.append(Rectangle.get_bbox(patch).get_points()) ax.add_patch(patch); #Show and Format Images ax.imshow(image) ax.set_title(f'{key}', fontsize = f_size) ax.set_axis_off() fig1.tight_layout() fig2, ax_2 = plt.subplots(1, 3, figsize = figure_size) for n, ax in enumerate(ax_2.flatten()): #Show and Format Rectangles key = list(patch_dict.keys())[n] ax.imshow(image[int(coord[n][0][1]) : int(coord[n][1][1]), int(coord[n][0][0]) : int(coord[n][1][0])]); ax.set_title(key, fontsize = f_size) ax.set_axis_off() fig2.tight_layout()fig3, ax_3 = plt.subplots(1, 3, figsize = figure_size) for n, ax in enumerate(ax_3.flatten()): patch =image[int(coord[n][0][1]) : int(coord[n][1][1]), int(coord[n][0][0]) : int(coord[n][1][0])] image_max = (image / patch.max(axis=(0, 1))).clip(0, 1) ax.imshow(image_max) ax.set_title(f'Max : {patch_names[n]}', fontsize = f_size) ax.set_axis_off()fig3.tight_layout()ground_truth(overcast, ['First', 'Second', ' Third'], [(105, 275), (50, 45), (330, 105)]) We can see that among the different ground truth patches, the third patch performs the best. Though the image is noticeable bluer, the yellow overcast was completely removed. Additionally, overexposure is kept at a bare minimum. In Conclusion We see that one does not need to be extremely well versed in the different ways color is interpreted by the machine. We can use the simple yet effective Ground Truth algorithm to adjust our images. This particular method may be more suited for individuals with an intuitive understanding of colors. Though good results did take a while to achieve, this method is worth keeping in mind as it one of the more straightforward ways to alter an image. I hope that you have learned the significance of this more simple algorithm.
[ { "code": null, "e": 469, "s": 172, "text": "In this lesson we shall go over an image adjustment algorithm which may be intuitive for most readers. Unlike the other image adjustment algorithms we have discussed so far (such as RGB Channel Adjustment and Histogram Manipulation), this method will use the actual colors available in the image." }, { "code": null, "e": 488, "s": 469, "text": "Let’s get started!" }, { "code": null, "e": 545, "s": 488, "text": "As always, we must import the required Python Libraries." }, { "code": null, "e": 743, "s": 545, "text": "import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.patches import Rectanglefrom skimage.io import imread, imshowimport skimage.io as skiofrom skimage import img_as_ubyte, img_as_float" }, { "code": null, "e": 799, "s": 743, "text": "Great, now let us look at the image we’re working with." }, { "code": null, "e": 900, "s": 799, "text": "overcast = imread(\"image_overcast.PNG\")plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(overcast);" }, { "code": null, "e": 969, "s": 900, "text": "The image clearly has a color overcast. Now let us try to adjust it." }, { "code": null, "e": 1134, "s": 969, "text": "To begin we must first select the particular ground truth patches we want the machine to work with. To do that we can use the Rectangle function available in NumPy." }, { "code": null, "e": 1295, "s": 1134, "text": "fig, ax = plt.subplots(1,1, figsize=(8, 6), dpi = 80)patch = Rectangle((70,175), 10, 10, edgecolor='r', facecolor='none')ax.add_patch(patch)ax.imshow(overcast);" }, { "code": null, "e": 1607, "s": 1295, "text": "We can see the red rectangle on the upper left corner of the image. I’m sure most of you suspect that this may not be the best ground truth patch to use. The reason being that it is quite different from the rest of the image. However, for pedagogical reasons we shall use this square and adjust our image to it." }, { "code": null, "e": 1748, "s": 1607, "text": "Let us first get a close up view of our ground truth patch. To do that we must use the get_bbox() and get_points() functions found in NumPy." }, { "code": null, "e": 1807, "s": 1748, "text": "coord = Rectangle.get_bbox(patch).get_points()print(coord)" }, { "code": null, "e": 1869, "s": 1807, "text": "We can now use this coordinate array to slice our main image." }, { "code": null, "e": 2031, "s": 1869, "text": "fig, ax = plt.subplots(1,1, figsize=(8, 6), dpi = 80)ax.imshow(overcast[int(coord[0][1]):int(coord[1][1]), int(coord[0][0]):int(coord[1][0])]);" }, { "code": null, "e": 2219, "s": 2031, "text": "As we can see, the ground truth patch is far from a monotonic color. Within it are multiple shades of brown and black (a testament to the amount of details not visible to the human eye!)." }, { "code": null, "e": 2321, "s": 2219, "text": "Now let us actually adjust our image to the patch. We shall use the Max and Mean values of the patch." }, { "code": null, "e": 2886, "s": 2321, "text": "image_patch = overcast[int(coord[0][1]):int(coord[1][1]), int(coord[0][0]):int(coord[1][0])]image_max = (overcast / image_patch.max(axis=(0, 1))).clip(0, 1)image_mean = ((overcast * image_patch.mean()) / overcast.mean(axis=(0, 1))).clip(0,255).astype(int)fig, ax = plt.subplots(1,2, figsize=(15, 10), dpi = 80)f_size = 19ax[0].imshow(image_max)ax[0].set_title('Max Adjusted', fontsize = f_size)ax[0].set_axis_off()ax[1].set_title('Mean Adjusted', fontsize = f_size)ax[1].imshow(image_mean);ax[1].set_axis_off()fig.tight_layout()" }, { "code": null, "e": 3425, "s": 2886, "text": "As we can see, both adjustments are pretty terrible. Depending on your preference you could say either is better. The Max adjusted image (though clearly overexposed) does highlight the green color of the plant on the left as well as the blue cap of the carriage driver on the right. The Mean adjusted image (though extremely faded) does fair better in terms of overall clarity of the image. But I believe it is safe to say that neither of these adjustments would do. To remedy this let us go back to the selection of ground truth patches." }, { "code": null, "e": 3829, "s": 3425, "text": "fig, ax = plt.subplots(1,1, figsize=(8, 6), dpi = 80)patch1 = Rectangle((100,300), 10, 10, edgecolor='r', facecolor='none')patch2 = Rectangle((200,250), 10, 10, edgecolor='r', facecolor='none')patch3 = Rectangle((200,190), 10, 10, edgecolor='r', facecolor='none')ax.add_patch(patch1)ax.add_patch(patch2)ax.add_patch(patch3)ax.imshow(overcast);" }, { "code": null, "e": 3934, "s": 3829, "text": "Though we do not have to, we can plot out the patches so that we can get an idea of what they look like." }, { "code": null, "e": 4558, "s": 3934, "text": "coor1 = Rectangle.get_bbox(patch1).get_points()coor2 = Rectangle.get_bbox(patch2).get_points()coor3 = Rectangle.get_bbox(patch3).get_points()image_patch1 = overcast[int(coor1[0][1]):int(coor1[1][1]), int(coor1[0][0]):int(coor1[1][0])]image_patch2 = overcast[int(coor2[0][1]):int(coor2[1][1]), int(coor2[0][0]):int(coor2[1][0])]image_patch3 = overcast[int(coor3[0][1]):int(coor3[1][1]), int(coor3[0][0]):int(coor3[1][0])]fig, ax = plt.subplots(1,3, figsize=(15, 12), dpi = 80)ax[0].imshow(image_patch1)ax[1].imshow(image_patch2)ax[2].imshow(image_patch3);" }, { "code": null, "e": 4787, "s": 4558, "text": "Like our first patch, these patches also show an array of colors. Let us now use each one in adjusting our image. To aid in this, let us first use Python’s list comprehension capabilities to create a list of the adjusted images." }, { "code": null, "e": 5097, "s": 4787, "text": "patch_list = [image_patch1, image_patch2, image_patch3]image_max_list = [(overcast / patch.max(axis=(0, 1))).clip(0, 1) for patch in patch_list]image_mean_list = [((overcast * patch.mean()) / overcast.mean(axis=(0, 1))).clip(0, 255).astype(int) for patch in patch_list]" }, { "code": null, "e": 5149, "s": 5097, "text": "Wonderful! Now we can simply call all these images." }, { "code": null, "e": 5163, "s": 5149, "text": "Let us begin." }, { "code": null, "e": 5600, "s": 5163, "text": "def patch_plotter(max_patch, mean_patch): fig, ax = plt.subplots(1,2, figsize=(15, 10), dpi = 80) f_size = 19 ax[0].imshow(max_patch) ax[0].set_title('Max Adjusted Patch', fontsize = f_size) ax[0].set_axis_off() ax[1].set_title('Mean Adjusted Patch', fontsize = f_size) ax[1].imshow(mean_patch); ax[1].set_axis_off() fig.tight_layout()for i in range(3): patch_plotter(image_max_list[i], image_mean_list[i])" }, { "code": null, "e": 6045, "s": 5600, "text": "We can see from the results that the Max adjusted patches perform much better than the Mean adjusted patches. Furthermore, it seems that the second patch faired the best. This seems to indicate that best batch is one that adjusts the image to a beige-like color. As a final exercise let us choose patches that fit that particular description. Also, we shall decrease the size of the patches to lessen the amount of color variety in the patches." }, { "code": null, "e": 6232, "s": 6045, "text": "Below is a function that can generate the ground truth adjusted images. We simply need to feed it our image, the names of the patches (for labelling purposes), and the patch coordinates." }, { "code": null, "e": 7877, "s": 6232, "text": "def ground_truth(image, patch_names, patch_coordinates): f_size = 25 figure_size = (17,12) patch_dict = dict(zip(patch_names, patch_coordinates)) coord = [] fig1, ax_1 = plt.subplots(1, 3, figsize = figure_size) for n, ax in enumerate(ax_1.flatten()): #Create Rectangles key = list(patch_dict.keys())[n] patch = Rectangle(patch_dict[key], 5, 5, edgecolor='r', facecolor='none') coord.append(Rectangle.get_bbox(patch).get_points()) ax.add_patch(patch); #Show and Format Images ax.imshow(image) ax.set_title(f'{key}', fontsize = f_size) ax.set_axis_off() fig1.tight_layout() fig2, ax_2 = plt.subplots(1, 3, figsize = figure_size) for n, ax in enumerate(ax_2.flatten()): #Show and Format Rectangles key = list(patch_dict.keys())[n] ax.imshow(image[int(coord[n][0][1]) : int(coord[n][1][1]), int(coord[n][0][0]) : int(coord[n][1][0])]); ax.set_title(key, fontsize = f_size) ax.set_axis_off() fig2.tight_layout()fig3, ax_3 = plt.subplots(1, 3, figsize = figure_size) for n, ax in enumerate(ax_3.flatten()): patch =image[int(coord[n][0][1]) : int(coord[n][1][1]), int(coord[n][0][0]) : int(coord[n][1][0])] image_max = (image / patch.max(axis=(0, 1))).clip(0, 1) ax.imshow(image_max) ax.set_title(f'Max : {patch_names[n]}', fontsize = f_size) ax.set_axis_off()fig3.tight_layout()ground_truth(overcast, ['First', 'Second', ' Third'], [(105, 275), (50, 45), (330, 105)])" }, { "code": null, "e": 8106, "s": 7877, "text": "We can see that among the different ground truth patches, the third patch performs the best. Though the image is noticeable bluer, the yellow overcast was completely removed. Additionally, overexposure is kept at a bare minimum." }, { "code": null, "e": 8120, "s": 8106, "text": "In Conclusion" }, { "code": null, "e": 8567, "s": 8120, "text": "We see that one does not need to be extremely well versed in the different ways color is interpreted by the machine. We can use the simple yet effective Ground Truth algorithm to adjust our images. This particular method may be more suited for individuals with an intuitive understanding of colors. Though good results did take a while to achieve, this method is worth keeping in mind as it one of the more straightforward ways to alter an image." } ]
Python in Sublime Text 3 with Sublime REPL and Anaconda | by Philipp Schmalen | Towards Data Science
Switch between projects with a keystroke and do not worry about switching build systems. Expedite your data science workflow with this project-centered setup. In this tutorial you will learn how to link Sublime Text 3 to an environment from Anaconda/Miniconda and execute Python with Sublime REPL. When you switch the project in Sublime, the build system switches as well to the conda environment associated with it. You might already have existing projects with different conda virtual environments - no worries. This setup can be easily applied to any project that you already have. Note: The guide is written for Windows 10. May look like many steps, but can be done in <1 min if you have evertyhing at hand. This is what you need to get going: Sublime Text 3, Package Control, Project Manager, Anaconda/Miniconda and a conda virtual environment. For example, I use example_env here. Open Sublime Text 3 and ensure you have package control, Sublime REPL and Project Manager. Shortcut to install with the command palette: CTRL+SHIFT+p, type install > Package Control: Install Package > [package name]Note the name of your conda env or create a new one conda create --name example_env python=3.8 -yAdd C:\Program Files\Sublime Text 3\ (or wherever subl.exe resides) to your system environment variables, open cmd in the project directory and open Sublime with subl .Add a new project to Project Manager with the command palette via CTRL+SHIFT+p > Project Manager: Add new projectCTRL+SHIFT+p type browse and select Preferences: Browse packages. The explorer opens in C:\Users\[YOURNAME]\AppData\Roaming\Sublime Text 3\Packages\. Navigate to SublimeREPL/config/Python, copy the file Main.sublime-menu and go back to C:\Users\[YOURNAME]\AppData\Roaming\Sublime Text 3\Packages\.Open the User folder, create the directories SublimeREPL\config\Python and paste Main.sublime-menu into the directory you just created (C:\Users\[YOURNAME]\AppData\Roaming\Sublime Text 3\Packages\User\SublimeREPL\config\Python). Rename Main.sublime-menu into example_env.sublime-menu and open it with Sublime.Search for the block where "id": "repl_python_run", and find"cmd": ["python", "-u", "$file_basename"],. We replace "python" with the path to the conda env we want to have linked with the project and save. For example: "cmd": ["C:\\Users\\philipp\\miniconda3\\envs\\example_env\\python.exe", "-u", "$file_basename"],.CTRL+SHIFT+p find Project: edit project. Insert the snippet below to define a build system for the project. Replace example_env with the conda env you want. Open Sublime Text 3 and ensure you have package control, Sublime REPL and Project Manager. Shortcut to install with the command palette: CTRL+SHIFT+p, type install > Package Control: Install Package > [package name] Note the name of your conda env or create a new one conda create --name example_env python=3.8 -y Add C:\Program Files\Sublime Text 3\ (or wherever subl.exe resides) to your system environment variables, open cmd in the project directory and open Sublime with subl . Add a new project to Project Manager with the command palette via CTRL+SHIFT+p > Project Manager: Add new project CTRL+SHIFT+p type browse and select Preferences: Browse packages. The explorer opens in C:\Users\[YOURNAME]\AppData\Roaming\Sublime Text 3\Packages\. Navigate to SublimeREPL/config/Python, copy the file Main.sublime-menu and go back to C:\Users\[YOURNAME]\AppData\Roaming\Sublime Text 3\Packages\. Open the User folder, create the directories SublimeREPL\config\Python and paste Main.sublime-menu into the directory you just created (C:\Users\[YOURNAME]\AppData\Roaming\Sublime Text 3\Packages\User\SublimeREPL\config\Python). Rename Main.sublime-menu into example_env.sublime-menu and open it with Sublime. Search for the block where "id": "repl_python_run", and find"cmd": ["python", "-u", "$file_basename"],. We replace "python" with the path to the conda env we want to have linked with the project and save. For example: "cmd": ["C:\\Users\\philipp\\miniconda3\\envs\\example_env\\python.exe", "-u", "$file_basename"],. CTRL+SHIFT+p find Project: edit project. Insert the snippet below to define a build system for the project. Replace example_env with the conda env you want. { "build_systems": [ { "name": "Conda Python example_env REPL", "target": "run_existing_window_command", "id": "repl_python_run", "file": "config/Python/example_env.sublime-menu", } ], ... } Awesome! Switch easily between projects with CTRL+ ALT + p and do not worry about the conda environment. The setting is project specific. I hope this expedites your workflow. Have fun with all your future projects! If you encountered any issues, refer to the more extensive guide below. Let me know when you still have issues, something is unclear or you just want to say hello. Any kind of feedback is much appreciated. This post was inspired by community efforts on Stackoverflow . My approach avoids that the Sublime build-system menu will be filled with every virtual environment you link to REPL. Furthermore, the solution here is project-centered or environment-centered instead of a global setting. The more projects you have, the more virtual environments you create — the more important project-specific settings become. I experienced this recently when three projects ran in parallel and I had to frequently switch between them. Switching projects and build systems disrupted my workflow. I needed a fast way to switch and have each build system changed as well. My workflow relies on Sublime Text 3, Anaconda and Sublime REPL, so I wanted a solution for these tools. This article suggests a way to smoothly integrate them for a quick & stable project setup. What do we need for a lightweight and fast Python setup? quickly load files with a lightweight text editor → Sublime Text 3 switch effortlessly between projects →Sublime Project Manager handle dependencies with virtual environments defined for each project → Anaconda/Miniconda have a build system with an interactive command line →Sublime REPL The setup presented here lets you switch between projects and their related virtual environments with CTRL+ALT+p. After selecting another project the build system switches as well to what you have defined in the project settings. A few steps have to be followed, but it is worth it. Hopefully you find this useful, as well. Install the following if you do not have it already: Sublime Text 3: https://www.sublimetext.com/3Sublime Package Control: https://packagecontrol.io/installationProject Manager: https://packagecontrol.io/packages/ProjectManagerSublime REPL: https://packagecontrol.io/packages/SublimeREPLAnaconda/Miniconda: https://docs.conda.io/en/latest/miniconda.html a. I use example_env for the whole tutorial (conda create --name example_env python=3.8 -y) Sublime Text 3: https://www.sublimetext.com/3 Sublime Package Control: https://packagecontrol.io/installation Project Manager: https://packagecontrol.io/packages/ProjectManager Sublime REPL: https://packagecontrol.io/packages/SublimeREPL Anaconda/Miniconda: https://docs.conda.io/en/latest/miniconda.html a. I use example_env for the whole tutorial (conda create --name example_env python=3.8 -y) This tutorial assumes Windows 10, but should similarly work on Linux. I recommend using Miniconda, see why on Reddit We installed everything from the above list and have a conda environment. I use example_env as a conda environment. The first step is to center Sublime around the project root folder. In this way, all shortcuts like jumping to a file with CTRL+p relate to the project root ./. Then we initialize the Project Manager. Let us open a new instance of Sublime at the project root like C:\Users\[YOURNAME]\[PATH-TO-PROJECT]\[PROJECTNAME]. I have Sublime added to my environment variables (find a short how-to below) and open a terminal in the project root directory which is C:\Users\philipp\projects\Sublime project setup. Access the address bar with CTRL+l, type cmd to open command, Enter. Run subl . (only works if you added subl.exe to your Windows environment variables - find a short howto in the appendix below). An empty Sublime window opens. There you go! Now we turn towards the Project Manager. Add a new project to Project Manager with the command palette via CTRL+SHIFT+p > Project Manager: Add new project. Check out the project setting file with CTRL+SHIFT+p > Project Manger: Edit project. Sublime stores your project settings here, including project name and path: { "folders": [ { "binary_file_patterns": [ ], "file_exclude_patterns": [ ], "folder_exclude_patterns": [ ], "name": "Sublime project setup", "path": "C:\\Users\\philipp\\projects\\Sublime project setup" } ] } Next, we define a build system which takes the python.exe of the project conda env, example_env. Note the name of your conda environment. For example, I created an environment with conda create --name example_env python=3.8 -y for this tutorial. So, I use example_env as an environment here. CTRL+SHIFT+p type browse and select Preferences: Browse packages. The browser opens in C:\Users\[YOURNAME]\AppData\Roaming\Sublime Text 3\Packages\.From here, navigate to SublimeREPL/config/Python and copy the file Main.sublime-menuGo back to C:\Users\[YOURNAME]\AppData\Roaming\Sublime Text 3\Packages\, open User and create the following folders: SublimeREPL\config\Python.Now you are in C:\Users\[YOURNAME]\AppData\Roaming\Sublime Text 3\Packages\User\SublimeREPL\config\Python and paste the Main.sublime-menu into the directory.Rename Main.sublime-menu into example_env.sublime-menu and open it with SublimeImportant step: Search for the block where "id": "repl_python_run",, replace "cmd": ["python", "-u", "$file_basename"], with "cmd": ["C:\\Users\\[YOURNAME]\\[PATHTOCONDA]\\envs\\example_env\\python.exe", "-u", "$file_basename"], and save. Note: Replace the path with any path that leads to the python.exe of your conda environment. In my case this is C:\\Users\\philipp\\Miniconda3\\envs\\example_env\\python.exe.Open the command palette with CTRL+SHIFT+p find Project: edit project and select the project name. Now we define the build systems that use the Python of our conda environment, example_env. Copy-paste the following snippet and replace example_env with the name of your environment. Important: There are 2 replacements in total in bold. CTRL+SHIFT+p type browse and select Preferences: Browse packages. The browser opens in C:\Users\[YOURNAME]\AppData\Roaming\Sublime Text 3\Packages\. From here, navigate to SublimeREPL/config/Python and copy the file Main.sublime-menu Go back to C:\Users\[YOURNAME]\AppData\Roaming\Sublime Text 3\Packages\, open User and create the following folders: SublimeREPL\config\Python. Now you are in C:\Users\[YOURNAME]\AppData\Roaming\Sublime Text 3\Packages\User\SublimeREPL\config\Python and paste the Main.sublime-menu into the directory. Rename Main.sublime-menu into example_env.sublime-menu and open it with Sublime Important step: Search for the block where "id": "repl_python_run",, replace "cmd": ["python", "-u", "$file_basename"], with "cmd": ["C:\\Users\\[YOURNAME]\\[PATHTOCONDA]\\envs\\example_env\\python.exe", "-u", "$file_basename"], and save. Note: Replace the path with any path that leads to the python.exe of your conda environment. In my case this is C:\\Users\\philipp\\Miniconda3\\envs\\example_env\\python.exe. Open the command palette with CTRL+SHIFT+p find Project: edit project and select the project name. Now we define the build systems that use the Python of our conda environment, example_env. Copy-paste the following snippet and replace example_env with the name of your environment. Important: There are 2 replacements in total in bold. { "build_systems": [ { "name": "Conda Python example_env REPL", "target": "run_existing_window_command", "id": "repl_python_run", "file": "config/Python/example_env.sublime-menu", } ], "folders": [ { "binary_file_patterns": [ ], "file_exclude_patterns": [ ], "folder_exclude_patterns": [ ], "name": "example project", "path": "C:\\Users\\[YOURNAME]\\Projects\\example_project" } ] } To briefly test the setup, create a new file like test.py and insert Run the file with our build system (here: Conda Python example_env REPL): I hope it is working until now. If not, please drop me a message or leave a comment! This setup reveals its strength when you work on several projects in parallel. You can (i) switch between projects in no time with CTRL+ ALT + p and (ii) have the related virtual environment among your build systems. To set up a new project, start out with subl . from the command line and repeat all steps from the Solution section. Doing this around two times, it will come natural in <1 min. I am sure there are other approaches and project setups which I not yet figured out. So, I appreciate any tips and best practices for project settings in Sublime, REPL and Anaconda. If there is someone who wants to automate the process and implements a project-based build system for Sublime REPL — I would be grateful! I think many others would benefit from this. It would link the best tools from the Sublime-Anaconda and REPL-world. In this tutorial you learned how to set up Sublime REPL and link it to your conda environment. In this way you can have several environments across projects and switch easily with Sublime’s Project Manager and its shortcut CTRL+ ALT+p. Have fun with your new setup and enjoy your projects! Drop me a message if you found this helpful or even encountered some issues with the setup. Feedback is greatly appreciated! Looking further for intermediate tips and tricks to develop your data science workflow? Stay tuned for the next post about data science tools 2021. Shortcut for Windows users: Hit Windows key, type env and select Edit environment variables for your account from the search results. Then click Path > Edit > New > C:\Program Files\Sublime Text 3\ > OK. Replace C:\Program Files\Sublime Text 3\ with the directory where you find subl.exe. Also see this tutorial. stackoverflow.com damnwidget.github.io Originally published at https://philippschmalen.github.io.
[ { "code": null, "e": 331, "s": 172, "text": "Switch between projects with a keystroke and do not worry about switching build systems. Expedite your data science workflow with this project-centered setup." }, { "code": null, "e": 589, "s": 331, "text": "In this tutorial you will learn how to link Sublime Text 3 to an environment from Anaconda/Miniconda and execute Python with Sublime REPL. When you switch the project in Sublime, the build system switches as well to the conda environment associated with it." }, { "code": null, "e": 800, "s": 589, "text": "You might already have existing projects with different conda virtual environments - no worries. This setup can be easily applied to any project that you already have. Note: The guide is written for Windows 10." }, { "code": null, "e": 1059, "s": 800, "text": "May look like many steps, but can be done in <1 min if you have evertyhing at hand. This is what you need to get going: Sublime Text 3, Package Control, Project Manager, Anaconda/Miniconda and a conda virtual environment. For example, I use example_env here." }, { "code": null, "e": 2731, "s": 1059, "text": "Open Sublime Text 3 and ensure you have package control, Sublime REPL and Project Manager. Shortcut to install with the command palette: CTRL+SHIFT+p, type install > Package Control: Install Package > [package name]Note the name of your conda env or create a new one conda create --name example_env python=3.8 -yAdd C:\\Program Files\\Sublime Text 3\\ (or wherever subl.exe resides) to your system environment variables, open cmd in the project directory and open Sublime with subl .Add a new project to Project Manager with the command palette via CTRL+SHIFT+p > Project Manager: Add new projectCTRL+SHIFT+p type browse and select Preferences: Browse packages. The explorer opens in C:\\Users\\[YOURNAME]\\AppData\\Roaming\\Sublime Text 3\\Packages\\. Navigate to SublimeREPL/config/Python, copy the file Main.sublime-menu and go back to C:\\Users\\[YOURNAME]\\AppData\\Roaming\\Sublime Text 3\\Packages\\.Open the User folder, create the directories SublimeREPL\\config\\Python and paste Main.sublime-menu into the directory you just created (C:\\Users\\[YOURNAME]\\AppData\\Roaming\\Sublime Text 3\\Packages\\User\\SublimeREPL\\config\\Python). Rename Main.sublime-menu into example_env.sublime-menu and open it with Sublime.Search for the block where \"id\": \"repl_python_run\", and find\"cmd\": [\"python\", \"-u\", \"$file_basename\"],. We replace \"python\" with the path to the conda env we want to have linked with the project and save. For example: \"cmd\": [\"C:\\\\Users\\\\philipp\\\\miniconda3\\\\envs\\\\example_env\\\\python.exe\", \"-u\", \"$file_basename\"],.CTRL+SHIFT+p find Project: edit project. Insert the snippet below to define a build system for the project. Replace example_env with the conda env you want." }, { "code": null, "e": 2947, "s": 2731, "text": "Open Sublime Text 3 and ensure you have package control, Sublime REPL and Project Manager. Shortcut to install with the command palette: CTRL+SHIFT+p, type install > Package Control: Install Package > [package name]" }, { "code": null, "e": 3045, "s": 2947, "text": "Note the name of your conda env or create a new one conda create --name example_env python=3.8 -y" }, { "code": null, "e": 3214, "s": 3045, "text": "Add C:\\Program Files\\Sublime Text 3\\ (or wherever subl.exe resides) to your system environment variables, open cmd in the project directory and open Sublime with subl ." }, { "code": null, "e": 3328, "s": 3214, "text": "Add a new project to Project Manager with the command palette via CTRL+SHIFT+p > Project Manager: Add new project" }, { "code": null, "e": 3626, "s": 3328, "text": "CTRL+SHIFT+p type browse and select Preferences: Browse packages. The explorer opens in C:\\Users\\[YOURNAME]\\AppData\\Roaming\\Sublime Text 3\\Packages\\. Navigate to SublimeREPL/config/Python, copy the file Main.sublime-menu and go back to C:\\Users\\[YOURNAME]\\AppData\\Roaming\\Sublime Text 3\\Packages\\." }, { "code": null, "e": 3936, "s": 3626, "text": "Open the User folder, create the directories SublimeREPL\\config\\Python and paste Main.sublime-menu into the directory you just created (C:\\Users\\[YOURNAME]\\AppData\\Roaming\\Sublime Text 3\\Packages\\User\\SublimeREPL\\config\\Python). Rename Main.sublime-menu into example_env.sublime-menu and open it with Sublime." }, { "code": null, "e": 4253, "s": 3936, "text": "Search for the block where \"id\": \"repl_python_run\", and find\"cmd\": [\"python\", \"-u\", \"$file_basename\"],. We replace \"python\" with the path to the conda env we want to have linked with the project and save. For example: \"cmd\": [\"C:\\\\Users\\\\philipp\\\\miniconda3\\\\envs\\\\example_env\\\\python.exe\", \"-u\", \"$file_basename\"],." }, { "code": null, "e": 4410, "s": 4253, "text": "CTRL+SHIFT+p find Project: edit project. Insert the snippet below to define a build system for the project. Replace example_env with the conda env you want." }, { "code": null, "e": 4601, "s": 4410, "text": "{ \"build_systems\": [ { \"name\": \"Conda Python example_env REPL\", \"target\": \"run_existing_window_command\", \"id\": \"repl_python_run\", \"file\": \"config/Python/example_env.sublime-menu\", } ], ... }" }, { "code": null, "e": 4816, "s": 4601, "text": "Awesome! Switch easily between projects with CTRL+ ALT + p and do not worry about the conda environment. The setting is project specific. I hope this expedites your workflow. Have fun with all your future projects!" }, { "code": null, "e": 5022, "s": 4816, "text": "If you encountered any issues, refer to the more extensive guide below. Let me know when you still have issues, something is unclear or you just want to say hello. Any kind of feedback is much appreciated." }, { "code": null, "e": 5307, "s": 5022, "text": "This post was inspired by community efforts on Stackoverflow . My approach avoids that the Sublime build-system menu will be filled with every virtual environment you link to REPL. Furthermore, the solution here is project-centered or environment-centered instead of a global setting." }, { "code": null, "e": 5870, "s": 5307, "text": "The more projects you have, the more virtual environments you create — the more important project-specific settings become. I experienced this recently when three projects ran in parallel and I had to frequently switch between them. Switching projects and build systems disrupted my workflow. I needed a fast way to switch and have each build system changed as well. My workflow relies on Sublime Text 3, Anaconda and Sublime REPL, so I wanted a solution for these tools. This article suggests a way to smoothly integrate them for a quick & stable project setup." }, { "code": null, "e": 5927, "s": 5870, "text": "What do we need for a lightweight and fast Python setup?" }, { "code": null, "e": 5994, "s": 5927, "text": "quickly load files with a lightweight text editor → Sublime Text 3" }, { "code": null, "e": 6056, "s": 5994, "text": "switch effortlessly between projects →Sublime Project Manager" }, { "code": null, "e": 6148, "s": 6056, "text": "handle dependencies with virtual environments defined for each project → Anaconda/Miniconda" }, { "code": null, "e": 6215, "s": 6148, "text": "have a build system with an interactive command line →Sublime REPL" }, { "code": null, "e": 6539, "s": 6215, "text": "The setup presented here lets you switch between projects and their related virtual environments with CTRL+ALT+p. After selecting another project the build system switches as well to what you have defined in the project settings. A few steps have to be followed, but it is worth it. Hopefully you find this useful, as well." }, { "code": null, "e": 6592, "s": 6539, "text": "Install the following if you do not have it already:" }, { "code": null, "e": 6985, "s": 6592, "text": "Sublime Text 3: https://www.sublimetext.com/3Sublime Package Control: https://packagecontrol.io/installationProject Manager: https://packagecontrol.io/packages/ProjectManagerSublime REPL: https://packagecontrol.io/packages/SublimeREPLAnaconda/Miniconda: https://docs.conda.io/en/latest/miniconda.html a. I use example_env for the whole tutorial (conda create --name example_env python=3.8 -y)" }, { "code": null, "e": 7031, "s": 6985, "text": "Sublime Text 3: https://www.sublimetext.com/3" }, { "code": null, "e": 7095, "s": 7031, "text": "Sublime Package Control: https://packagecontrol.io/installation" }, { "code": null, "e": 7162, "s": 7095, "text": "Project Manager: https://packagecontrol.io/packages/ProjectManager" }, { "code": null, "e": 7223, "s": 7162, "text": "Sublime REPL: https://packagecontrol.io/packages/SublimeREPL" }, { "code": null, "e": 7382, "s": 7223, "text": "Anaconda/Miniconda: https://docs.conda.io/en/latest/miniconda.html a. I use example_env for the whole tutorial (conda create --name example_env python=3.8 -y)" }, { "code": null, "e": 7499, "s": 7382, "text": "This tutorial assumes Windows 10, but should similarly work on Linux. I recommend using Miniconda, see why on Reddit" }, { "code": null, "e": 7816, "s": 7499, "text": "We installed everything from the above list and have a conda environment. I use example_env as a conda environment. The first step is to center Sublime around the project root folder. In this way, all shortcuts like jumping to a file with CTRL+p relate to the project root ./. Then we initialize the Project Manager." }, { "code": null, "e": 8360, "s": 7816, "text": "Let us open a new instance of Sublime at the project root like C:\\Users\\[YOURNAME]\\[PATH-TO-PROJECT]\\[PROJECTNAME]. I have Sublime added to my environment variables (find a short how-to below) and open a terminal in the project root directory which is C:\\Users\\philipp\\projects\\Sublime project setup. Access the address bar with CTRL+l, type cmd to open command, Enter. Run subl . (only works if you added subl.exe to your Windows environment variables - find a short howto in the appendix below). An empty Sublime window opens. There you go!" }, { "code": null, "e": 8677, "s": 8360, "text": "Now we turn towards the Project Manager. Add a new project to Project Manager with the command palette via CTRL+SHIFT+p > Project Manager: Add new project. Check out the project setting file with CTRL+SHIFT+p > Project Manger: Edit project. Sublime stores your project settings here, including project name and path:" }, { "code": null, "e": 8886, "s": 8677, "text": "{ \"folders\": [ { \"binary_file_patterns\": [ ], \"file_exclude_patterns\": [ ], \"folder_exclude_patterns\": [ ], \"name\": \"Sublime project setup\", \"path\": \"C:\\\\Users\\\\philipp\\\\projects\\\\Sublime project setup\" } ] }" }, { "code": null, "e": 9178, "s": 8886, "text": "Next, we define a build system which takes the python.exe of the project conda env, example_env. Note the name of your conda environment. For example, I created an environment with conda create --name example_env python=3.8 -y for this tutorial. So, I use example_env as an environment here." }, { "code": null, "e": 10538, "s": 9178, "text": "CTRL+SHIFT+p type browse and select Preferences: Browse packages. The browser opens in C:\\Users\\[YOURNAME]\\AppData\\Roaming\\Sublime Text 3\\Packages\\.From here, navigate to SublimeREPL/config/Python and copy the file Main.sublime-menuGo back to C:\\Users\\[YOURNAME]\\AppData\\Roaming\\Sublime Text 3\\Packages\\, open User and create the following folders: SublimeREPL\\config\\Python.Now you are in C:\\Users\\[YOURNAME]\\AppData\\Roaming\\Sublime Text 3\\Packages\\User\\SublimeREPL\\config\\Python and paste the Main.sublime-menu into the directory.Rename Main.sublime-menu into example_env.sublime-menu and open it with SublimeImportant step: Search for the block where \"id\": \"repl_python_run\",, replace \"cmd\": [\"python\", \"-u\", \"$file_basename\"], with \"cmd\": [\"C:\\\\Users\\\\[YOURNAME]\\\\[PATHTOCONDA]\\\\envs\\\\example_env\\\\python.exe\", \"-u\", \"$file_basename\"], and save. Note: Replace the path with any path that leads to the python.exe of your conda environment. In my case this is C:\\\\Users\\\\philipp\\\\Miniconda3\\\\envs\\\\example_env\\\\python.exe.Open the command palette with CTRL+SHIFT+p find Project: edit project and select the project name. Now we define the build systems that use the Python of our conda environment, example_env. Copy-paste the following snippet and replace example_env with the name of your environment. Important: There are 2 replacements in total in bold." }, { "code": null, "e": 10687, "s": 10538, "text": "CTRL+SHIFT+p type browse and select Preferences: Browse packages. The browser opens in C:\\Users\\[YOURNAME]\\AppData\\Roaming\\Sublime Text 3\\Packages\\." }, { "code": null, "e": 10772, "s": 10687, "text": "From here, navigate to SublimeREPL/config/Python and copy the file Main.sublime-menu" }, { "code": null, "e": 10916, "s": 10772, "text": "Go back to C:\\Users\\[YOURNAME]\\AppData\\Roaming\\Sublime Text 3\\Packages\\, open User and create the following folders: SublimeREPL\\config\\Python." }, { "code": null, "e": 11074, "s": 10916, "text": "Now you are in C:\\Users\\[YOURNAME]\\AppData\\Roaming\\Sublime Text 3\\Packages\\User\\SublimeREPL\\config\\Python and paste the Main.sublime-menu into the directory." }, { "code": null, "e": 11154, "s": 11074, "text": "Rename Main.sublime-menu into example_env.sublime-menu and open it with Sublime" }, { "code": null, "e": 11568, "s": 11154, "text": "Important step: Search for the block where \"id\": \"repl_python_run\",, replace \"cmd\": [\"python\", \"-u\", \"$file_basename\"], with \"cmd\": [\"C:\\\\Users\\\\[YOURNAME]\\\\[PATHTOCONDA]\\\\envs\\\\example_env\\\\python.exe\", \"-u\", \"$file_basename\"], and save. Note: Replace the path with any path that leads to the python.exe of your conda environment. In my case this is C:\\\\Users\\\\philipp\\\\Miniconda3\\\\envs\\\\example_env\\\\python.exe." }, { "code": null, "e": 11904, "s": 11568, "text": "Open the command palette with CTRL+SHIFT+p find Project: edit project and select the project name. Now we define the build systems that use the Python of our conda environment, example_env. Copy-paste the following snippet and replace example_env with the name of your environment. Important: There are 2 replacements in total in bold." }, { "code": null, "e": 12287, "s": 11904, "text": "{ \"build_systems\": [ { \"name\": \"Conda Python example_env REPL\", \"target\": \"run_existing_window_command\", \"id\": \"repl_python_run\", \"file\": \"config/Python/example_env.sublime-menu\", } ], \"folders\": [ { \"binary_file_patterns\": [ ], \"file_exclude_patterns\": [ ], \"folder_exclude_patterns\": [ ], \"name\": \"example project\", \"path\": \"C:\\\\Users\\\\[YOURNAME]\\\\Projects\\\\example_project\" } ] }" }, { "code": null, "e": 12356, "s": 12287, "text": "To briefly test the setup, create a new file like test.py and insert" }, { "code": null, "e": 12430, "s": 12356, "text": "Run the file with our build system (here: Conda Python example_env REPL):" }, { "code": null, "e": 12515, "s": 12430, "text": "I hope it is working until now. If not, please drop me a message or leave a comment!" }, { "code": null, "e": 12732, "s": 12515, "text": "This setup reveals its strength when you work on several projects in parallel. You can (i) switch between projects in no time with CTRL+ ALT + p and (ii) have the related virtual environment among your build systems." }, { "code": null, "e": 12910, "s": 12732, "text": "To set up a new project, start out with subl . from the command line and repeat all steps from the Solution section. Doing this around two times, it will come natural in <1 min." }, { "code": null, "e": 13092, "s": 12910, "text": "I am sure there are other approaches and project setups which I not yet figured out. So, I appreciate any tips and best practices for project settings in Sublime, REPL and Anaconda." }, { "code": null, "e": 13346, "s": 13092, "text": "If there is someone who wants to automate the process and implements a project-based build system for Sublime REPL — I would be grateful! I think many others would benefit from this. It would link the best tools from the Sublime-Anaconda and REPL-world." }, { "code": null, "e": 13636, "s": 13346, "text": "In this tutorial you learned how to set up Sublime REPL and link it to your conda environment. In this way you can have several environments across projects and switch easily with Sublime’s Project Manager and its shortcut CTRL+ ALT+p. Have fun with your new setup and enjoy your projects!" }, { "code": null, "e": 13761, "s": 13636, "text": "Drop me a message if you found this helpful or even encountered some issues with the setup. Feedback is greatly appreciated!" }, { "code": null, "e": 13909, "s": 13761, "text": "Looking further for intermediate tips and tricks to develop your data science workflow? Stay tuned for the next post about data science tools 2021." }, { "code": null, "e": 14043, "s": 13909, "text": "Shortcut for Windows users: Hit Windows key, type env and select Edit environment variables for your account from the search results." }, { "code": null, "e": 14222, "s": 14043, "text": "Then click Path > Edit > New > C:\\Program Files\\Sublime Text 3\\ > OK. Replace C:\\Program Files\\Sublime Text 3\\ with the directory where you find subl.exe. Also see this tutorial." }, { "code": null, "e": 14240, "s": 14222, "text": "stackoverflow.com" }, { "code": null, "e": 14261, "s": 14240, "text": "damnwidget.github.io" } ]
Fundamental Statistics. Time Series Modeling With Python Code | by Jiahui Wang | Towards Data Science
Time series data is everywhere around us, ranging from the stock market price to the daily temperature of your city. As its name suggests, the x axis of time series data is time. We are always standing at the current time point. Towards the left-hand side of the x axis, we are looking into the past. If we are lucky, at a simple glimpse, we may be able to find some periodic patterns in the past. Or, if we put in more effort and pull some other variables, we may be able to get some ‘correlations’ to explain our past data. But, can we evaluate how well these other variables models the data? Will these ‘correlations’ hold in the future? Can we count on these past ‘correlations’ and make predictions? If you also have these questions, let’s explore analysing and modeling time series data together! I will code using Python to conduct some experiments and statistical tests. A good thing about learning statistics using Python is that we can use established libraries and plot nice graphs to better understand the complex statistical concepts. In the future, I also plan to have the following posts: Time Series Modeling With Python Code: How To Analyse A Single Time Series Variable. Time Series Modeling With Python Code: How To Analyse Multiple Time Series Variable. Time Series Modeling With Python Code: How To Model Time Series Data With Linear Regression. Since I will start from the very basic statistical concepts to more complex analysis and modeling, if you are a beginner to time series data, I would strongly recommend you start from this post. Population has an underlying distribution process, which we usually are not able to know exactly. What we can do is to sample from the population and use the samples to estimate the population. But how to choose the proper estimators? There are three properties to define a good estimator: unbiased, consistent, and efficient. The estimator is unbiased, when the expected value of the sample parameter is equal to the population parameter: If the variance of the sample parameter decreases with the increasing sample size, the estimator is consistent. With the same sample size, the estimator with lower variance is more efficient. The probability density distribution (PDF) is used to specify the probability of the random variable falling within a particular range of values. The probability density at a certain x is denoted as f(x). By applying integral function to f(x) over a range of (x1,x2), the probability of x falling in (x1,x2) can be calculated. Central Limit Theorem states that when the sample size is large, the sample mean of the independent random variable follows normal distribution. Typically, when sample size is larger than 30, the requirement of large sample size is considered fulfilled. The independent random variables can follow any distribution, while the sample mean of these independent random variables follows normal distribution. import numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import normmeanList = []num_trials = 10000num_observations = 1000for i in range(num_trials): # sample from uniform distribution numList = np.random.randint(1,7,num_observations) # sample from normal distribution #numList = np.random.normal(loc=0,scale=1,size=num_observations) # sample from poisson distribution #numList = np.random.poisson(lam=1,size=num_observations) meanList.append(np.mean(numList))mu, std = norm.fit(meanList)fig, ax = plt.subplots()ax.hist(meanList, bins=20, density=True, alpha=1, color='#4495c9')xmin, xmax = ax.get_xlim()x = np.linspace(xmin, xmax, 100)p = norm.pdf(x, mu, std)ax.plot(x, p, 'k', linewidth=4)ax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)ax.set_yticks([])plt.show() Law of large numbers states that given a large number of trials, the average of the estimator gets closer to the theoretical value. For the above experiment, if we only repeat the trials for 10 times, the distribution will be very different from the plots. If you are interested, you can quickly test out the results to visualize how law of large numbers makes a difference. Given that only sample parameters can be calculated, we need to make inference on the population parameters using hypothesis testing. In hypothesis testing, a set of complementary hypotheses is proposed, which consists of a null hypothesis and an alternative hypothesis. When conducting the hypothesis testing, we choose to believe that the null hypothesis holds true. If the observed value is likely to occur under the condition that the null hypothesis is true, then we do not reject the null hypothesis. However, if the observed value is unlikely to occur, then we reject the null hypothesis and accept the alternative hypothesis. Before conducting hypothesis testing, we need to define a significance level first. Significance level determines the level that we want to believe in the null hypothesis. If we set the significance level as 0.05, then as long as the probability of the observation is higher than 5%, we do not reject the null hypothesis. However, if the probability of the observation falls below 5%, we reject the null hypothesis and accept the alternative hypothesis. There is a tradeoff between the Type I and Type II error. Basically, a higher significance level makes it easier to reject the null hypothesis. Although in this way, a higher significance level reduces the Type II error, it also results in a higher Type I error at the same time. The only way to reduce both Type I and Type II error is by increasing the sample size. The probability of the observed value is called p value. A low p value means that the observation is unlikely to occur under the condition that the null hypothesis holds true. When the p value is lower than significance level, then we reject the null hypothesis. However, one thing to note is that p value should be interpreted as binary: it is only larger or smaller than the significance level. In this post, I highlighted some fundamental statistical concepts which are important to understand the future posts on analysing and modeling time series data. Hope you are confident to make a further step on our journal to explore time series data! Stay tuned for the following post on how to analyse a single time series variable!
[ { "code": null, "e": 876, "s": 171, "text": "Time series data is everywhere around us, ranging from the stock market price to the daily temperature of your city. As its name suggests, the x axis of time series data is time. We are always standing at the current time point. Towards the left-hand side of the x axis, we are looking into the past. If we are lucky, at a simple glimpse, we may be able to find some periodic patterns in the past. Or, if we put in more effort and pull some other variables, we may be able to get some ‘correlations’ to explain our past data. But, can we evaluate how well these other variables models the data? Will these ‘correlations’ hold in the future? Can we count on these past ‘correlations’ and make predictions?" }, { "code": null, "e": 1219, "s": 876, "text": "If you also have these questions, let’s explore analysing and modeling time series data together! I will code using Python to conduct some experiments and statistical tests. A good thing about learning statistics using Python is that we can use established libraries and plot nice graphs to better understand the complex statistical concepts." }, { "code": null, "e": 1275, "s": 1219, "text": "In the future, I also plan to have the following posts:" }, { "code": null, "e": 1360, "s": 1275, "text": "Time Series Modeling With Python Code: How To Analyse A Single Time Series Variable." }, { "code": null, "e": 1445, "s": 1360, "text": "Time Series Modeling With Python Code: How To Analyse Multiple Time Series Variable." }, { "code": null, "e": 1538, "s": 1445, "text": "Time Series Modeling With Python Code: How To Model Time Series Data With Linear Regression." }, { "code": null, "e": 1733, "s": 1538, "text": "Since I will start from the very basic statistical concepts to more complex analysis and modeling, if you are a beginner to time series data, I would strongly recommend you start from this post." }, { "code": null, "e": 2060, "s": 1733, "text": "Population has an underlying distribution process, which we usually are not able to know exactly. What we can do is to sample from the population and use the samples to estimate the population. But how to choose the proper estimators? There are three properties to define a good estimator: unbiased, consistent, and efficient." }, { "code": null, "e": 2173, "s": 2060, "text": "The estimator is unbiased, when the expected value of the sample parameter is equal to the population parameter:" }, { "code": null, "e": 2285, "s": 2173, "text": "If the variance of the sample parameter decreases with the increasing sample size, the estimator is consistent." }, { "code": null, "e": 2365, "s": 2285, "text": "With the same sample size, the estimator with lower variance is more efficient." }, { "code": null, "e": 2692, "s": 2365, "text": "The probability density distribution (PDF) is used to specify the probability of the random variable falling within a particular range of values. The probability density at a certain x is denoted as f(x). By applying integral function to f(x) over a range of (x1,x2), the probability of x falling in (x1,x2) can be calculated." }, { "code": null, "e": 3097, "s": 2692, "text": "Central Limit Theorem states that when the sample size is large, the sample mean of the independent random variable follows normal distribution. Typically, when sample size is larger than 30, the requirement of large sample size is considered fulfilled. The independent random variables can follow any distribution, while the sample mean of these independent random variables follows normal distribution." }, { "code": null, "e": 3954, "s": 3097, "text": "import numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import normmeanList = []num_trials = 10000num_observations = 1000for i in range(num_trials): # sample from uniform distribution numList = np.random.randint(1,7,num_observations) # sample from normal distribution #numList = np.random.normal(loc=0,scale=1,size=num_observations) # sample from poisson distribution #numList = np.random.poisson(lam=1,size=num_observations) meanList.append(np.mean(numList))mu, std = norm.fit(meanList)fig, ax = plt.subplots()ax.hist(meanList, bins=20, density=True, alpha=1, color='#4495c9')xmin, xmax = ax.get_xlim()x = np.linspace(xmin, xmax, 100)p = norm.pdf(x, mu, std)ax.plot(x, p, 'k', linewidth=4)ax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)ax.set_yticks([])plt.show()" }, { "code": null, "e": 4329, "s": 3954, "text": "Law of large numbers states that given a large number of trials, the average of the estimator gets closer to the theoretical value. For the above experiment, if we only repeat the trials for 10 times, the distribution will be very different from the plots. If you are interested, you can quickly test out the results to visualize how law of large numbers makes a difference." }, { "code": null, "e": 4963, "s": 4329, "text": "Given that only sample parameters can be calculated, we need to make inference on the population parameters using hypothesis testing. In hypothesis testing, a set of complementary hypotheses is proposed, which consists of a null hypothesis and an alternative hypothesis. When conducting the hypothesis testing, we choose to believe that the null hypothesis holds true. If the observed value is likely to occur under the condition that the null hypothesis is true, then we do not reject the null hypothesis. However, if the observed value is unlikely to occur, then we reject the null hypothesis and accept the alternative hypothesis." }, { "code": null, "e": 5784, "s": 4963, "text": "Before conducting hypothesis testing, we need to define a significance level first. Significance level determines the level that we want to believe in the null hypothesis. If we set the significance level as 0.05, then as long as the probability of the observation is higher than 5%, we do not reject the null hypothesis. However, if the probability of the observation falls below 5%, we reject the null hypothesis and accept the alternative hypothesis. There is a tradeoff between the Type I and Type II error. Basically, a higher significance level makes it easier to reject the null hypothesis. Although in this way, a higher significance level reduces the Type II error, it also results in a higher Type I error at the same time. The only way to reduce both Type I and Type II error is by increasing the sample size." }, { "code": null, "e": 6181, "s": 5784, "text": "The probability of the observed value is called p value. A low p value means that the observation is unlikely to occur under the condition that the null hypothesis holds true. When the p value is lower than significance level, then we reject the null hypothesis. However, one thing to note is that p value should be interpreted as binary: it is only larger or smaller than the significance level." } ]
Creating an Excel-like data grid in React JS
In this article, we will see how to create an Excel-like data grid in React JS frontend. We will use a third-party package for this, which is called react-data-grid. This is a useful package if you are working with data and want to make a dashboard application. First create a react project − npx create-react-app tutorialpurpose Go to the project directory − cd tutorialpurpose Download and install the react-data-grid package − npm i --save react-data-grid We can use this package to add default styled grid tables or you can say data grids which are premade. Add the following lines of code in App.js − import DataGrid from "react-data-grid"; const columns = [ { key: "id", name: "ID" }, { key: "title", name: "Title" }, ]; const rows = [ { id: 0, title: "Example" }, { id: 1, title: "Demo" }, { id: 2, title: "React JS" }, { id: 3, title: "Tutorialspoint" }, { id: 4, title: "Ath Tripathi" }, { id: 5, title: "Kiran Kumar Panigrahi" }, ]; export default function App() { return <DataGrid columns={columns} rows={rows} />; } The concept is simple. We first make a column variable to indicate how the columns should be arranged. It will be a list of JSON objects and one column should have two keys: “key” which will be used for reference when creating a row and “name” which will be used for showing the column name. The row variable will be same as the column variable. Keys of row’s JSON will be the “key” of column variable, and the value will be the data to show under that column. On execution, it will produce the following output −
[ { "code": null, "e": 1324, "s": 1062, "text": "In this article, we will see how to create an Excel-like data grid in React JS frontend. We will use a third-party package for this, which is called react-data-grid. This is a useful package if you are working with data and want to make a dashboard application." }, { "code": null, "e": 1355, "s": 1324, "text": "First create a react project −" }, { "code": null, "e": 1392, "s": 1355, "text": "npx create-react-app tutorialpurpose" }, { "code": null, "e": 1422, "s": 1392, "text": "Go to the project directory −" }, { "code": null, "e": 1441, "s": 1422, "text": "cd tutorialpurpose" }, { "code": null, "e": 1492, "s": 1441, "text": "Download and install the react-data-grid package −" }, { "code": null, "e": 1521, "s": 1492, "text": "npm i --save react-data-grid" }, { "code": null, "e": 1624, "s": 1521, "text": "We can use this package to add default styled grid tables or you can\nsay data grids which are premade." }, { "code": null, "e": 1668, "s": 1624, "text": "Add the following lines of code in App.js −" }, { "code": null, "e": 2120, "s": 1668, "text": "import DataGrid from \"react-data-grid\";\n\nconst columns = [\n { key: \"id\", name: \"ID\" },\n { key: \"title\", name: \"Title\" },\n];\n\nconst rows = [\n { id: 0, title: \"Example\" },\n { id: 1, title: \"Demo\" },\n { id: 2, title: \"React JS\" },\n { id: 3, title: \"Tutorialspoint\" },\n { id: 4, title: \"Ath Tripathi\" },\n { id: 5, title: \"Kiran Kumar Panigrahi\" },\n];\n\nexport default function App() {\n return <DataGrid columns={columns} rows={rows} />;\n}" }, { "code": null, "e": 2412, "s": 2120, "text": "The concept is simple. We first make a column variable to indicate how the columns should be arranged. It will be a list of JSON objects and one column should have two keys: “key” which will be used for reference when creating a row and “name” which will be used for showing the column name." }, { "code": null, "e": 2581, "s": 2412, "text": "The row variable will be same as the column variable. Keys of row’s JSON will be the “key” of column variable, and the value will be the data to show under that column." }, { "code": null, "e": 2634, "s": 2581, "text": "On execution, it will produce the following output −" } ]
JSON Introduction - GeeksforGeeks
06 Dec, 2021 JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. JSON is the replacement of the XML data exchange format in JSON. It is easy to struct the data compare to XML. It supports data structures like arrays and objects and the JSON documents that are rapidly executed on the server. It is also a Language-Independent format that is derived from JavaScript. The official media type for the JSON is application/json and to save those file .json extension. Features of JSON: Easy to understand: JSON is easy to read and write. Format: It is a text-based interchange format. It can store any kind of data in an array of video, audio, and image anything that you required. Support: It is light-weighted and supported by almost every language and OS. It has a wide range of support for the browsers approx each browser supported by JSON. Dependency: It is an Independent language that is text-based. It is much faster compared to other text-based structured data. JSON Syntax Rules: Data is in name/value pairs and they are separated by commas. It uses curly brackets to hold the objects and square brackets to hold the arrays. Example: Javascript { "Courses": [ { "Name" : "Java Foundation", "Created by" : "Geeksforgeeks", "Content" : [ "Java Core", "JSP", "Servlets", "Collections" ] }, { "Name" : "Data Structures", "also known as" : "Interview Preparation Course", "Topics" : [ "Trees", "Graphs", "Maps" ] } ]} Advantages of JSON: JSON stores all the data in an array so data transfer makes easier. That’s why JSON is the best for sharing data of any size even audio, video, etc. Its syntax is very easy to use. Its syntax is very small and light-weighted that’s the reason that it executes and response in a faster way. JSON has a wide range for the browser support compatibility with the operating systems, it doesn’t require much effort to make it all browser compatible. On the server-side parsing the most important part that developers want, if the parsing will be fast on the server side then the user can get the fast response, so in this case JSON server-side parsing is the strong point compare tot others. Disadvantages of JSON: The main disadvantage for JSON is that there is no error handling in JSON, if there was a slight mistake in the JSON script then you will not get the structured data. JSON becomes quite dangerous when you used it with some unauthorized browsers. Like JSON service return a JSON file wrapped in a function call that has to be executed by the browsers if the browsers are unauthorized then your data can be hacked. JSON has limited supported tools that we can use during JSON development. JavaScript-Questions JSON JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to get selected value in dropdown list using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24933, "s": 24905, "text": "\n06 Dec, 2021" }, { "code": null, "e": 25494, "s": 24933, "text": "JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. JSON is the replacement of the XML data exchange format in JSON. It is easy to struct the data compare to XML. It supports data structures like arrays and objects and the JSON documents that are rapidly executed on the server. It is also a Language-Independent format that is derived from JavaScript. The official media type for the JSON is application/json and to save those file .json extension." }, { "code": null, "e": 25512, "s": 25494, "text": "Features of JSON:" }, { "code": null, "e": 25564, "s": 25512, "text": "Easy to understand: JSON is easy to read and write." }, { "code": null, "e": 25708, "s": 25564, "text": "Format: It is a text-based interchange format. It can store any kind of data in an array of video, audio, and image anything that you required." }, { "code": null, "e": 25872, "s": 25708, "text": "Support: It is light-weighted and supported by almost every language and OS. It has a wide range of support for the browsers approx each browser supported by JSON." }, { "code": null, "e": 25998, "s": 25872, "text": "Dependency: It is an Independent language that is text-based. It is much faster compared to other text-based structured data." }, { "code": null, "e": 26162, "s": 25998, "text": "JSON Syntax Rules: Data is in name/value pairs and they are separated by commas. It uses curly brackets to hold the objects and square brackets to hold the arrays." }, { "code": null, "e": 26173, "s": 26164, "text": "Example:" }, { "code": null, "e": 26184, "s": 26173, "text": "Javascript" }, { "code": "{ \"Courses\": [ { \"Name\" : \"Java Foundation\", \"Created by\" : \"Geeksforgeeks\", \"Content\" : [ \"Java Core\", \"JSP\", \"Servlets\", \"Collections\" ] }, { \"Name\" : \"Data Structures\", \"also known as\" : \"Interview Preparation Course\", \"Topics\" : [ \"Trees\", \"Graphs\", \"Maps\" ] } ]}", "e": 26577, "s": 26184, "text": null }, { "code": null, "e": 26597, "s": 26577, "text": "Advantages of JSON:" }, { "code": null, "e": 26746, "s": 26597, "text": "JSON stores all the data in an array so data transfer makes easier. That’s why JSON is the best for sharing data of any size even audio, video, etc." }, { "code": null, "e": 26887, "s": 26746, "text": "Its syntax is very easy to use. Its syntax is very small and light-weighted that’s the reason that it executes and response in a faster way." }, { "code": null, "e": 27041, "s": 26887, "text": "JSON has a wide range for the browser support compatibility with the operating systems, it doesn’t require much effort to make it all browser compatible." }, { "code": null, "e": 27283, "s": 27041, "text": "On the server-side parsing the most important part that developers want, if the parsing will be fast on the server side then the user can get the fast response, so in this case JSON server-side parsing is the strong point compare tot others." }, { "code": null, "e": 27306, "s": 27283, "text": "Disadvantages of JSON:" }, { "code": null, "e": 27473, "s": 27306, "text": "The main disadvantage for JSON is that there is no error handling in JSON, if there was a slight mistake in the JSON script then you will not get the structured data." }, { "code": null, "e": 27719, "s": 27473, "text": "JSON becomes quite dangerous when you used it with some unauthorized browsers. Like JSON service return a JSON file wrapped in a function call that has to be executed by the browsers if the browsers are unauthorized then your data can be hacked." }, { "code": null, "e": 27793, "s": 27719, "text": "JSON has limited supported tools that we can use during JSON development." }, { "code": null, "e": 27814, "s": 27793, "text": "JavaScript-Questions" }, { "code": null, "e": 27819, "s": 27814, "text": "JSON" }, { "code": null, "e": 27830, "s": 27819, "text": "JavaScript" }, { "code": null, "e": 27847, "s": 27830, "text": "Web Technologies" }, { "code": null, "e": 27945, "s": 27847, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27954, "s": 27945, "text": "Comments" }, { "code": null, "e": 27967, "s": 27954, "text": "Old Comments" }, { "code": null, "e": 28028, "s": 27967, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28069, "s": 28028, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28123, "s": 28069, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28163, "s": 28123, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28225, "s": 28163, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 28281, "s": 28225, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28314, "s": 28281, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28376, "s": 28314, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28419, "s": 28376, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Collect Data from TikTok (Tutorial) | by Jack Bandy | Towards Data Science
As The Information put it, TikTok has “taken off like a rocket ship in the U.S. and around the world, creating a new mobile video experience that has left YouTube and Facebook scrambling to keep up.” Just looking at U.S. users over the age of 18, TikTok went from 22.2 million unique visitors in January, to 39.2 million in April, according to Comscore data provided to Adweek. The platform is more than just a cool new app: as recent events have shown, its algorithms spread videos that can have real-world consequences. To name a few prominent examples, K-pop fans used TikTok to prank Trump’s rally in Tulsa, purchasing tickets and then not showing up Teens on TikTok organized “shopping cart abandonment” on Trump’s merchandise website in attempt to hide inventory from others Some users are encouraging Trump’s opposition to click on ads for Trump in order to drive up the campaign’s advertising costs The app has spread manipulated videos of Joe Biden In short, TikTok and its driving algorithms now have a sizeable real-world influence, especially considering that a typical user spends almost an hour per day watching videos on the platform. With this in mind, it is important to understand what TikTok shows to millions of eyeballs every day, and to do that, we will need some data. Below, I have included code for how to collect TikTok data in a variety of ways. I tried to keep it general and helpful for most use cases, but you will probably need to tweak it depending on what you are doing. The remainder of this post covers how to do the following: 👤 Collect videos posted by a user❤️ Collect videos liked by a user⛄️ Snowball a list of users📈 Collect trending videos 👤 Collect videos posted by a user ❤️ Collect videos liked by a user ⛄️ Snowball a list of users 📈 Collect trending videos (A couple notes for the nerds: if you plan to make more than a few dozen requests, I suggest setting up a proxy. I have not yet tested it, but the API I demo here should integrate with your proxy quite easily. Second, if you want to track popularity over time, you will want to add timestamps to the statistics.) A good place to start is collecting videos from a given user. I will be using TikTok-Api by David Teather (run pip3 install TikTokApi to get the package). To collect videos from the Washington Post TikTok account (one of my favorites), here is all you need to do in Python: from TikTokApi import TikTokApiapi = TikTokApi()n_videos = 100username = 'washingtonpost'user_videos = api.byUsername(username, count=n_videos) The user_videos object is now a list of 100 video dictionaries (an example dictionary is here). You will probably be mostly interested in just a few stats, which you can extract from the full dictionary with the following function: def simple_dict(tiktok_dict): to_return = {} to_return['user_name'] = tiktok_dict['author']['uniqueId'] to_return['user_id'] = tiktok_dict['author']['id'] to_return['video_id'] = tiktok_dict['id'] to_return['video_desc'] = tiktok_dict['desc'] to_return['video_time'] = tiktok_dict['createTime'] to_return['video_length'] = tiktok_dict['video']['duration'] to_return['video_link'] = 'https://www.tiktok.com/@{}/video/{}?lang=en'.format(to_return['user_name'], to_return['video_id']) to_return['n_likes'] = tiktok_dict['stats']['diggCount'] to_return['n_shares'] = tiktok_dict['stats']['shareCount'] to_return['n_comments'] = tiktok_dict['stats']['commentCount'] to_return['n_plays'] = tiktok_dict['stats']['playCount'] return to_return Then, we can go from the API-outputteduser_videos list to a nice, clean table (i.e. Pandas data frame) with just three lines: user_videos = [simple_dict(v) for v in user_videos]user_videos_df = pd.DataFrame(user_videos)user_videos_df.to_csv('{}_videos.csv'.format(username),index=False) Here is what the output file looks like (I removed some rows and columns to make it readable on here): In this case, you may be interested in the videos “liked” by a given user. This is pretty straightforward to collect. Let’s see what videos the official TikTok account has liked recently: username = 'tiktok'n_videos = 10liked_videos = api.userLikedbyUsername(username, count=n_videos)liked_videos = [simple_dict(v) for v in liked_videos]liked_videos_df = pd.DataFrame(liked_videos)liked_videos_df.to_csv('{}_liked_videos.csv'.format(username), index=False) And the output file looks similar to the one from last time, since it also saves a list of videos: Say you wanted to create a large list of users from which you could collect videos they post and videos they like. You could use the 50 most-followed TikTok accounts, but 50 may not generate a wide enough sample. An alternative approach is to use the suggested users to snowball a list of users from just one user. First, we will do this for four different accounts: tiktok is the app’s official account washingtonpost is one of my favorite accounts charlidamelio is the most-followed account on TikTok chunkysdead leads a self-proclaimed “cult” on the app Here is the code I used: seed_users = ['tiktok', 'washingtonpost', 'charlidamelio', 'chunkysdead']seed_ids = [api.getUser(user_name)['userInfo']['user']['id'] for user_name in seed_users]suggested = [api.getSuggestedUsersbyID(count=20, startingId=s_id) for s_id in seed_ids] And here are the suggested users: Notably, the list of recommendations for washingtonpost and chunkysdead were identical, and there is a lot of overlap between the other recommendations, so this approach may not give you what you need. Another method to create a large list of users it to use the getSuggestedUsersbyIDCrawler to keep the snowball rolling, so to speak. To create a list of 100 suggested accounts using tiktok as the seed account, you just need the following code: tiktok_id = api.getUser('tiktok')['userInfo']['user']['id']suggested_100 = api.getSuggestedUsersbyIDCrawler(count=100, startingId=tiktok_id) This creates a list which contains a variety of different celebrity accounts, here are a few: @lizzo (lizzo, 8900000 fans)@wizkhalifa (Wiz Khalifa, 1800000 fans)@capuchina114 (Capuchina❗️👸🏼, 32600 fans)@silviastephaniev (Silvia Stephanie💓, 27600 fans)@theweeknd (The Weeknd, 1400000 fans)@theawesometalents (Music videos, 33400 fans)... From what I observed, the getSuggestedUsersbyIDCrawler method starts to branch out and find smaller, more niche accounts, which have tens of thousands of followers rather than hundreds of thousands or millions. This is good news if you want a representative dataset. If you want to collect a wide sample of data from TikTok, I advise starting with the suggested users crawler. Finally, maybe you simply want to collect trending videos for a simple content analysis, or just to keep up 🙂. The API makes that pretty simple, as follows: n_trending = 20trending_videos = api.trending(count=n_trending)trending_videos = [simple_dict(v) for v in trending_videos]trending_videos_df = pd.DataFrame(trending_videos)trending_videos_df.to_csv('trending.csv',index=False) And here is the output file for trending videos on Thursday afternoon (July 2nd, 2020): That will be all for this tutorial, thank you for reading! Here is a file with all the code I used.
[ { "code": null, "e": 371, "s": 171, "text": "As The Information put it, TikTok has “taken off like a rocket ship in the U.S. and around the world, creating a new mobile video experience that has left YouTube and Facebook scrambling to keep up.”" }, { "code": null, "e": 549, "s": 371, "text": "Just looking at U.S. users over the age of 18, TikTok went from 22.2 million unique visitors in January, to 39.2 million in April, according to Comscore data provided to Adweek." }, { "code": null, "e": 727, "s": 549, "text": "The platform is more than just a cool new app: as recent events have shown, its algorithms spread videos that can have real-world consequences. To name a few prominent examples," }, { "code": null, "e": 826, "s": 727, "text": "K-pop fans used TikTok to prank Trump’s rally in Tulsa, purchasing tickets and then not showing up" }, { "code": null, "e": 952, "s": 826, "text": "Teens on TikTok organized “shopping cart abandonment” on Trump’s merchandise website in attempt to hide inventory from others" }, { "code": null, "e": 1078, "s": 952, "text": "Some users are encouraging Trump’s opposition to click on ads for Trump in order to drive up the campaign’s advertising costs" }, { "code": null, "e": 1129, "s": 1078, "text": "The app has spread manipulated videos of Joe Biden" }, { "code": null, "e": 1463, "s": 1129, "text": "In short, TikTok and its driving algorithms now have a sizeable real-world influence, especially considering that a typical user spends almost an hour per day watching videos on the platform. With this in mind, it is important to understand what TikTok shows to millions of eyeballs every day, and to do that, we will need some data." }, { "code": null, "e": 1734, "s": 1463, "text": "Below, I have included code for how to collect TikTok data in a variety of ways. I tried to keep it general and helpful for most use cases, but you will probably need to tweak it depending on what you are doing. The remainder of this post covers how to do the following:" }, { "code": null, "e": 1853, "s": 1734, "text": "👤 Collect videos posted by a user❤️ Collect videos liked by a user⛄️ Snowball a list of users📈 Collect trending videos" }, { "code": null, "e": 1887, "s": 1853, "text": "👤 Collect videos posted by a user" }, { "code": null, "e": 1921, "s": 1887, "text": "❤️ Collect videos liked by a user" }, { "code": null, "e": 1949, "s": 1921, "text": "⛄️ Snowball a list of users" }, { "code": null, "e": 1975, "s": 1949, "text": "📈 Collect trending videos" }, { "code": null, "e": 2288, "s": 1975, "text": "(A couple notes for the nerds: if you plan to make more than a few dozen requests, I suggest setting up a proxy. I have not yet tested it, but the API I demo here should integrate with your proxy quite easily. Second, if you want to track popularity over time, you will want to add timestamps to the statistics.)" }, { "code": null, "e": 2443, "s": 2288, "text": "A good place to start is collecting videos from a given user. I will be using TikTok-Api by David Teather (run pip3 install TikTokApi to get the package)." }, { "code": null, "e": 2562, "s": 2443, "text": "To collect videos from the Washington Post TikTok account (one of my favorites), here is all you need to do in Python:" }, { "code": null, "e": 2706, "s": 2562, "text": "from TikTokApi import TikTokApiapi = TikTokApi()n_videos = 100username = 'washingtonpost'user_videos = api.byUsername(username, count=n_videos)" }, { "code": null, "e": 2938, "s": 2706, "text": "The user_videos object is now a list of 100 video dictionaries (an example dictionary is here). You will probably be mostly interested in just a few stats, which you can extract from the full dictionary with the following function:" }, { "code": null, "e": 3686, "s": 2938, "text": "def simple_dict(tiktok_dict): to_return = {} to_return['user_name'] = tiktok_dict['author']['uniqueId'] to_return['user_id'] = tiktok_dict['author']['id'] to_return['video_id'] = tiktok_dict['id'] to_return['video_desc'] = tiktok_dict['desc'] to_return['video_time'] = tiktok_dict['createTime'] to_return['video_length'] = tiktok_dict['video']['duration'] to_return['video_link'] = 'https://www.tiktok.com/@{}/video/{}?lang=en'.format(to_return['user_name'], to_return['video_id']) to_return['n_likes'] = tiktok_dict['stats']['diggCount'] to_return['n_shares'] = tiktok_dict['stats']['shareCount'] to_return['n_comments'] = tiktok_dict['stats']['commentCount'] to_return['n_plays'] = tiktok_dict['stats']['playCount'] return to_return" }, { "code": null, "e": 3812, "s": 3686, "text": "Then, we can go from the API-outputteduser_videos list to a nice, clean table (i.e. Pandas data frame) with just three lines:" }, { "code": null, "e": 3973, "s": 3812, "text": "user_videos = [simple_dict(v) for v in user_videos]user_videos_df = pd.DataFrame(user_videos)user_videos_df.to_csv('{}_videos.csv'.format(username),index=False)" }, { "code": null, "e": 4076, "s": 3973, "text": "Here is what the output file looks like (I removed some rows and columns to make it readable on here):" }, { "code": null, "e": 4264, "s": 4076, "text": "In this case, you may be interested in the videos “liked” by a given user. This is pretty straightforward to collect. Let’s see what videos the official TikTok account has liked recently:" }, { "code": null, "e": 4533, "s": 4264, "text": "username = 'tiktok'n_videos = 10liked_videos = api.userLikedbyUsername(username, count=n_videos)liked_videos = [simple_dict(v) for v in liked_videos]liked_videos_df = pd.DataFrame(liked_videos)liked_videos_df.to_csv('{}_liked_videos.csv'.format(username), index=False)" }, { "code": null, "e": 4632, "s": 4533, "text": "And the output file looks similar to the one from last time, since it also saves a list of videos:" }, { "code": null, "e": 4845, "s": 4632, "text": "Say you wanted to create a large list of users from which you could collect videos they post and videos they like. You could use the 50 most-followed TikTok accounts, but 50 may not generate a wide enough sample." }, { "code": null, "e": 4999, "s": 4845, "text": "An alternative approach is to use the suggested users to snowball a list of users from just one user. First, we will do this for four different accounts:" }, { "code": null, "e": 5036, "s": 4999, "text": "tiktok is the app’s official account" }, { "code": null, "e": 5082, "s": 5036, "text": "washingtonpost is one of my favorite accounts" }, { "code": null, "e": 5135, "s": 5082, "text": "charlidamelio is the most-followed account on TikTok" }, { "code": null, "e": 5189, "s": 5135, "text": "chunkysdead leads a self-proclaimed “cult” on the app" }, { "code": null, "e": 5214, "s": 5189, "text": "Here is the code I used:" }, { "code": null, "e": 5464, "s": 5214, "text": "seed_users = ['tiktok', 'washingtonpost', 'charlidamelio', 'chunkysdead']seed_ids = [api.getUser(user_name)['userInfo']['user']['id'] for user_name in seed_users]suggested = [api.getSuggestedUsersbyID(count=20, startingId=s_id) for s_id in seed_ids]" }, { "code": null, "e": 5498, "s": 5464, "text": "And here are the suggested users:" }, { "code": null, "e": 5700, "s": 5498, "text": "Notably, the list of recommendations for washingtonpost and chunkysdead were identical, and there is a lot of overlap between the other recommendations, so this approach may not give you what you need." }, { "code": null, "e": 5944, "s": 5700, "text": "Another method to create a large list of users it to use the getSuggestedUsersbyIDCrawler to keep the snowball rolling, so to speak. To create a list of 100 suggested accounts using tiktok as the seed account, you just need the following code:" }, { "code": null, "e": 6085, "s": 5944, "text": "tiktok_id = api.getUser('tiktok')['userInfo']['user']['id']suggested_100 = api.getSuggestedUsersbyIDCrawler(count=100, startingId=tiktok_id)" }, { "code": null, "e": 6179, "s": 6085, "text": "This creates a list which contains a variety of different celebrity accounts, here are a few:" }, { "code": null, "e": 6422, "s": 6179, "text": "@lizzo (lizzo, 8900000 fans)@wizkhalifa (Wiz Khalifa, 1800000 fans)@capuchina114 (Capuchina❗️👸🏼, 32600 fans)@silviastephaniev (Silvia Stephanie💓, 27600 fans)@theweeknd (The Weeknd, 1400000 fans)@theawesometalents (Music videos, 33400 fans)..." }, { "code": null, "e": 6689, "s": 6422, "text": "From what I observed, the getSuggestedUsersbyIDCrawler method starts to branch out and find smaller, more niche accounts, which have tens of thousands of followers rather than hundreds of thousands or millions. This is good news if you want a representative dataset." }, { "code": null, "e": 6799, "s": 6689, "text": "If you want to collect a wide sample of data from TikTok, I advise starting with the suggested users crawler." }, { "code": null, "e": 6956, "s": 6799, "text": "Finally, maybe you simply want to collect trending videos for a simple content analysis, or just to keep up 🙂. The API makes that pretty simple, as follows:" }, { "code": null, "e": 7182, "s": 6956, "text": "n_trending = 20trending_videos = api.trending(count=n_trending)trending_videos = [simple_dict(v) for v in trending_videos]trending_videos_df = pd.DataFrame(trending_videos)trending_videos_df.to_csv('trending.csv',index=False)" }, { "code": null, "e": 7270, "s": 7182, "text": "And here is the output file for trending videos on Thursday afternoon (July 2nd, 2020):" } ]
Checking SAP HANA Schema owner name
To check schema owner, you need access on “SYS” schema. Open SAP HANA SQL console and run the following SQL query − SELECT * FROM "SYS"."SCHEMAS";
[ { "code": null, "e": 1178, "s": 1062, "text": "To check schema owner, you need access on “SYS” schema. Open SAP HANA SQL console and run the following SQL query −" }, { "code": null, "e": 1209, "s": 1178, "text": "SELECT * FROM \"SYS\".\"SCHEMAS\";" } ]
fc-list command in Linux with examples - GeeksforGeeks
15 May, 2019 fc-list command is a part of the fontconfig system. It is used to list the available fonts and font styles. Using the format option, the list of all fonts can be filtered and sorted out. Moreover, multiple parameters can be passed to it after a colon symbol (:) to restrict the information that is being displayed on the screen. Syntax: fc-list [-vqVh] [-f FORMAT] [–verbose] [–format=FORMAT] [–quiet] [–version] [–help] [pattern] {element ...} List fonts matching [pattern] Example: It will print all the file locations of the font files present in the system, with their font name, spacing and style type. fc-list Options: -v, –verbose: It is used to show the entire font pattern verbosely. -f, –format=FORMAT: To use the given output format. -q, –quiet: It will suppress all normal output, exit 1 if no fonts matched. -V, –version: It will show font config version and exit. -h, –help: Used to show the help message and exit. Some More Examples: fc-list with font-family: It will print only the names of the font families, without displaying the other aforementioned details.fc-list : family fc-list : family fc-list with font family + Language selector: It will print only the names of the font families which support the selected language code, without displaying the other aforementioned details.Note: The language code used here is “ta”, which stands for the language Tamil.fc-list : family lang=ta Note: The language code used here is “hi”, which stands for the language Hindi.fc-list : family lang=hi Note: The language code used here is “ta”, which stands for the language Tamil. fc-list : family lang=ta Note: The language code used here is “hi”, which stands for the language Hindi. fc-list : family lang=hi fc-list with other selectors: Similar to the family selector, we can also select the file location, spacing or/and style of the required fonts to be displayed onscreen.fc-list : family style Note: Sorting and unique can also be incorporated along with this commandfc-list : family spacing | sort | uniq fc-list : family style Note: Sorting and unique can also be incorporated along with this command fc-list : family spacing | sort | uniq fc-list with format option: This option is used to format the output text to the required pattern given by the user. In this example, the format option is used to get the family names of all the fonts, sorted and unique.fc-list --format="%{family[0]}\n" | sort | uniq fc-list --format="%{family[0]}\n" | sort | uniq linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Named Pipe or FIFO with example C program Thread functions in C/C++ SED command in Linux | Set 2 Array Basics in Shell Scripting | Set 1 Introduction to Linux Shell and Shell Scripting Linux system call in Detail chown command in Linux with Examples Looping Statements | Shell Script mv command in Linux with examples PING Command in Linux with examples
[ { "code": null, "e": 24326, "s": 24298, "text": "\n15 May, 2019" }, { "code": null, "e": 24655, "s": 24326, "text": "fc-list command is a part of the fontconfig system. It is used to list the available fonts and font styles. Using the format option, the list of all fonts can be filtered and sorted out. Moreover, multiple parameters can be passed to it after a colon symbol (:) to restrict the information that is being displayed on the screen." }, { "code": null, "e": 24663, "s": 24655, "text": "Syntax:" }, { "code": null, "e": 24801, "s": 24663, "text": "fc-list [-vqVh] [-f FORMAT] [–verbose] [–format=FORMAT] [–quiet] [–version] [–help] [pattern] {element ...} List fonts matching [pattern]" }, { "code": null, "e": 24934, "s": 24801, "text": "Example: It will print all the file locations of the font files present in the system, with their font name, spacing and style type." }, { "code": null, "e": 24942, "s": 24934, "text": "fc-list" }, { "code": null, "e": 24951, "s": 24942, "text": "Options:" }, { "code": null, "e": 25019, "s": 24951, "text": "-v, –verbose: It is used to show the entire font pattern verbosely." }, { "code": null, "e": 25071, "s": 25019, "text": "-f, –format=FORMAT: To use the given output format." }, { "code": null, "e": 25147, "s": 25071, "text": "-q, –quiet: It will suppress all normal output, exit 1 if no fonts matched." }, { "code": null, "e": 25204, "s": 25147, "text": "-V, –version: It will show font config version and exit." }, { "code": null, "e": 25255, "s": 25204, "text": "-h, –help: Used to show the help message and exit." }, { "code": null, "e": 25275, "s": 25255, "text": "Some More Examples:" }, { "code": null, "e": 25422, "s": 25275, "text": "fc-list with font-family: It will print only the names of the font families, without displaying the other aforementioned details.fc-list : family " }, { "code": null, "e": 25440, "s": 25422, "text": "fc-list : family " }, { "code": null, "e": 25838, "s": 25440, "text": "fc-list with font family + Language selector: It will print only the names of the font families which support the selected language code, without displaying the other aforementioned details.Note: The language code used here is “ta”, which stands for the language Tamil.fc-list : family lang=ta Note: The language code used here is “hi”, which stands for the language Hindi.fc-list : family lang=hi" }, { "code": null, "e": 25918, "s": 25838, "text": "Note: The language code used here is “ta”, which stands for the language Tamil." }, { "code": null, "e": 25944, "s": 25918, "text": "fc-list : family lang=ta " }, { "code": null, "e": 26024, "s": 25944, "text": "Note: The language code used here is “hi”, which stands for the language Hindi." }, { "code": null, "e": 26049, "s": 26024, "text": "fc-list : family lang=hi" }, { "code": null, "e": 26352, "s": 26049, "text": "fc-list with other selectors: Similar to the family selector, we can also select the file location, spacing or/and style of the required fonts to be displayed onscreen.fc-list : family style Note: Sorting and unique can also be incorporated along with this commandfc-list : family spacing | sort | uniq" }, { "code": null, "e": 26376, "s": 26352, "text": "fc-list : family style " }, { "code": null, "e": 26450, "s": 26376, "text": "Note: Sorting and unique can also be incorporated along with this command" }, { "code": null, "e": 26489, "s": 26450, "text": "fc-list : family spacing | sort | uniq" }, { "code": null, "e": 26757, "s": 26489, "text": "fc-list with format option: This option is used to format the output text to the required pattern given by the user. In this example, the format option is used to get the family names of all the fonts, sorted and unique.fc-list --format=\"%{family[0]}\\n\" | sort | uniq" }, { "code": null, "e": 26805, "s": 26757, "text": "fc-list --format=\"%{family[0]}\\n\" | sort | uniq" }, { "code": null, "e": 26819, "s": 26805, "text": "linux-command" }, { "code": null, "e": 26839, "s": 26819, "text": "Linux-misc-commands" }, { "code": null, "e": 26846, "s": 26839, "text": "Picked" }, { "code": null, "e": 26857, "s": 26846, "text": "Linux-Unix" }, { "code": null, "e": 26955, "s": 26857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26964, "s": 26955, "text": "Comments" }, { "code": null, "e": 26977, "s": 26964, "text": "Old Comments" }, { "code": null, "e": 27019, "s": 26977, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 27045, "s": 27019, "text": "Thread functions in C/C++" }, { "code": null, "e": 27074, "s": 27045, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27114, "s": 27074, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 27162, "s": 27114, "text": "Introduction to Linux Shell and Shell Scripting" }, { "code": null, "e": 27190, "s": 27162, "text": "Linux system call in Detail" }, { "code": null, "e": 27227, "s": 27190, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27261, "s": 27227, "text": "Looping Statements | Shell Script" }, { "code": null, "e": 27295, "s": 27261, "text": "mv command in Linux with examples" } ]
filter() in python - GeeksforGeeks
22 Apr, 2020 The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. syntax: filter(function, sequence) Parameters: function: function that tests if each element of a sequence true or not. sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators. Returns: returns an iterator that is already filtered. # function that filters vowelsdef fun(variable): letters = ['a', 'e', 'i', 'o', 'u'] if (variable in letters): return True else: return False # sequencesequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r'] # using filter functionfiltered = filter(fun, sequence) print('The filtered letters are:')for s in filtered: print(s) Output: The filtered letters are: e e Application:It is normally used with Lambda functions to separate list, tuple, or sets. # a list contains both even and odd numbers. seq = [0, 1, 2, 3, 5, 8, 13] # result contains odd numbers of the listresult = filter(lambda x: x % 2 != 0, seq)print(list(result)) # result contains even numbers of the listresult = filter(lambda x: x % 2 == 0, seq)print(list(result)) Output: [1, 3, 5, 13] [0, 2, 8] Please refer Python Lambda functions for more details. kailashc_j nidhi_biet erpriyarana Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python Graph Plotting in Python | Set 1 Print lists in Python (4 Different Ways) How To Convert Python Dictionary To JSON? Check if element exists in list in Python Convert integer to string in Python
[ { "code": null, "e": 23679, "s": 23651, "text": "\n22 Apr, 2020" }, { "code": null, "e": 23813, "s": 23679, "text": "The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not." }, { "code": null, "e": 23821, "s": 23813, "text": "syntax:" }, { "code": null, "e": 24101, "s": 23821, "text": "filter(function, sequence)\nParameters:\nfunction: function that tests if each element of a \nsequence true or not.\nsequence: sequence which needs to be filtered, it can \nbe sets, lists, tuples, or containers of any iterators.\nReturns:\nreturns an iterator that is already filtered.\n" }, { "code": "# function that filters vowelsdef fun(variable): letters = ['a', 'e', 'i', 'o', 'u'] if (variable in letters): return True else: return False # sequencesequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r'] # using filter functionfiltered = filter(fun, sequence) print('The filtered letters are:')for s in filtered: print(s)", "e": 24454, "s": 24101, "text": null }, { "code": null, "e": 24462, "s": 24454, "text": "Output:" }, { "code": null, "e": 24493, "s": 24462, "text": "The filtered letters are:\ne\ne\n" }, { "code": null, "e": 24581, "s": 24493, "text": "Application:It is normally used with Lambda functions to separate list, tuple, or sets." }, { "code": "# a list contains both even and odd numbers. seq = [0, 1, 2, 3, 5, 8, 13] # result contains odd numbers of the listresult = filter(lambda x: x % 2 != 0, seq)print(list(result)) # result contains even numbers of the listresult = filter(lambda x: x % 2 == 0, seq)print(list(result))", "e": 24864, "s": 24581, "text": null }, { "code": null, "e": 24872, "s": 24864, "text": "Output:" }, { "code": null, "e": 24897, "s": 24872, "text": "[1, 3, 5, 13]\n[0, 2, 8]\n" }, { "code": null, "e": 24952, "s": 24897, "text": "Please refer Python Lambda functions for more details." }, { "code": null, "e": 24963, "s": 24952, "text": "kailashc_j" }, { "code": null, "e": 24974, "s": 24963, "text": "nidhi_biet" }, { "code": null, "e": 24986, "s": 24974, "text": "erpriyarana" }, { "code": null, "e": 25012, "s": 24986, "text": "Python-Built-in-functions" }, { "code": null, "e": 25019, "s": 25012, "text": "Python" }, { "code": null, "e": 25117, "s": 25019, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25126, "s": 25117, "text": "Comments" }, { "code": null, "e": 25139, "s": 25126, "text": "Old Comments" }, { "code": null, "e": 25171, "s": 25139, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25213, "s": 25171, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25250, "s": 25213, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 25306, "s": 25250, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25335, "s": 25306, "text": "*args and **kwargs in Python" }, { "code": null, "e": 25368, "s": 25335, "text": "Graph Plotting in Python | Set 1" }, { "code": null, "e": 25409, "s": 25368, "text": "Print lists in Python (4 Different Ways)" }, { "code": null, "e": 25451, "s": 25409, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25493, "s": 25451, "text": "Check if element exists in list in Python" } ]
How to implement an endless list with RecyclerView in Android using Kotlin?
This example demonstrates how to implement an endless list with RecyclerView in Android using Kotlin. 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"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" app:cardElevation="2dp" app:cardUseCompatPadding="true"> <TextView android:id="@+id/textViewItem" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" android:textColor="@android:color/holo_blue_bright" android:textStyle="bold" /> </androidx.cardview.widget.CardView> Step 3 − Add the following code to src/MainActivity.kt import android.os.Bundle import android.os.Handler import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { lateinit var recyclerView: RecyclerView lateinit var recyclerViewAdapter: RecyclerViewAdapter var rowsArrayList: ArrayList<String> = ArrayList() var isLoading = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" recyclerView = findViewById(R.id.recyclerView) populateData() initAdapter() initScrollListener() } private fun initScrollListener() { recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val linearLayoutManager = recyclerView.layoutManager as LinearLayoutManager? if (!isLoading) { if (linearLayoutManager != null && linearLayoutManager.findLastCompletelyVisibleItemPosition() == rowsArrayList.size − 1) { //bottom of list! loadMore() isLoading = true } } } }) } private fun initAdapter() { recyclerViewAdapter = RecyclerViewAdapter(rowsArrayList) recyclerView.layoutManager = LinearLayoutManager(applicationContext) recyclerView.adapter = recyclerViewAdapter } private fun populateData() { for (i in 0..9) { rowsArrayList.add("Number $i") } } private fun loadMore() { rowsArrayList.add(null.toString()) recyclerViewAdapter.notifyItemInserted(rowsArrayList.size − 1) val handler = Handler() handler.postDelayed(Runnable { rowsArrayList.removeAt(rowsArrayList.size − 1) val scrollPosition = rowsArrayList.size recyclerViewAdapter.notifyItemRemoved(scrollPosition) var currentSize = scrollPosition val nextLimit = currentSize + 10 while (currentSize − 1 < nextLimit) { rowsArrayList.add("Number $currentSize") currentSize++ } recyclerViewAdapter.notifyDataSetChanged() isLoading = false }, 2000) } } Step 4 − Create a new class RecyclerViewAdapter.kt and add the following code − import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import android.widget.TextView import androidx.annotation.NonNull import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder class RecyclerViewAdapter internal constructor(private val itemList: List<String>) : RecyclerView.Adapter<ViewHolder>() { private val viewItemType = 0 @NonNull override fun onCreateViewHolder( @NonNull parent: ViewGroup, viewType: Int ): ViewHolder { return if (viewType == viewItemType) { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_row, parent, false) ItemViewHolder(view) } else { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_loading, parent, false) LoadingViewHolder(view) } } override fun onBindViewHolder(@NonNull viewHolder: ViewHolder, position: Int) { if (viewHolder is ItemViewHolder) { populateItemRows(viewHolder, position) } else if (viewHolder is LoadingViewHolder) { showLoadingView(viewHolder, position) } } override fun getItemViewType(position: Int): Int { return viewItemType } private inner class ItemViewHolder internal constructor(@NonNull itemView: View) : ViewHolder(itemView) { internal var tvItem: TextView = itemView.findViewById(R.id.textViewItem) } private class LoadingViewHolder internal constructor(itemView: View) : ViewHolder(itemView) { var progressBar: ProgressBar = itemView.findViewById(R.id.progressBar) } override fun getItemCount(): Int { return itemList.size } private fun showLoadingView(viewHolder: LoadingViewHolder, position: Int) {} private fun populateItemRows(viewHolder: ItemViewHolder, position: Int) { val item = itemList[position] viewHolder.tvItem.text = item } } Step 5 − Create a Layout resource file item_row.xml and add the following − <?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" app:cardElevation="2dp" app:cardUseCompatPadding="true"> <TextView android:id="@+id/textViewItem" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" android:textColor="@android:color/holo_blue_bright" android:textStyle="bold" /> </androidx.cardview.widget.CardView> Step 6 − Create a Layout resource file item_loading.xml and add the following − <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ProgressBar android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:indeterminate="true" android:paddingLeft="8dp" android:paddingRight="8dp" /> </LinearLayout> Step 7 − 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.q11"> <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 the 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": 1164, "s": 1062, "text": "This example demonstrates how to implement an endless list with RecyclerView in Android using Kotlin." }, { "code": null, "e": 1293, "s": 1164, "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": 1358, "s": 1293, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1981, "s": 1358, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n app:cardElevation=\"2dp\"\n app:cardUseCompatPadding=\"true\">\n <TextView\n android:id=\"@+id/textViewItem\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:padding=\"16dp\"\n android:textColor=\"@android:color/holo_blue_bright\"\n android:textStyle=\"bold\" />\n</androidx.cardview.widget.CardView>" }, { "code": null, "e": 2036, "s": 1981, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 4464, "s": 2036, "text": "import android.os.Bundle\nimport android.os.Handler\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.recyclerview.widget.LinearLayoutManager\nimport androidx.recyclerview.widget.RecyclerView\nclass MainActivity : AppCompatActivity() {\n lateinit var recyclerView: RecyclerView\n lateinit var recyclerViewAdapter: RecyclerViewAdapter\n var rowsArrayList: ArrayList<String> = ArrayList()\n var isLoading = false\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n recyclerView = findViewById(R.id.recyclerView)\n populateData()\n initAdapter()\n initScrollListener()\n }\n private fun initScrollListener() {\n recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {\n override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {\n super.onScrolled(recyclerView, dx, dy)\n val linearLayoutManager = recyclerView.layoutManager as LinearLayoutManager?\n if (!isLoading) {\n if (linearLayoutManager != null && linearLayoutManager.findLastCompletelyVisibleItemPosition() ==\n rowsArrayList.size − 1) {\n //bottom of list!\n loadMore()\n isLoading = true\n }\n }\n }\n })\n }\n private fun initAdapter() {\n recyclerViewAdapter = RecyclerViewAdapter(rowsArrayList)\n recyclerView.layoutManager = LinearLayoutManager(applicationContext)\n recyclerView.adapter = recyclerViewAdapter\n }\n private fun populateData() {\n for (i in 0..9) {\n rowsArrayList.add(\"Number $i\")\n }\n }\n private fun loadMore() {\n rowsArrayList.add(null.toString())\n recyclerViewAdapter.notifyItemInserted(rowsArrayList.size − 1)\n val handler = Handler()\n handler.postDelayed(Runnable {\n rowsArrayList.removeAt(rowsArrayList.size − 1)\n val scrollPosition = rowsArrayList.size\n recyclerViewAdapter.notifyItemRemoved(scrollPosition)\n var currentSize = scrollPosition\n val nextLimit = currentSize + 10\n while (currentSize − 1 < nextLimit) {\n rowsArrayList.add(\"Number $currentSize\")\n currentSize++\n }\n recyclerViewAdapter.notifyDataSetChanged()\n isLoading = false\n }, 2000)\n }\n}" }, { "code": null, "e": 4544, "s": 4464, "text": "Step 4 − Create a new class RecyclerViewAdapter.kt and add the following code −" }, { "code": null, "e": 6521, "s": 4544, "text": "import android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport android.widget.ProgressBar\nimport android.widget.TextView\nimport androidx.annotation.NonNull\nimport androidx.recyclerview.widget.RecyclerView\nimport androidx.recyclerview.widget.RecyclerView.ViewHolder\nclass RecyclerViewAdapter internal constructor(private val itemList: List<String>) :\nRecyclerView.Adapter<ViewHolder>() {\n private val viewItemType = 0\n @NonNull\n override fun onCreateViewHolder(\n @NonNull parent: ViewGroup,\n viewType: Int\n ): ViewHolder {\n return if (viewType == viewItemType) {\n val view =\n LayoutInflater.from(parent.context).inflate(R.layout.item_row, parent, false)\n ItemViewHolder(view)\n } else {\n val view = LayoutInflater.from(parent.context)\n .inflate(R.layout.item_loading, parent, false)\n LoadingViewHolder(view)\n }\n }\n override fun onBindViewHolder(@NonNull viewHolder: ViewHolder, position: Int) {\n if (viewHolder is ItemViewHolder) {\n populateItemRows(viewHolder, position)\n } else if (viewHolder is LoadingViewHolder) {\n showLoadingView(viewHolder, position)\n }\n }\n override fun getItemViewType(position: Int): Int {\n return viewItemType\n }\n private inner class ItemViewHolder internal constructor(@NonNull itemView: View) :\n ViewHolder(itemView) {\n internal var tvItem: TextView = itemView.findViewById(R.id.textViewItem)\n }\n private class LoadingViewHolder internal constructor(itemView: View) :\n ViewHolder(itemView) {\n var progressBar: ProgressBar = itemView.findViewById(R.id.progressBar)\n }\n override fun getItemCount(): Int {\n return itemList.size\n }\n private fun showLoadingView(viewHolder: LoadingViewHolder, position: Int) {}\n private fun populateItemRows(viewHolder: ItemViewHolder, position: Int) {\n val item = itemList[position]\n viewHolder.tvItem.text = item\n }\n}" }, { "code": null, "e": 6597, "s": 6521, "text": "Step 5 − Create a Layout resource file item_row.xml and add the following −" }, { "code": null, "e": 7220, "s": 6597, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n app:cardElevation=\"2dp\"\n app:cardUseCompatPadding=\"true\">\n <TextView\n android:id=\"@+id/textViewItem\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:padding=\"16dp\"\n android:textColor=\"@android:color/holo_blue_bright\"\n android:textStyle=\"bold\" />\n</androidx.cardview.widget.CardView>" }, { "code": null, "e": 7300, "s": 7220, "text": "Step 6 − Create a Layout resource file item_loading.xml and add the following −" }, { "code": null, "e": 7831, "s": 7300, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\">\n <ProgressBar\n android:id=\"@+id/progressBar\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"center_horizontal\"\n android:indeterminate=\"true\"\n android:paddingLeft=\"8dp\"\n android:paddingRight=\"8dp\" />\n</LinearLayout>" }, { "code": null, "e": 7886, "s": 7831, "text": "Step 7 − Add the following code to androidManifest.xml" }, { "code": null, "e": 8557, "s": 7886, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\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": 8905, "s": 8557, "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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
How to Explain Graph Neural Network — GNNExplainer | by Shanon Hong | Towards Data Science
Graph Neural Network(GNN) is a type of neural network that can be directly applied to graph-structured data. My previous post gave a brief introduction on GNN. Readers may be directed to this post for more details. Many research works have shown GNN’s power for understanding graphs, but the way how and why GNN works still remains a mystery for most people. Unlike CNN, where we can extract activation of each layer to visualize the decisions of the network, in GNN it is hard to get a meaningful explanation of what features the network has learnt. Why does GNN determine a node is class A instead of class B? Why does GNN determine a graph is a chemical or molecule? It seems like GNN sees some useful structural information and determines are made upon these observations. But now the problem is, what observations does GNN see? GNNExplainer is introduced in this paper. Briefly speaking, it is trying to build a network to learn what a GNN has learnt. The main principle of GNNExplainer is by reducing redundant information in a graph which does not directly impact the decisions. To explain a graph, we want to know what are the crucial features or structures in the graph that affect the decisions of a neural network. If a feature is important, then the prediction should be altered largely by removing or replacing this feature with something else. On the other hand, if removing or altering a feature does not affect the prediction outcome, the feature is considered not essential and thus should not be included in the explanation for a graph. The primary objective for GNNExplainer is to generate a minimal graph that explains the decision for a node or a graph. To achieve this goal, the problem can be defined as finding a subgraph in the computation graph, that minimizes the difference in the prediction scores using the whole computation graph and the minimal graph. In the paper, this process is formulated as maximizing the mutual information(MI) between the minimal graph Gs and the computation graph G: Besides, there is a secondary objective: the graph needs to be minimal. Though it was also mentioned in the first objective, we need to have a method to formulate this objective as well. The paper addresses it by adding a loss for the number of edges. Therefore, the loss for GNNExplainer is literally the combination of prediction loss and edge size loss. Three types of explanations are discussed in the paper: the explanation for one node, the explanation for one class of nodes, and the explanation for a graph. The major difference is in the computation graphs. For an explanation on a single node, the computation graph is its k-hops neighbours, where k is the number of convolutions in the model. For an explanation on a class of nodes, the paper suggests selecting a reference node and using the same method to compute explanation. The reference node can be selected by taking the node whose features are closest to the mean features of all other nodes with the same class. For an explanation of the entire graph, the computation graph becomes the union of the computation graphs for all nodes in the graph. That makes the computation graph equivalent to the entire input graph. The learning of the minimal graph Gs is by learning a mask for edges and a mask for features. That is, for each edge in the computation graph, there exists a value in the edge_mask which determines the importance of the edge. Similarly, for each feature in the node feature, the feature_mask determines if the feature is important to the final decision. With all those concepts, we can summarize everything for a GNNExplainer: We need to extract the computation graph, which is the k-hops neighbour for node classification, or the entire graph for graph classification.Initialize an edge_mask for each edge in the computation graph, and a feature mask for each feature dimension.Construct a neural network that learns the edge_mask and feature_mask with loss described above.Use edge_mask and feature_mask to reduce the computation graph to a minimal graph. We need to extract the computation graph, which is the k-hops neighbour for node classification, or the entire graph for graph classification. Initialize an edge_mask for each edge in the computation graph, and a feature mask for each feature dimension. Construct a neural network that learns the edge_mask and feature_mask with loss described above. Use edge_mask and feature_mask to reduce the computation graph to a minimal graph. That’s about everything we need to know before we can implement a GNNExplainer. To summarize up, we are trying to learn an edge_mask and a node_feature_mask which remove some edges and features from the computation graph while minimizing the difference in prediction score, the resultant graph is a minimal graph that explains the decision of the node or graph. I’m going to implement this in Pytorch Geometric(PyG). One great advantage of PyG is that it updates very frequently and has many implementations of current models. Surprisingly I found GNNExplainer is already implemented in PyG library, which saves me a lot of time. Although it only works for node explanations, thanks to its open-source, it is not hard to change it to work for graph explanations as well. To start, we first need to install PyG. GNNExplainer is not yet in their current release (PyG 1.4.4) but the codes are already released their Github. So to get GNNExplainer, you must clone from their Github repository and install from there. The example code is provided on the PyG website. It is easy to follow so I’m not going to show the code in this post. But the implementation details are something we want to check out and use it for graph classification thereafter. I’m going to trace the code based on my short summary above. The example code passes node index, together with the full feature matrix and edge list to a GNNExplainer module. explainer = GNNExplainer(model, epochs=200)node_idx = 10node_feat_mask, edge_mask = explainer.explain_node(node_idx, x, edge_index) What’s happening in GNNExplainer is exactly what we discussed in the previous section. Extract the computation graph Extract the computation graph To Explain a node, we first need to get its k-hop computation graph. This is done by __subgraph__() method in PyG. x, edge_index, hard_edge_mask, kwargs = self.__subgraph__( node_idx, x, edge_index, **kwargs) The hard_edge_mask removes all other edges outside the k-hop neighbourhood. 2. Masks are initialized by __set_mask__() method and applied to every layer of the network. self.__set_masks__(x, edge_index) def __set_masks__(self, x, edge_index, init="normal"): (N, F), E = x.size(), edge_index.size(1) std = 0.1 self.node_feat_mask = torch.nn.Parameter(torch.randn(F) * 0.1) std = torch.nn.init.calculate_gain('relu') * sqrt(2.0 / (2 * N)) self.edge_mask = torch.nn.Parameter(torch.randn(E) * std) for module in self.model.modules(): if isinstance(module, MessagePassing): module.__explain__ = True module.__edge_mask__ = self.edge_mask 3. Initial prediction is performed using the trained model, then the prediction is used as a label to train the GNNExplainer. # Get the initial prediction. with torch.no_grad(): log_logits = self.model(x=x, edge_index=edge_index, **kwargs) pred_label = log_logits.argmax(dim=-1) # Train GNNExplainerfor epoch in range(1, self.epochs + 1): optimizer.zero_grad() h = x * self.node_feat_mask.view(1, -1).sigmoid() log_logits = self.model(x=h, edge_index=edge_index, **kwargs) loss = self.__loss__(0, log_logits, pred_label) loss.backward() optimizer.step() 4. The loss is defined def __loss__(self, node_idx, log_logits, pred_label): loss = -log_logits[node_idx, pred_label[node_idx]] m = self.edge_mask.sigmoid() loss = loss + self.coeffs['edge_size'] * m.sum() ent = -m * torch.log(m + EPS) - (1 - m) * torch.log(1 - m + EPS) loss = loss + self.coeffs['edge_ent'] * ent.mean() m = self.node_feat_mask.sigmoid() loss = loss + self.coeffs['node_feat_size'] * m.sum() ent = -m * torch.log(m + EPS) - (1 - m) * torch.log(1 - m + EPS) loss = loss + self.coeffs['node_feat_ent'] * ent.mean() return loss The current implementation is PyG is only for node explanation. But having understanding the principles behind, it isn’t hard to rewrite the function for graph explanation. Only A few functions we need to replace: 1) we need to replace __subgraph__ function to obtain the computation graph for the entire graph. 2) we need to set masks for the entire graph. 3) We need to change the loss function to compute loss for graphs. Complete code implementation is available at this Github link. GNNExplainer provides a framework to visualize what a GNN model has learnt. However, the actual explanation result may not be good enough to explain a huge graph as search space for the optimal explanation is exponentially larger than a smaller one. Instead of fitting a neural network, other search techniques may also be applied to find the optimal explanation borrowing the same concepts and the performance is yet to be proved. GNNExplainer: Generating Explanations for Graph Neural Networks, https://arxiv.org/abs/1903.03894 Pytorch Geometric, https://pytorch-geometric.readthedocs.io/en/latest/
[ { "code": null, "e": 387, "s": 172, "text": "Graph Neural Network(GNN) is a type of neural network that can be directly applied to graph-structured data. My previous post gave a brief introduction on GNN. Readers may be directed to this post for more details." }, { "code": null, "e": 1005, "s": 387, "text": "Many research works have shown GNN’s power for understanding graphs, but the way how and why GNN works still remains a mystery for most people. Unlike CNN, where we can extract activation of each layer to visualize the decisions of the network, in GNN it is hard to get a meaningful explanation of what features the network has learnt. Why does GNN determine a node is class A instead of class B? Why does GNN determine a graph is a chemical or molecule? It seems like GNN sees some useful structural information and determines are made upon these observations. But now the problem is, what observations does GNN see?" }, { "code": null, "e": 1047, "s": 1005, "text": "GNNExplainer is introduced in this paper." }, { "code": null, "e": 1129, "s": 1047, "text": "Briefly speaking, it is trying to build a network to learn what a GNN has learnt." }, { "code": null, "e": 1727, "s": 1129, "text": "The main principle of GNNExplainer is by reducing redundant information in a graph which does not directly impact the decisions. To explain a graph, we want to know what are the crucial features or structures in the graph that affect the decisions of a neural network. If a feature is important, then the prediction should be altered largely by removing or replacing this feature with something else. On the other hand, if removing or altering a feature does not affect the prediction outcome, the feature is considered not essential and thus should not be included in the explanation for a graph." }, { "code": null, "e": 2196, "s": 1727, "text": "The primary objective for GNNExplainer is to generate a minimal graph that explains the decision for a node or a graph. To achieve this goal, the problem can be defined as finding a subgraph in the computation graph, that minimizes the difference in the prediction scores using the whole computation graph and the minimal graph. In the paper, this process is formulated as maximizing the mutual information(MI) between the minimal graph Gs and the computation graph G:" }, { "code": null, "e": 2553, "s": 2196, "text": "Besides, there is a secondary objective: the graph needs to be minimal. Though it was also mentioned in the first objective, we need to have a method to formulate this objective as well. The paper addresses it by adding a loss for the number of edges. Therefore, the loss for GNNExplainer is literally the combination of prediction loss and edge size loss." }, { "code": null, "e": 2763, "s": 2553, "text": "Three types of explanations are discussed in the paper: the explanation for one node, the explanation for one class of nodes, and the explanation for a graph. The major difference is in the computation graphs." }, { "code": null, "e": 2900, "s": 2763, "text": "For an explanation on a single node, the computation graph is its k-hops neighbours, where k is the number of convolutions in the model." }, { "code": null, "e": 3178, "s": 2900, "text": "For an explanation on a class of nodes, the paper suggests selecting a reference node and using the same method to compute explanation. The reference node can be selected by taking the node whose features are closest to the mean features of all other nodes with the same class." }, { "code": null, "e": 3383, "s": 3178, "text": "For an explanation of the entire graph, the computation graph becomes the union of the computation graphs for all nodes in the graph. That makes the computation graph equivalent to the entire input graph." }, { "code": null, "e": 3737, "s": 3383, "text": "The learning of the minimal graph Gs is by learning a mask for edges and a mask for features. That is, for each edge in the computation graph, there exists a value in the edge_mask which determines the importance of the edge. Similarly, for each feature in the node feature, the feature_mask determines if the feature is important to the final decision." }, { "code": null, "e": 3810, "s": 3737, "text": "With all those concepts, we can summarize everything for a GNNExplainer:" }, { "code": null, "e": 4241, "s": 3810, "text": "We need to extract the computation graph, which is the k-hops neighbour for node classification, or the entire graph for graph classification.Initialize an edge_mask for each edge in the computation graph, and a feature mask for each feature dimension.Construct a neural network that learns the edge_mask and feature_mask with loss described above.Use edge_mask and feature_mask to reduce the computation graph to a minimal graph." }, { "code": null, "e": 4384, "s": 4241, "text": "We need to extract the computation graph, which is the k-hops neighbour for node classification, or the entire graph for graph classification." }, { "code": null, "e": 4495, "s": 4384, "text": "Initialize an edge_mask for each edge in the computation graph, and a feature mask for each feature dimension." }, { "code": null, "e": 4592, "s": 4495, "text": "Construct a neural network that learns the edge_mask and feature_mask with loss described above." }, { "code": null, "e": 4675, "s": 4592, "text": "Use edge_mask and feature_mask to reduce the computation graph to a minimal graph." }, { "code": null, "e": 5037, "s": 4675, "text": "That’s about everything we need to know before we can implement a GNNExplainer. To summarize up, we are trying to learn an edge_mask and a node_feature_mask which remove some edges and features from the computation graph while minimizing the difference in prediction score, the resultant graph is a minimal graph that explains the decision of the node or graph." }, { "code": null, "e": 5446, "s": 5037, "text": "I’m going to implement this in Pytorch Geometric(PyG). One great advantage of PyG is that it updates very frequently and has many implementations of current models. Surprisingly I found GNNExplainer is already implemented in PyG library, which saves me a lot of time. Although it only works for node explanations, thanks to its open-source, it is not hard to change it to work for graph explanations as well." }, { "code": null, "e": 5688, "s": 5446, "text": "To start, we first need to install PyG. GNNExplainer is not yet in their current release (PyG 1.4.4) but the codes are already released their Github. So to get GNNExplainer, you must clone from their Github repository and install from there." }, { "code": null, "e": 5920, "s": 5688, "text": "The example code is provided on the PyG website. It is easy to follow so I’m not going to show the code in this post. But the implementation details are something we want to check out and use it for graph classification thereafter." }, { "code": null, "e": 6095, "s": 5920, "text": "I’m going to trace the code based on my short summary above. The example code passes node index, together with the full feature matrix and edge list to a GNNExplainer module." }, { "code": null, "e": 6227, "s": 6095, "text": "explainer = GNNExplainer(model, epochs=200)node_idx = 10node_feat_mask, edge_mask = explainer.explain_node(node_idx, x, edge_index)" }, { "code": null, "e": 6314, "s": 6227, "text": "What’s happening in GNNExplainer is exactly what we discussed in the previous section." }, { "code": null, "e": 6344, "s": 6314, "text": "Extract the computation graph" }, { "code": null, "e": 6374, "s": 6344, "text": "Extract the computation graph" }, { "code": null, "e": 6489, "s": 6374, "text": "To Explain a node, we first need to get its k-hop computation graph. This is done by __subgraph__() method in PyG." }, { "code": null, "e": 6594, "s": 6489, "text": "x, edge_index, hard_edge_mask, kwargs = self.__subgraph__( node_idx, x, edge_index, **kwargs)" }, { "code": null, "e": 6670, "s": 6594, "text": "The hard_edge_mask removes all other edges outside the k-hop neighbourhood." }, { "code": null, "e": 6763, "s": 6670, "text": "2. Masks are initialized by __set_mask__() method and applied to every layer of the network." }, { "code": null, "e": 7394, "s": 6763, "text": "self.__set_masks__(x, edge_index) def __set_masks__(self, x, edge_index, init=\"normal\"): (N, F), E = x.size(), edge_index.size(1) std = 0.1 self.node_feat_mask = torch.nn.Parameter(torch.randn(F) * 0.1) std = torch.nn.init.calculate_gain('relu') * sqrt(2.0 / (2 * N)) self.edge_mask = torch.nn.Parameter(torch.randn(E) * std) for module in self.model.modules(): if isinstance(module, MessagePassing): module.__explain__ = True module.__edge_mask__ = self.edge_mask" }, { "code": null, "e": 7520, "s": 7394, "text": "3. Initial prediction is performed using the trained model, then the prediction is used as a label to train the GNNExplainer." }, { "code": null, "e": 8087, "s": 7520, "text": "# Get the initial prediction. with torch.no_grad(): log_logits = self.model(x=x, edge_index=edge_index, **kwargs) pred_label = log_logits.argmax(dim=-1) # Train GNNExplainerfor epoch in range(1, self.epochs + 1): optimizer.zero_grad() h = x * self.node_feat_mask.view(1, -1).sigmoid() log_logits = self.model(x=h, edge_index=edge_index, **kwargs) loss = self.__loss__(0, log_logits, pred_label) loss.backward() optimizer.step()" }, { "code": null, "e": 8110, "s": 8087, "text": "4. The loss is defined" }, { "code": null, "e": 8767, "s": 8110, "text": "def __loss__(self, node_idx, log_logits, pred_label): loss = -log_logits[node_idx, pred_label[node_idx]] m = self.edge_mask.sigmoid() loss = loss + self.coeffs['edge_size'] * m.sum() ent = -m * torch.log(m + EPS) - (1 - m) * torch.log(1 - m + EPS) loss = loss + self.coeffs['edge_ent'] * ent.mean() m = self.node_feat_mask.sigmoid() loss = loss + self.coeffs['node_feat_size'] * m.sum() ent = -m * torch.log(m + EPS) - (1 - m) * torch.log(1 - m + EPS) loss = loss + self.coeffs['node_feat_ent'] * ent.mean() return loss" }, { "code": null, "e": 8940, "s": 8767, "text": "The current implementation is PyG is only for node explanation. But having understanding the principles behind, it isn’t hard to rewrite the function for graph explanation." }, { "code": null, "e": 9192, "s": 8940, "text": "Only A few functions we need to replace: 1) we need to replace __subgraph__ function to obtain the computation graph for the entire graph. 2) we need to set masks for the entire graph. 3) We need to change the loss function to compute loss for graphs." }, { "code": null, "e": 9255, "s": 9192, "text": "Complete code implementation is available at this Github link." }, { "code": null, "e": 9687, "s": 9255, "text": "GNNExplainer provides a framework to visualize what a GNN model has learnt. However, the actual explanation result may not be good enough to explain a huge graph as search space for the optimal explanation is exponentially larger than a smaller one. Instead of fitting a neural network, other search techniques may also be applied to find the optimal explanation borrowing the same concepts and the performance is yet to be proved." }, { "code": null, "e": 9785, "s": 9687, "text": "GNNExplainer: Generating Explanations for Graph Neural Networks, https://arxiv.org/abs/1903.03894" } ]
Promoting Energy and Economic Empowerment with Python | by Diogo Sá | Towards Data Science
I created a tool to do solar power simulations over a 20 year time and tested it on my city, Porto, with several values of electricity average monthly bills. The goal is to give, for each average monthly bill, the best solar solution (which and how many solar panels, if a battery, and which battery, would be a good idea) to maximize the return of the investment.This report can be useful by consumers or companies. The most important parts of the code can be viewed at Github.Check the report of this project below! The idea for this project came out when I was trying to think about what I would do if I ran a renewable energy company. Of course, other software exists to calculate the renewable energy potential but neither is free, accurate and with the possibility to compare multiple solar panels at the same time. Being passionate about renewable energies I thought this would be the perfect first project on python data science libraries. When it comes to scientific computing and data science the two key python libraries are NumPy and pandas. Numpy has incredible advantages on its use: NumPy is written in Python and C, therefore NumPy arrays are faster compared to Python lists. However, unlike Python lists, NumPy arrays are not flexible and all elements should be of the same type. Pandas is quite a game changer when it comes to analyzing data with Python. Pandas receives data (CSV file, SQL databases, etc.) and creates a Python object with rows and columns called data frame that looks very similar to table in a statistical software (allow mathematical operations on the data structures, ignoring the metadata of the data structures, uses relational operations and it is easy to handle missing data). This enables easy and fast data analysis and manipulation tools by providing numerical tables and time series data structures. Scikit-learn is a powerful and efficient tool for data mining and data analysis. The library is focused on modeling data and is one of the main libraries to use when doing machine learning projects. PVlib python is a community supported tool that provides a set of functions and classes for simulating the performance of photovoltaic energy systems. PVlib was developed at Sandia National Laboratories and it implements many of the models and methods developed at the Labs. Sandia National Laboratories is facilitating a collaborative group of photovoltaic (PV) professionals (PV Performance Modeling Collaborative or PVPMC). This group is interested in improving the accuracy and technical rigor of PV performance models and analyses. Such models are used to evaluate current performance (performance index) and determine the future value of PV generation projects (expressed as the predicted energy yield) and, by extension, influence how PV projects and technologies are perceived by the financial community in terms of investment risk. The source code for PVlib python is hosted on GitHub. The important code used on this section can be viewed on Github: Function_Find_Panels, Find_Panels_DB, Prices_aux Due to the lack of information regarding the solar panel prices on the Sandia Database, new ways of finding how the companies valued their products were found. Two databases were created based on web scrapping two different websites with solar panel price information. The two websites had different relevant information: DB1: Brand; Solar Panel Model; Maximum Power; Everyday Power; Efficiency; Minimum Power; Cost per Panel; Country of production; Warranty; DB2: Brand; Solar Panel Model; Power; Cost per Panel; Size; Weight; Country of production As there was no clear or available data on the prices of the solar modules to be tested. I had to create an interpolation method to predict the price per watt that each solar company was charging based on the prices charged for the panels available for purchase, its power and the year. A new database was created associating the solar panel brands with its predicted prices with two methods from scikit-learn library: (1) Linear Regression Method — A single independent variable is used to predict the value of a dependent variable; (2) Ransac Method — Iterative algorithm for the robust estimation of parameters from a subset of inliers from the complete data set. Looking at the plots above, it is possible to see that for SunPower prices, the two regression methods do not differ one from another. On the other hand, LG shows a very interesting case as to why the RANSAC regressor should be chosen to interpolate the price of the modules. If a linear regression was chosen, it was assumed that the prices of LG panels decreased as the power increased and that does not make much sense. For that reason, the RANSAC Regressor was chosen to interpolate the solar module prices. With the most information I could gather regarding the solar module prices, the two databases were compared (Sandia modules and solar panel prices) and 35 panels would be tested from that comparison (see table on the left). Panel Name and Sandia_Name are with “(...)” in the image on the lefy to avoid creating a table too large. The important code used on this section can be viewed on Github: CONSUMPTION_FUNC, sazonal_consumption, AC_helper The consumption function was adapted from the California hourly electric load curve. It was assumed that the same curve pattern applied to Portugal’s case. The curve from the image was scanned through a plot digitizer package which converted the curve to a x,y coordinates text file. With numpy, I created a function that would fit the points that I had previously marked on the plot digitizer package. Several polifit functions with different regression degrees were run and the degree with less error was found at n=15 (see image below) It was also important to know the seasonal consumption pattern. For that, the same procedure was made for a Portuguese energy monthly variation. Now comes the tricky part:The daily variation had to fit within the yearly variation of energy consumption. In other words, the daily energy consumption within each month had to check with the variation that each month had within a year. For that, I divided every value with the sum of all the Watt values. That way, the sum of all values would be one. The yearly variation on electrical consumption was made differently. Instead of having the sum equal to one, as in a cluster of consumptions, it made sense to divide every 12 values for the mean of the values. That way it would be easy to multiply the values with the average monthly bill. With numpy functionalities, a matrix 24x12 was created. Inside the matrix, there are the values of electricity consumed through each hour every month (it was assumed that there was no variation of consumption within the days from the same month). Finally, with the pandas library date-range (the same used in PVlib), for every hour of the calculation was allocated a specific electrical consumption. The batteries database was built by web scrapping three websites with battery information and prices. A database with 22 battery models was created. The models were from AXITEC Energy, LG, SolaX Power, BYD, Tesla, PYLONTECH, VARTA and Enphase were stored in a csv file and contained the information as the example on the left. The important code used on this section can be viewed on Github: Solar_modules, Batt_Interpreter, Batt_Script To ensure the most accurate results as possible, the calculations are done by the hour. The solar panels energy is calculated with irradiance changes over the year and over the years in hourly periods. Having a 20 year time-line, each round of calculations for a single panel combined with the consumption data takes about 40 seconds. Calculating all the panel production with all the batteries for all the electric bills would take an absurd amount of time. To tackle this issue I thought about discovering the best solution for each monthly electric bill in three steps: Step 1 — Every solar panel would be tested to sort them in potential savings. The calculated savings would be an approximation of the real savings that would be calculated in step 2.Step 2 — The five best potential savings for each average monthly bill would make it step 2 calculations. On this stage, precision savings will be simulated.Step 3 — The two best cases on step 2 for every average monthly bill would be tested with every battery on the battery database. The first calculations involving solar panels performance were made with the use of the PVlib library. For every average monthly bill, it is calculated how many solar panels would be needed to ensure that the yearly production of each panel installation would be at least close enough to the yearly consumption. Three models were created for each solar module installation to give the consumers more choice and improve transparency. The first, using the closest integer number from what the yearly consumption divided by the annual energy of one panel would be (n=0). The second case would be one more panel than the first one (n=1) and the third case being one less panel than the first case (n=-1). The savings per panel were calculated being the energy produced over the 20 years times the price per kWh of energy in Portugal subtracting by the price of the panel. The total savings for the recommended number of solar panels, the savings were multiplicated by the number of recommended solar panels. For each installation, a new database was created. The table above represents the best case when the monthly average bill is 50€ and n=0. The results from step 1 are the basis for this stage. Only the five best results from the previous stage are calculated now. A new method to calculate the total savings is introduced. On this stage, the savings are calculated hourly for improved precision. The consumption function calculated above takes part in this. The method consisted on calculating the savings being a balance between the money that one would spend without the installation during the 20 year time, the initial investment, the money that one would still have to buy to the grid (night times essentially) and the money earned from selling power to the grid (although in Portugal this value is still 4 times lower compared to buying energy to the grid). To calculate hourly if the solar panels would be producing energy to feed the consumer needs, not producing at all or even producing more than the needs the following for loop was used with ac_df having 175 316 elements (number of hours in 20 years): for k in range(len(ac_df)): Grid_Power[k] = consumo[k] - ac_df.iloc[k].loc['Watt-hour']if Grid_Power[k] < 0: Grid_Buying_Power[k] = 0 Grid_Selling_Power[k] = Grid_Power[k]if Grid_Power[k] > 0: Grid_Buying_Power[k] = Grid_Power[k] Grid_Selling_Power[k] = 0 Once again, three solutions were calculated for each average monthly bill. The final results on this step present five panels and reorder them by the new savings calculation. On the image at the left there is the final information for the best panel for a monthly average of 75€ (when n=0). After looking at these results, a careful eye would say that the results presented on this panel are simply impossible. Unfortunately, a bought electricity of only 1129.6€ in a 20 year period is impossible. In Portugal, the daylight period is about 40%. Thus, without batteries, the total electricity bought from the grid would have to be somewhere near half of the price paid for electricity without solar panels. This error was found on several other panels and those panels were erased from the calculations. Step 3 calculations contemplate the battery storage. The savings calculations are done similarly to step 2 but this time having the battery to store energy to be used overnight. It is expected that the remaining buying electricity to the grid to be near zero in all cases. On these calculations, the 2 best panels (on step 2) on each average monthly bill was used. To calculate hourly if the balance of energy production and battery storage the following for loop was used: for k in range(len(ac_df)):if k == 0: batt_stock[k] = batt_aux + ac_df.iloc[k].loc['Watt-hour'] -consumo[k]else: batt_stock[k] = batt_stock[k - 1] + ac_df.iloc[k].loc['Watt-hour'] - consumo[k] Grid_Selling_Power[k],Grid_Selling_Power[k] = 0, 0if batt_stock[k] < 0: Grid_Buying_Power[k] = - copy.deepcopy(batt_stock[k]) batt_stock[k] = 0if batt_stock[k] > Battery_Capacity_Wh[num]: Grid_Selling_Power[k] = batt_stock[k] - battery_Capacity_Wh[num] batt_stock[k] = copy.deepcopy(Battery_Capacity_Wh[num]) Grid_Buying_Power[k] = 0 The best solution was chosen based on the highest savings value. Final results are presented for each average monthly electric bill: Although the results are very accurate, approximations were made: (1) Every solar panel was considered to have the same 15% loss of efficiency over the 20 year period (see the calculations here); (2) Only one inversor was used on the calculations. This may result in different results since an inversor can work better on a certain type of solar panel; (3) The energy loss between solar modules was not accounted for. Although the small setback with some panel’s bought from the grid values eliminated some solar modules from the calculation, reducing the number of solar panels and brands from the study, the goal of this project was reached. It was proven that solar panels can be a great long-term investment and batteries can make that investment even more profitable.We can draw a line between the number of watts hour consumed during a time period and the number of solar panels that your house should need. The number of panels installed should be able to generate that power at the same time period. That way, the solar installation will generate 200% emotional profit and 400% of real, monetary, profit. Renewable energies can be a great way to empower new generations of people. Saving, at average, 620€ per year can be a big leap forward in people’s lives and with smart investments, the money saved on the electrical bill can become a game changer to entrepreneurs and companies. This post marks the first perkier.tech project. perkier.tech creates innovative engineering projects aimed to help the world to be a better place and at the same time letting me research and learn something new. The next step on this energy project will be creating a small grid-independent community using micro-grid and blockchain technologies with also implementing new ways of generating energy (p.e. small wind turbines). I will be learning more about smart grids and blockchain code for the next few months. I welcome feedback and suggestions! I’d love to hear from you about new ideas on how to implement innovative engineering. You can reach me at diogoncsa@gmail.com or find me at LinkedIn
[ { "code": null, "e": 589, "s": 172, "text": "I created a tool to do solar power simulations over a 20 year time and tested it on my city, Porto, with several values of electricity average monthly bills. The goal is to give, for each average monthly bill, the best solar solution (which and how many solar panels, if a battery, and which battery, would be a good idea) to maximize the return of the investment.This report can be useful by consumers or companies." }, { "code": null, "e": 690, "s": 589, "text": "The most important parts of the code can be viewed at Github.Check the report of this project below!" }, { "code": null, "e": 1120, "s": 690, "text": "The idea for this project came out when I was trying to think about what I would do if I ran a renewable energy company. Of course, other software exists to calculate the renewable energy potential but neither is free, accurate and with the possibility to compare multiple solar panels at the same time. Being passionate about renewable energies I thought this would be the perfect first project on python data science libraries." }, { "code": null, "e": 1226, "s": 1120, "text": "When it comes to scientific computing and data science the two key python libraries are NumPy and pandas." }, { "code": null, "e": 1469, "s": 1226, "text": "Numpy has incredible advantages on its use: NumPy is written in Python and C, therefore NumPy arrays are faster compared to Python lists. However, unlike Python lists, NumPy arrays are not flexible and all elements should be of the same type." }, { "code": null, "e": 2020, "s": 1469, "text": "Pandas is quite a game changer when it comes to analyzing data with Python. Pandas receives data (CSV file, SQL databases, etc.) and creates a Python object with rows and columns called data frame that looks very similar to table in a statistical software (allow mathematical operations on the data structures, ignoring the metadata of the data structures, uses relational operations and it is easy to handle missing data). This enables easy and fast data analysis and manipulation tools by providing numerical tables and time series data structures." }, { "code": null, "e": 2219, "s": 2020, "text": "Scikit-learn is a powerful and efficient tool for data mining and data analysis. The library is focused on modeling data and is one of the main libraries to use when doing machine learning projects." }, { "code": null, "e": 2494, "s": 2219, "text": "PVlib python is a community supported tool that provides a set of functions and classes for simulating the performance of photovoltaic energy systems. PVlib was developed at Sandia National Laboratories and it implements many of the models and methods developed at the Labs." }, { "code": null, "e": 3060, "s": 2494, "text": "Sandia National Laboratories is facilitating a collaborative group of photovoltaic (PV) professionals (PV Performance Modeling Collaborative or PVPMC). This group is interested in improving the accuracy and technical rigor of PV performance models and analyses. Such models are used to evaluate current performance (performance index) and determine the future value of PV generation projects (expressed as the predicted energy yield) and, by extension, influence how PV projects and technologies are perceived by the financial community in terms of investment risk." }, { "code": null, "e": 3114, "s": 3060, "text": "The source code for PVlib python is hosted on GitHub." }, { "code": null, "e": 3228, "s": 3114, "text": "The important code used on this section can be viewed on Github: Function_Find_Panels, Find_Panels_DB, Prices_aux" }, { "code": null, "e": 3550, "s": 3228, "text": "Due to the lack of information regarding the solar panel prices on the Sandia Database, new ways of finding how the companies valued their products were found. Two databases were created based on web scrapping two different websites with solar panel price information. The two websites had different relevant information:" }, { "code": null, "e": 3688, "s": 3550, "text": "DB1: Brand; Solar Panel Model; Maximum Power; Everyday Power; Efficiency; Minimum Power; Cost per Panel; Country of production; Warranty;" }, { "code": null, "e": 3778, "s": 3688, "text": "DB2: Brand; Solar Panel Model; Power; Cost per Panel; Size; Weight; Country of production" }, { "code": null, "e": 4065, "s": 3778, "text": "As there was no clear or available data on the prices of the solar modules to be tested. I had to create an interpolation method to predict the price per watt that each solar company was charging based on the prices charged for the panels available for purchase, its power and the year." }, { "code": null, "e": 4445, "s": 4065, "text": "A new database was created associating the solar panel brands with its predicted prices with two methods from scikit-learn library: (1) Linear Regression Method — A single independent variable is used to predict the value of a dependent variable; (2) Ransac Method — Iterative algorithm for the robust estimation of parameters from a subset of inliers from the complete data set." }, { "code": null, "e": 4957, "s": 4445, "text": "Looking at the plots above, it is possible to see that for SunPower prices, the two regression methods do not differ one from another. On the other hand, LG shows a very interesting case as to why the RANSAC regressor should be chosen to interpolate the price of the modules. If a linear regression was chosen, it was assumed that the prices of LG panels decreased as the power increased and that does not make much sense. For that reason, the RANSAC Regressor was chosen to interpolate the solar module prices." }, { "code": null, "e": 5287, "s": 4957, "text": "With the most information I could gather regarding the solar module prices, the two databases were compared (Sandia modules and solar panel prices) and 35 panels would be tested from that comparison (see table on the left). Panel Name and Sandia_Name are with “(...)” in the image on the lefy to avoid creating a table too large." }, { "code": null, "e": 5401, "s": 5287, "text": "The important code used on this section can be viewed on Github: CONSUMPTION_FUNC, sazonal_consumption, AC_helper" }, { "code": null, "e": 5685, "s": 5401, "text": "The consumption function was adapted from the California hourly electric load curve. It was assumed that the same curve pattern applied to Portugal’s case. The curve from the image was scanned through a plot digitizer package which converted the curve to a x,y coordinates text file." }, { "code": null, "e": 5940, "s": 5685, "text": "With numpy, I created a function that would fit the points that I had previously marked on the plot digitizer package. Several polifit functions with different regression degrees were run and the degree with less error was found at n=15 (see image below)" }, { "code": null, "e": 6085, "s": 5940, "text": "It was also important to know the seasonal consumption pattern. For that, the same procedure was made for a Portuguese energy monthly variation." }, { "code": null, "e": 6438, "s": 6085, "text": "Now comes the tricky part:The daily variation had to fit within the yearly variation of energy consumption. In other words, the daily energy consumption within each month had to check with the variation that each month had within a year. For that, I divided every value with the sum of all the Watt values. That way, the sum of all values would be one." }, { "code": null, "e": 6728, "s": 6438, "text": "The yearly variation on electrical consumption was made differently. Instead of having the sum equal to one, as in a cluster of consumptions, it made sense to divide every 12 values for the mean of the values. That way it would be easy to multiply the values with the average monthly bill." }, { "code": null, "e": 6975, "s": 6728, "text": "With numpy functionalities, a matrix 24x12 was created. Inside the matrix, there are the values of electricity consumed through each hour every month (it was assumed that there was no variation of consumption within the days from the same month)." }, { "code": null, "e": 7128, "s": 6975, "text": "Finally, with the pandas library date-range (the same used in PVlib), for every hour of the calculation was allocated a specific electrical consumption." }, { "code": null, "e": 7230, "s": 7128, "text": "The batteries database was built by web scrapping three websites with battery information and prices." }, { "code": null, "e": 7455, "s": 7230, "text": "A database with 22 battery models was created. The models were from AXITEC Energy, LG, SolaX Power, BYD, Tesla, PYLONTECH, VARTA and Enphase were stored in a csv file and contained the information as the example on the left." }, { "code": null, "e": 7565, "s": 7455, "text": "The important code used on this section can be viewed on Github: Solar_modules, Batt_Interpreter, Batt_Script" }, { "code": null, "e": 8138, "s": 7565, "text": "To ensure the most accurate results as possible, the calculations are done by the hour. The solar panels energy is calculated with irradiance changes over the year and over the years in hourly periods. Having a 20 year time-line, each round of calculations for a single panel combined with the consumption data takes about 40 seconds. Calculating all the panel production with all the batteries for all the electric bills would take an absurd amount of time. To tackle this issue I thought about discovering the best solution for each monthly electric bill in three steps:" }, { "code": null, "e": 8606, "s": 8138, "text": "Step 1 — Every solar panel would be tested to sort them in potential savings. The calculated savings would be an approximation of the real savings that would be calculated in step 2.Step 2 — The five best potential savings for each average monthly bill would make it step 2 calculations. On this stage, precision savings will be simulated.Step 3 — The two best cases on step 2 for every average monthly bill would be tested with every battery on the battery database." }, { "code": null, "e": 8918, "s": 8606, "text": "The first calculations involving solar panels performance were made with the use of the PVlib library. For every average monthly bill, it is calculated how many solar panels would be needed to ensure that the yearly production of each panel installation would be at least close enough to the yearly consumption." }, { "code": null, "e": 9307, "s": 8918, "text": "Three models were created for each solar module installation to give the consumers more choice and improve transparency. The first, using the closest integer number from what the yearly consumption divided by the annual energy of one panel would be (n=0). The second case would be one more panel than the first one (n=1) and the third case being one less panel than the first case (n=-1)." }, { "code": null, "e": 9748, "s": 9307, "text": "The savings per panel were calculated being the energy produced over the 20 years times the price per kWh of energy in Portugal subtracting by the price of the panel. The total savings for the recommended number of solar panels, the savings were multiplicated by the number of recommended solar panels. For each installation, a new database was created. The table above represents the best case when the monthly average bill is 50€ and n=0." }, { "code": null, "e": 9873, "s": 9748, "text": "The results from step 1 are the basis for this stage. Only the five best results from the previous stage are calculated now." }, { "code": null, "e": 10473, "s": 9873, "text": "A new method to calculate the total savings is introduced. On this stage, the savings are calculated hourly for improved precision. The consumption function calculated above takes part in this. The method consisted on calculating the savings being a balance between the money that one would spend without the installation during the 20 year time, the initial investment, the money that one would still have to buy to the grid (night times essentially) and the money earned from selling power to the grid (although in Portugal this value is still 4 times lower compared to buying energy to the grid)." }, { "code": null, "e": 10724, "s": 10473, "text": "To calculate hourly if the solar panels would be producing energy to feed the consumer needs, not producing at all or even producing more than the needs the following for loop was used with ac_df having 175 316 elements (number of hours in 20 years):" }, { "code": null, "e": 11015, "s": 10724, "text": "for k in range(len(ac_df)): Grid_Power[k] = consumo[k] - ac_df.iloc[k].loc['Watt-hour']if Grid_Power[k] < 0: Grid_Buying_Power[k] = 0 Grid_Selling_Power[k] = Grid_Power[k]if Grid_Power[k] > 0: Grid_Buying_Power[k] = Grid_Power[k] Grid_Selling_Power[k] = 0" }, { "code": null, "e": 11090, "s": 11015, "text": "Once again, three solutions were calculated for each average monthly bill." }, { "code": null, "e": 11818, "s": 11090, "text": "The final results on this step present five panels and reorder them by the new savings calculation. On the image at the left there is the final information for the best panel for a monthly average of 75€ (when n=0). After looking at these results, a careful eye would say that the results presented on this panel are simply impossible. Unfortunately, a bought electricity of only 1129.6€ in a 20 year period is impossible. In Portugal, the daylight period is about 40%. Thus, without batteries, the total electricity bought from the grid would have to be somewhere near half of the price paid for electricity without solar panels. This error was found on several other panels and those panels were erased from the calculations." }, { "code": null, "e": 12091, "s": 11818, "text": "Step 3 calculations contemplate the battery storage. The savings calculations are done similarly to step 2 but this time having the battery to store energy to be used overnight. It is expected that the remaining buying electricity to the grid to be near zero in all cases." }, { "code": null, "e": 12183, "s": 12091, "text": "On these calculations, the 2 best panels (on step 2) on each average monthly bill was used." }, { "code": null, "e": 12292, "s": 12183, "text": "To calculate hourly if the balance of energy production and battery storage the following for loop was used:" }, { "code": null, "e": 12926, "s": 12292, "text": "for k in range(len(ac_df)):if k == 0: batt_stock[k] = batt_aux + ac_df.iloc[k].loc['Watt-hour'] -consumo[k]else: batt_stock[k] = batt_stock[k - 1] + ac_df.iloc[k].loc['Watt-hour'] - consumo[k] Grid_Selling_Power[k],Grid_Selling_Power[k] = 0, 0if batt_stock[k] < 0: Grid_Buying_Power[k] = - copy.deepcopy(batt_stock[k]) batt_stock[k] = 0if batt_stock[k] > Battery_Capacity_Wh[num]: Grid_Selling_Power[k] = batt_stock[k] - battery_Capacity_Wh[num] batt_stock[k] = copy.deepcopy(Battery_Capacity_Wh[num]) Grid_Buying_Power[k] = 0" }, { "code": null, "e": 12991, "s": 12926, "text": "The best solution was chosen based on the highest savings value." }, { "code": null, "e": 13059, "s": 12991, "text": "Final results are presented for each average monthly electric bill:" }, { "code": null, "e": 13477, "s": 13059, "text": "Although the results are very accurate, approximations were made: (1) Every solar panel was considered to have the same 15% loss of efficiency over the 20 year period (see the calculations here); (2) Only one inversor was used on the calculations. This may result in different results since an inversor can work better on a certain type of solar panel; (3) The energy loss between solar modules was not accounted for." }, { "code": null, "e": 14172, "s": 13477, "text": "Although the small setback with some panel’s bought from the grid values eliminated some solar modules from the calculation, reducing the number of solar panels and brands from the study, the goal of this project was reached. It was proven that solar panels can be a great long-term investment and batteries can make that investment even more profitable.We can draw a line between the number of watts hour consumed during a time period and the number of solar panels that your house should need. The number of panels installed should be able to generate that power at the same time period. That way, the solar installation will generate 200% emotional profit and 400% of real, monetary, profit." }, { "code": null, "e": 14451, "s": 14172, "text": "Renewable energies can be a great way to empower new generations of people. Saving, at average, 620€ per year can be a big leap forward in people’s lives and with smart investments, the money saved on the electrical bill can become a game changer to entrepreneurs and companies." }, { "code": null, "e": 14663, "s": 14451, "text": "This post marks the first perkier.tech project. perkier.tech creates innovative engineering projects aimed to help the world to be a better place and at the same time letting me research and learn something new." }, { "code": null, "e": 14878, "s": 14663, "text": "The next step on this energy project will be creating a small grid-independent community using micro-grid and blockchain technologies with also implementing new ways of generating energy (p.e. small wind turbines)." }, { "code": null, "e": 14965, "s": 14878, "text": "I will be learning more about smart grids and blockchain code for the next few months." }, { "code": null, "e": 15087, "s": 14965, "text": "I welcome feedback and suggestions! I’d love to hear from you about new ideas on how to implement innovative engineering." } ]
Curiously recurring template pattern (CRTP) - GeeksforGeeks
20 Sep, 2021 Background: It is recommended to refer Virtual Functions and Runtime Polymorphism as a prerequisite of this. Below is an example program to demonstrate run time polymorphism. CPP // A simple C++ program to demonstrate run-time// polymorphism#include <chrono>#include <iostream>using namespace std; typedef std::chrono::high_resolution_clock Clock; // To store dimensions of an imageclass Dimension {public: Dimension(int _X, int _Y) { mX = _X; mY = _Y; } private: int mX, mY;}; // Base class for all image typesclass Image {public: virtual void Draw() = 0; virtual Dimension GetDimensionInPixels() = 0; protected: int dimensionX; int dimensionY;}; // For Tiff Imagesclass TiffImage : public Image {public: void Draw() {} Dimension GetDimensionInPixels() { return Dimension(dimensionX, dimensionY); }}; // There can be more derived classes like PngImage,// BitmapImage, etc // Driver code that calls virtual functionint main(){ // An image type Image* pImage = new TiffImage; // Store time before virtual function calls auto then = Clock::now(); // Call Draw 1000 times to make sure performance // is visible for (int i = 0; i < 1000; ++i) pImage->Draw(); // Store time after virtual function calls auto now = Clock::now(); cout << "Time taken: " << std::chrono::duration_cast<std::chrono::nanoseconds>(now - then).count() << " nanoseconds" << endl; return 0;} Output : Time taken: 2613 nanoseconds See this for above result.When a method is declared virtual, compiler secretly does two things for us: Defines a VPtr in first 4 bytes of the class objectInserts code in constructor to initialize VPtr to point to the VTable Defines a VPtr in first 4 bytes of the class object Inserts code in constructor to initialize VPtr to point to the VTable What are VTable and VPtr? When a method is declared virtual in a class, compiler creates a virtual table (aka VTable) and stores addresses of virtual methods in that table. A virtual pointer (aka VPtr) is then created and initialized to point to that VTable. A VTable is shared across all the instances of the class, i.e. compiler creates only one instance of VTable to be shared across all the objects of a class. Each instance of the class has its own version of VPtr. If we print the size of a class object containing at least one virtual method, the output will be sizeof(class data) + sizeof(VPtr). Since address of virtual method is stored in VTable, VPtr can be manipulated to make calls to those virtual methods thereby violating principles of encapsulation. See below example: CPP // A C++ program to demonstrate that we can directly// manipulate VPtr. Note that this program is based// on the assumption that compiler store vPtr in a// specific way to achieve run-time polymorphism.#include <iostream>using namespace std; #pragma pack(1) // A base class with virtual function foo()class CBase {public: virtual void foo() noexcept { cout << "CBase::Foo() called" << endl; } protected: int mData;}; // A derived class with its own implementation// of foo()class CDerived : public CBase {public: void foo() noexcept { cout << "CDerived::Foo() called" << endl; } private: char cChar;}; // Driver codeint main(){ // A base type pointer pointing to derived CBase* pBase = new CDerived; // Accessing vPtr int* pVPtr = *(int**)pBase; // Calling virtual method ((void (*)())pVPtr[0])(); // Changing vPtr delete pBase; pBase = new CBase; pVPtr = *(int**)pBase; // Calls method for new base object ((void (*)())pVPtr[0])(); return 0;} Output : CDerived::Foo() called CBase::Foo() called We are able to access vPtr and able to make calls to virtual methods through it. The memory representation of objects is explained here.Is it wise to use virtual method? As it can be seen, through base class pointer, call to derived class method is being dispatched. Everything seems to be working fine. Then what is the problem? If a virtual routine is called many times (order of hundreds of thousands), it drops the performance of system, reason being each time the routine is called, its address needs to be resolved by looking through VTable using VPtr. Extra indirection (pointer dereference) for each call to a virtual method makes accessing VTable a costly operation and it is better to avoid it as much as we can. Curiously Recurring Template Pattern (CRTP) Usage of VPtr and VTable can be avoided altogether through Curiously Recurring Template Pattern (CRTP). CRTP is a design pattern in C++ in which a class X derives from a class template instantiation using X itself as template argument. More generally it is known as F-bound polymorphism. CPP // Image program (similar to above) to demonstrate// working of CRTP#include <chrono>#include <iostream>using namespace std; typedef std::chrono::high_resolution_clock Clock; // To store dimensions of an imageclass Dimension {public: Dimension(int _X, int _Y) { mX = _X; mY = _Y; } private: int mX, mY;}; // Base class for all image types. The template// parameter T is used to know type of derived// class pointed by pointer.template <class T>class Image {public: void Draw() { // Dispatch call to exact type static_cast<T*>(this)->Draw(); } Dimension GetDimensionInPixels() { // Dispatch call to exact type static_cast<T*>(this)->GetDimensionInPixels(); } protected: int dimensionX, dimensionY;}; // For Tiff Imagesclass TiffImage : public Image<TiffImage> {public: void Draw() { // Uncomment this to check method dispatch // cout << "TiffImage::Draw() called" << endl; } Dimension GetDimensionInPixels() { return Dimension(dimensionX, dimensionY); }}; // There can be more derived classes like PngImage,// BitmapImage, etc // Driver codeint main(){ // An Image type pointer pointing to Tiffimage Image<TiffImage>* pImage = new TiffImage; // Store time before virtual function calls auto then = Clock::now(); // Call Draw 1000 times to make sure performance // is visible for (int i = 0; i < 1000; ++i) pImage->Draw(); // Store time after virtual function calls auto now = Clock::now(); cout << "Time taken: " << std::chrono::duration_cast<std::chrono::nanoseconds>(now - then).count() << " nanoseconds" << endl; return 0;} Output : Time taken: 732 nanoseconds See this for above result.Virtual method vs CRTP benchmark The time taken while using virtual method was 2613 nanoseconds. This (small) performance gain from CRTP is because the use of a VTable dispatch has been circumvented. Please note that the performance depends on a lot of factors like compiler used, operations performed by virtual methods. Performance numbers might differ in different runs, but (small) performance gain is expected from CRTP. Note: If we print size of class in CRTP, it can bee seen that VPtr no longer reserves 4 bytes of memory. cout << sizeof(Image) << endl; Another use case of CRTP is, when it’s required to access the derived class object in the base class member functions then will have to use CRTP. CPP #include <iostream>#include <typeinfo>using namespace std; template <typename DerivedT> class Base {public: int accessDerivedData() // Parsing json object { // this will call the respective derived class object. auto derived = static_cast<DerivedT*>(this); // some generic parsing logic for any json object // then call derived objects to set parsed values derived->implementation(); derived->display(); }}; class Derived1 : public Base<Derived1> // jsonMessage1{public: int data1; Derived1() { cout << "Derived1 constr" << endl; } void display() { cout << " data1:" << data1 << endl; } void implementation() { this->data1 = 8900; }}; class Derived2 : public Base<Derived2> // jsonMessage2{public: int data2; Derived2() { cout << "Derived2 constr" << endl; } void display() { cout << " data2:" << data2 << endl; } void implementation() { this->data2 = 898; }}; int main(){ auto obj1 = new Derived1; obj1->accessDerivedData(); auto obj2 = new Derived2; obj2->accessDerivedData();} Questions? Keep them coming. We would love to answer.Reference(s) https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern This article is contributed by Aashish Barnwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 RamsTime gabaa406 Design Pattern Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Command Pattern Strategy Pattern | Set 1 (Introduction) Template Method Design Pattern State Design Pattern Conceptual Model of the Unified Modeling Language (UML) Visitor design pattern Flyweight Design Pattern Difference between Sequence Diagram and Activity Diagram Difference Between Architectural Style, Architectural Patterns and Design Patterns
[ { "code": null, "e": 24247, "s": 24219, "text": "\n20 Sep, 2021" }, { "code": null, "e": 24423, "s": 24247, "text": "Background: It is recommended to refer Virtual Functions and Runtime Polymorphism as a prerequisite of this. Below is an example program to demonstrate run time polymorphism. " }, { "code": null, "e": 24427, "s": 24423, "text": "CPP" }, { "code": "// A simple C++ program to demonstrate run-time// polymorphism#include <chrono>#include <iostream>using namespace std; typedef std::chrono::high_resolution_clock Clock; // To store dimensions of an imageclass Dimension {public: Dimension(int _X, int _Y) { mX = _X; mY = _Y; } private: int mX, mY;}; // Base class for all image typesclass Image {public: virtual void Draw() = 0; virtual Dimension GetDimensionInPixels() = 0; protected: int dimensionX; int dimensionY;}; // For Tiff Imagesclass TiffImage : public Image {public: void Draw() {} Dimension GetDimensionInPixels() { return Dimension(dimensionX, dimensionY); }}; // There can be more derived classes like PngImage,// BitmapImage, etc // Driver code that calls virtual functionint main(){ // An image type Image* pImage = new TiffImage; // Store time before virtual function calls auto then = Clock::now(); // Call Draw 1000 times to make sure performance // is visible for (int i = 0; i < 1000; ++i) pImage->Draw(); // Store time after virtual function calls auto now = Clock::now(); cout << \"Time taken: \" << std::chrono::duration_cast<std::chrono::nanoseconds>(now - then).count() << \" nanoseconds\" << endl; return 0;}", "e": 25726, "s": 24427, "text": null }, { "code": null, "e": 25736, "s": 25726, "text": "Output : " }, { "code": null, "e": 25765, "s": 25736, "text": "Time taken: 2613 nanoseconds" }, { "code": null, "e": 25869, "s": 25765, "text": "See this for above result.When a method is declared virtual, compiler secretly does two things for us: " }, { "code": null, "e": 25990, "s": 25869, "text": "Defines a VPtr in first 4 bytes of the class objectInserts code in constructor to initialize VPtr to point to the VTable" }, { "code": null, "e": 26042, "s": 25990, "text": "Defines a VPtr in first 4 bytes of the class object" }, { "code": null, "e": 26112, "s": 26042, "text": "Inserts code in constructor to initialize VPtr to point to the VTable" }, { "code": null, "e": 26900, "s": 26112, "text": "What are VTable and VPtr? When a method is declared virtual in a class, compiler creates a virtual table (aka VTable) and stores addresses of virtual methods in that table. A virtual pointer (aka VPtr) is then created and initialized to point to that VTable. A VTable is shared across all the instances of the class, i.e. compiler creates only one instance of VTable to be shared across all the objects of a class. Each instance of the class has its own version of VPtr. If we print the size of a class object containing at least one virtual method, the output will be sizeof(class data) + sizeof(VPtr). Since address of virtual method is stored in VTable, VPtr can be manipulated to make calls to those virtual methods thereby violating principles of encapsulation. See below example: " }, { "code": null, "e": 26904, "s": 26900, "text": "CPP" }, { "code": "// A C++ program to demonstrate that we can directly// manipulate VPtr. Note that this program is based// on the assumption that compiler store vPtr in a// specific way to achieve run-time polymorphism.#include <iostream>using namespace std; #pragma pack(1) // A base class with virtual function foo()class CBase {public: virtual void foo() noexcept { cout << \"CBase::Foo() called\" << endl; } protected: int mData;}; // A derived class with its own implementation// of foo()class CDerived : public CBase {public: void foo() noexcept { cout << \"CDerived::Foo() called\" << endl; } private: char cChar;}; // Driver codeint main(){ // A base type pointer pointing to derived CBase* pBase = new CDerived; // Accessing vPtr int* pVPtr = *(int**)pBase; // Calling virtual method ((void (*)())pVPtr[0])(); // Changing vPtr delete pBase; pBase = new CBase; pVPtr = *(int**)pBase; // Calls method for new base object ((void (*)())pVPtr[0])(); return 0;}", "e": 27930, "s": 26904, "text": null }, { "code": null, "e": 27940, "s": 27930, "text": "Output : " }, { "code": null, "e": 27984, "s": 27940, "text": "CDerived::Foo() called\nCBase::Foo() called " }, { "code": null, "e": 29041, "s": 27984, "text": "We are able to access vPtr and able to make calls to virtual methods through it. The memory representation of objects is explained here.Is it wise to use virtual method? As it can be seen, through base class pointer, call to derived class method is being dispatched. Everything seems to be working fine. Then what is the problem? If a virtual routine is called many times (order of hundreds of thousands), it drops the performance of system, reason being each time the routine is called, its address needs to be resolved by looking through VTable using VPtr. Extra indirection (pointer dereference) for each call to a virtual method makes accessing VTable a costly operation and it is better to avoid it as much as we can. Curiously Recurring Template Pattern (CRTP) Usage of VPtr and VTable can be avoided altogether through Curiously Recurring Template Pattern (CRTP). CRTP is a design pattern in C++ in which a class X derives from a class template instantiation using X itself as template argument. More generally it is known as F-bound polymorphism. " }, { "code": null, "e": 29045, "s": 29041, "text": "CPP" }, { "code": "// Image program (similar to above) to demonstrate// working of CRTP#include <chrono>#include <iostream>using namespace std; typedef std::chrono::high_resolution_clock Clock; // To store dimensions of an imageclass Dimension {public: Dimension(int _X, int _Y) { mX = _X; mY = _Y; } private: int mX, mY;}; // Base class for all image types. The template// parameter T is used to know type of derived// class pointed by pointer.template <class T>class Image {public: void Draw() { // Dispatch call to exact type static_cast<T*>(this)->Draw(); } Dimension GetDimensionInPixels() { // Dispatch call to exact type static_cast<T*>(this)->GetDimensionInPixels(); } protected: int dimensionX, dimensionY;}; // For Tiff Imagesclass TiffImage : public Image<TiffImage> {public: void Draw() { // Uncomment this to check method dispatch // cout << \"TiffImage::Draw() called\" << endl; } Dimension GetDimensionInPixels() { return Dimension(dimensionX, dimensionY); }}; // There can be more derived classes like PngImage,// BitmapImage, etc // Driver codeint main(){ // An Image type pointer pointing to Tiffimage Image<TiffImage>* pImage = new TiffImage; // Store time before virtual function calls auto then = Clock::now(); // Call Draw 1000 times to make sure performance // is visible for (int i = 0; i < 1000; ++i) pImage->Draw(); // Store time after virtual function calls auto now = Clock::now(); cout << \"Time taken: \" << std::chrono::duration_cast<std::chrono::nanoseconds>(now - then).count() << \" nanoseconds\" << endl; return 0;}", "e": 30746, "s": 29045, "text": null }, { "code": null, "e": 30755, "s": 30746, "text": "Output :" }, { "code": null, "e": 30783, "s": 30755, "text": "Time taken: 732 nanoseconds" }, { "code": null, "e": 31341, "s": 30783, "text": "See this for above result.Virtual method vs CRTP benchmark The time taken while using virtual method was 2613 nanoseconds. This (small) performance gain from CRTP is because the use of a VTable dispatch has been circumvented. Please note that the performance depends on a lot of factors like compiler used, operations performed by virtual methods. Performance numbers might differ in different runs, but (small) performance gain is expected from CRTP. Note: If we print size of class in CRTP, it can bee seen that VPtr no longer reserves 4 bytes of memory. " }, { "code": null, "e": 31375, "s": 31341, "text": " \ncout << sizeof(Image) << endl; " }, { "code": null, "e": 31522, "s": 31375, "text": "Another use case of CRTP is, when it’s required to access the derived class object in the base class member functions then will have to use CRTP. " }, { "code": null, "e": 31526, "s": 31522, "text": "CPP" }, { "code": "#include <iostream>#include <typeinfo>using namespace std; template <typename DerivedT> class Base {public: int accessDerivedData() // Parsing json object { // this will call the respective derived class object. auto derived = static_cast<DerivedT*>(this); // some generic parsing logic for any json object // then call derived objects to set parsed values derived->implementation(); derived->display(); }}; class Derived1 : public Base<Derived1> // jsonMessage1{public: int data1; Derived1() { cout << \"Derived1 constr\" << endl; } void display() { cout << \" data1:\" << data1 << endl; } void implementation() { this->data1 = 8900; }}; class Derived2 : public Base<Derived2> // jsonMessage2{public: int data2; Derived2() { cout << \"Derived2 constr\" << endl; } void display() { cout << \" data2:\" << data2 << endl; } void implementation() { this->data2 = 898; }}; int main(){ auto obj1 = new Derived1; obj1->accessDerivedData(); auto obj2 = new Derived2; obj2->accessDerivedData();}", "e": 32647, "s": 31526, "text": null }, { "code": null, "e": 33174, "s": 32647, "text": "Questions? Keep them coming. We would love to answer.Reference(s) https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern This article is contributed by Aashish Barnwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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": 33183, "s": 33174, "text": "RamsTime" }, { "code": null, "e": 33192, "s": 33183, "text": "gabaa406" }, { "code": null, "e": 33207, "s": 33192, "text": "Design Pattern" }, { "code": null, "e": 33305, "s": 33207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33314, "s": 33305, "text": "Comments" }, { "code": null, "e": 33327, "s": 33314, "text": "Old Comments" }, { "code": null, "e": 33343, "s": 33327, "text": "Command Pattern" }, { "code": null, "e": 33383, "s": 33343, "text": "Strategy Pattern | Set 1 (Introduction)" }, { "code": null, "e": 33414, "s": 33383, "text": "Template Method Design Pattern" }, { "code": null, "e": 33435, "s": 33414, "text": "State Design Pattern" }, { "code": null, "e": 33491, "s": 33435, "text": "Conceptual Model of the Unified Modeling Language (UML)" }, { "code": null, "e": 33514, "s": 33491, "text": "Visitor design pattern" }, { "code": null, "e": 33539, "s": 33514, "text": "Flyweight Design Pattern" }, { "code": null, "e": 33596, "s": 33539, "text": "Difference between Sequence Diagram and Activity Diagram" } ]
DateTime.AddSeconds() Method in C# - GeeksforGeeks
18 Jan, 2019 This method is used to return a new DateTime that adds the specified number of seconds to the value of this instance. Syntax: public DateTime AddSeconds (double value); Here, value is a number of whole and fractional seconds. The value parameter can be negative or positive. Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and the number of seconds represented by value. Exception: This method will throw ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue. Below programs illustrate the use of the above-discussed method: Example 1: // C# program to demonstrate the// DateTime.AddSeconds(Double) Methodusing System; class GFG { // Main Methodpublic static void Main(){ // defining the format of date string dateFormat = "MM/dd/yyyy hh:mm:ss"; // Creating a DateTime object and // taking a particular date and time DateTime d1 = new DateTime(2018, 9, 7, 7, 0, 0); Console.WriteLine("Original date: {0}", d1.ToString(dateFormat)); // Taking seconds int sec = 30; // using method DateTime d2 = d1.AddSeconds(sec); Console.WriteLine("After Using Method: {0}", d2.ToString(dateFormat));}} Output: Original date: 09/07/2018 07:00:00 After Using Method: 09/07/2018 07:00:30 Example 2: // C# program to demonstrate the// DateTime.AddSeconds(Double) Methodusing System; class GFG { // Main Methodpublic static void Main(){ // defining the format of date string dateFormat = "MM/dd/yyyy hh:mm:ss"; // Creating a DateTime object and // taking a MaxValue of Date DateTime d1 = DateTime.MaxValue; Console.WriteLine("Original date: {0}", d1.ToString(dateFormat)); // Taking seconds int sec = 17; // using method will give error as the // resulting DateTime will be greater // than the MaxValue DateTime d2 = d1.AddSeconds(sec); Console.WriteLine("After Using Method: {0}", d2.ToString(dateFormat));}} Runtime Error: Unhandled Exception:System.ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime.Parameter name: value Note: This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation. The fractional part of the value is the fractional part of a minute. For example, 7.5 is equivalent to 7 minutes, 30 seconds, 0 milliseconds, and 0 ticks. The value parameter is rounded to the nearest millisecond. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.addseconds?view=netframework-4.7.2 CSharp DateTime Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 C# Interview Questions & Answers Extension Method in C# HashSet in C# with Examples Partial Classes in C# C# | Inheritance Convert String to Character Array in C# Linked List Implementation in C# C# | How to insert an element in an Array? C# | List Class Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 23911, "s": 23883, "text": "\n18 Jan, 2019" }, { "code": null, "e": 24029, "s": 23911, "text": "This method is used to return a new DateTime that adds the specified number of seconds to the value of this instance." }, { "code": null, "e": 24037, "s": 24029, "text": "Syntax:" }, { "code": null, "e": 24080, "s": 24037, "text": "public DateTime AddSeconds (double value);" }, { "code": null, "e": 24186, "s": 24080, "text": "Here, value is a number of whole and fractional seconds. The value parameter can be negative or positive." }, { "code": null, "e": 24351, "s": 24186, "text": "Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and the number of seconds represented by value." }, { "code": null, "e": 24487, "s": 24351, "text": "Exception: This method will throw ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue." }, { "code": null, "e": 24552, "s": 24487, "text": "Below programs illustrate the use of the above-discussed method:" }, { "code": null, "e": 24563, "s": 24552, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// DateTime.AddSeconds(Double) Methodusing System; class GFG { // Main Methodpublic static void Main(){ // defining the format of date string dateFormat = \"MM/dd/yyyy hh:mm:ss\"; // Creating a DateTime object and // taking a particular date and time DateTime d1 = new DateTime(2018, 9, 7, 7, 0, 0); Console.WriteLine(\"Original date: {0}\", d1.ToString(dateFormat)); // Taking seconds int sec = 30; // using method DateTime d2 = d1.AddSeconds(sec); Console.WriteLine(\"After Using Method: {0}\", d2.ToString(dateFormat));}}", "e": 25202, "s": 24563, "text": null }, { "code": null, "e": 25210, "s": 25202, "text": "Output:" }, { "code": null, "e": 25286, "s": 25210, "text": "Original date: 09/07/2018 07:00:00\nAfter Using Method: 09/07/2018 07:00:30\n" }, { "code": null, "e": 25297, "s": 25286, "text": "Example 2:" }, { "code": "// C# program to demonstrate the// DateTime.AddSeconds(Double) Methodusing System; class GFG { // Main Methodpublic static void Main(){ // defining the format of date string dateFormat = \"MM/dd/yyyy hh:mm:ss\"; // Creating a DateTime object and // taking a MaxValue of Date DateTime d1 = DateTime.MaxValue; Console.WriteLine(\"Original date: {0}\", d1.ToString(dateFormat)); // Taking seconds int sec = 17; // using method will give error as the // resulting DateTime will be greater // than the MaxValue DateTime d2 = d1.AddSeconds(sec); Console.WriteLine(\"After Using Method: {0}\", d2.ToString(dateFormat));}}", "e": 26003, "s": 25297, "text": null }, { "code": null, "e": 26018, "s": 26003, "text": "Runtime Error:" }, { "code": null, "e": 26166, "s": 26018, "text": "Unhandled Exception:System.ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime.Parameter name: value" }, { "code": null, "e": 26172, "s": 26166, "text": "Note:" }, { "code": null, "e": 26308, "s": 26172, "text": "This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation." }, { "code": null, "e": 26463, "s": 26308, "text": "The fractional part of the value is the fractional part of a minute. For example, 7.5 is equivalent to 7 minutes, 30 seconds, 0 milliseconds, and 0 ticks." }, { "code": null, "e": 26522, "s": 26463, "text": "The value parameter is rounded to the nearest millisecond." }, { "code": null, "e": 26533, "s": 26522, "text": "Reference:" }, { "code": null, "e": 26628, "s": 26533, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.addseconds?view=netframework-4.7.2" }, { "code": null, "e": 26651, "s": 26628, "text": "CSharp DateTime Struct" }, { "code": null, "e": 26665, "s": 26651, "text": "CSharp-method" }, { "code": null, "e": 26668, "s": 26665, "text": "C#" }, { "code": null, "e": 26766, "s": 26668, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26775, "s": 26766, "text": "Comments" }, { "code": null, "e": 26788, "s": 26775, "text": "Old Comments" }, { "code": null, "e": 26828, "s": 26788, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26851, "s": 26828, "text": "Extension Method in C#" }, { "code": null, "e": 26879, "s": 26851, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26901, "s": 26879, "text": "Partial Classes in C#" }, { "code": null, "e": 26918, "s": 26901, "text": "C# | Inheritance" }, { "code": null, "e": 26958, "s": 26918, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 26991, "s": 26958, "text": "Linked List Implementation in C#" }, { "code": null, "e": 27034, "s": 26991, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27050, "s": 27034, "text": "C# | List Class" } ]
Everything You Need to Know About “loc” and “iloc” of Pandas | by Soner Yıldırım | Towards Data Science
Pandas being the most widely used data analysis and manipulation library provides many flexible and convenient functions that ease and expedite data analysis process. In this post, I will cover two important tools which are used to select data from a dataframe based on specified rows and columns. Let’s introduce them first and build up a comprehensive understanding with different kinds of examples. loc: select by labels of rows and columns iloc: select by positions of rows and columns The distinction becomes clear as we go through examples. As always, we start with importing numpy and pandas. import pandas as pdimport numpy as np We will do the examples on telco customer churn dataset available on kaggle. Let’s read the dataset into a pandas dataframe. df = pd.read_csv("Projects/churn_prediction/Telco-Customer-Churn.csv") Dataset includes 21 columns but we can only see the ones that fit to screen. loc is used to select data by label. The labels of columns are the column names. For example, customerID, gender, SeniorCitizen are the first three column names (i.e. labels). We need to be careful about row labels. Since we did not assign any specific indices, pandas created integer index by default. Thus, the row labels are integers starting from 0 and going up. The row positions that are used with iloc are also integers starting from 0. We will see how pandas handle rows differently with loc and iloc with examples. Select row “2” and column “gender” It returns the value in ‘gender’ column of row ‘2’ Select the row labels up to ‘5’ and columns “gender” and “Partner” Select row labels “2”, “4”, “5” and “InternetService” column We can also filter the dataframe and then apply loc or iloc Select row labels to “10” and “InternetService” and “PhoneService” columns of customer with a Partner (Partner == ‘Yes’) We filter the dataframe but do not change the index. Thus, the indices of the resulting dataframe only contain the labels of the rows that are not omitted. Therefore, when use loc[:10], we can select the rows with labels up to “10”. O the other hand, if we use iloc[:10] after applying the filter, we get 10 rows because iloc selects by position regardless of the labels. As you notice, we also need to change the way to select the columns. We also need to pass the positions of columns to iloc. Select the first 5 rows and first 5 columns Select the last 5 rows and last 5 columns. The positions start from 0 from the beginning. If we start the positions from the end, we start with -1 so we use “-5:” to select the last five. We can also apply lambda functions. Select the every third row up to 15th row and show only “Partner” and “InternetService” columns. We can select positions or labels in between. Select the row positions between 20 and 25 , column positions between 4 and 6. If you try to pass labels to iloc, Pandas is kind enough to return an informative feedback as follows: ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types A similar error is returned when we pass positions to loc. I hope the distinction between loc and iloc is crystal clear now. To grasp the knowledge and actually “learn”, I suggest to practice a lot. Just try different examples and you will get used to them in a very short time. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 574, "s": 172, "text": "Pandas being the most widely used data analysis and manipulation library provides many flexible and convenient functions that ease and expedite data analysis process. In this post, I will cover two important tools which are used to select data from a dataframe based on specified rows and columns. Let’s introduce them first and build up a comprehensive understanding with different kinds of examples." }, { "code": null, "e": 616, "s": 574, "text": "loc: select by labels of rows and columns" }, { "code": null, "e": 662, "s": 616, "text": "iloc: select by positions of rows and columns" }, { "code": null, "e": 772, "s": 662, "text": "The distinction becomes clear as we go through examples. As always, we start with importing numpy and pandas." }, { "code": null, "e": 810, "s": 772, "text": "import pandas as pdimport numpy as np" }, { "code": null, "e": 935, "s": 810, "text": "We will do the examples on telco customer churn dataset available on kaggle. Let’s read the dataset into a pandas dataframe." }, { "code": null, "e": 1006, "s": 935, "text": "df = pd.read_csv(\"Projects/churn_prediction/Telco-Customer-Churn.csv\")" }, { "code": null, "e": 1083, "s": 1006, "text": "Dataset includes 21 columns but we can only see the ones that fit to screen." }, { "code": null, "e": 1607, "s": 1083, "text": "loc is used to select data by label. The labels of columns are the column names. For example, customerID, gender, SeniorCitizen are the first three column names (i.e. labels). We need to be careful about row labels. Since we did not assign any specific indices, pandas created integer index by default. Thus, the row labels are integers starting from 0 and going up. The row positions that are used with iloc are also integers starting from 0. We will see how pandas handle rows differently with loc and iloc with examples." }, { "code": null, "e": 1642, "s": 1607, "text": "Select row “2” and column “gender”" }, { "code": null, "e": 1693, "s": 1642, "text": "It returns the value in ‘gender’ column of row ‘2’" }, { "code": null, "e": 1760, "s": 1693, "text": "Select the row labels up to ‘5’ and columns “gender” and “Partner”" }, { "code": null, "e": 1821, "s": 1760, "text": "Select row labels “2”, “4”, “5” and “InternetService” column" }, { "code": null, "e": 1881, "s": 1821, "text": "We can also filter the dataframe and then apply loc or iloc" }, { "code": null, "e": 2002, "s": 1881, "text": "Select row labels to “10” and “InternetService” and “PhoneService” columns of customer with a Partner (Partner == ‘Yes’)" }, { "code": null, "e": 2374, "s": 2002, "text": "We filter the dataframe but do not change the index. Thus, the indices of the resulting dataframe only contain the labels of the rows that are not omitted. Therefore, when use loc[:10], we can select the rows with labels up to “10”. O the other hand, if we use iloc[:10] after applying the filter, we get 10 rows because iloc selects by position regardless of the labels." }, { "code": null, "e": 2498, "s": 2374, "text": "As you notice, we also need to change the way to select the columns. We also need to pass the positions of columns to iloc." }, { "code": null, "e": 2542, "s": 2498, "text": "Select the first 5 rows and first 5 columns" }, { "code": null, "e": 2585, "s": 2542, "text": "Select the last 5 rows and last 5 columns." }, { "code": null, "e": 2730, "s": 2585, "text": "The positions start from 0 from the beginning. If we start the positions from the end, we start with -1 so we use “-5:” to select the last five." }, { "code": null, "e": 2766, "s": 2730, "text": "We can also apply lambda functions." }, { "code": null, "e": 2863, "s": 2766, "text": "Select the every third row up to 15th row and show only “Partner” and “InternetService” columns." }, { "code": null, "e": 2909, "s": 2863, "text": "We can select positions or labels in between." }, { "code": null, "e": 2988, "s": 2909, "text": "Select the row positions between 20 and 25 , column positions between 4 and 6." }, { "code": null, "e": 3091, "s": 2988, "text": "If you try to pass labels to iloc, Pandas is kind enough to return an informative feedback as follows:" }, { "code": null, "e": 3258, "s": 3091, "text": "ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types" }, { "code": null, "e": 3317, "s": 3258, "text": "A similar error is returned when we pass positions to loc." }, { "code": null, "e": 3537, "s": 3317, "text": "I hope the distinction between loc and iloc is crystal clear now. To grasp the knowledge and actually “learn”, I suggest to practice a lot. Just try different examples and you will get used to them in a very short time." } ]
Violin plots explained. Learn how to use violin plots and what... | by Eryk Lewinson | Towards Data Science
In general, violin plots are a method of plotting numeric data and can be considered a combination of the box plot with a kernel density plot. In the violin plot, we can find the same information as in the box plots: median (a white dot on the violin plot) interquartile range (the black bar in the center of violin) the lower/upper adjacent values (the black lines stretched from the bar) — defined as first quartile — 1.5 IQR and third quartile + 1.5 IQR respectively. These values can be used in a simple outlier detection technique (Tukey’s fences) — observations lying outside of these “fences” can be considered outliers. The unquestionable advantage of the violin plot over the box plot is that aside from showing the abovementioned statistics it also shows the entire distribution of the data. This is of interest, especially when dealing with multimodal data, i.e., a distribution with more than one peak. In this article we use the following libraries: seaborn 0.9.0numpy 1.17.2pandas 0.25.1matplotlib 3.1.1 We start by defining the number of random observations we will draw from certain distributions, as well as setting the seed for reproducibility of the results. N = 10 ** 4np.random.seed(42) Then, we define a function plotting the following: a histogram with a kernel density estimate (KDE) a boxplot a violin plot We will use this function for inspecting the randomly created samples. def plot_comparison(x, title): fig, ax = plt.subplots(3, 1, sharex=True) sns.distplot(x, ax=ax[0]) ax[0].set_title('Histogram + KDE') sns.boxplot(x, ax=ax[1]) ax[1].set_title('Boxplot') sns.violinplot(x, ax=ax[2]) ax[2].set_title('Violin plot') fig.suptitle(title, fontsize=16) plt.show() We start with the most basic distribution — Standard Normal. We draw 10000 numbers at random and plot the results. sample_gaussian = np.random.normal(size=N)plot_comparison(sample_gaussian, 'Standard Normal Distribution') Some of the observations we can make: in the histogram we see the symmetric shape of the distribution we can see the previously mentioned metrics (median, IQR, Tukey’s fences) in both the box plot as well as the violin plot the kernel density plot used for creating the violin plot is the same as the one added on top of the histogram. Wider sections of the violin plot represent a higher probability of observations taking a given value, the thinner sections correspond to a lower probability. I believe that showing these three plots together provides good intuition to what a violin plot actually is and what kind of information it contains. In the second example, we consider the log-normal distribution, which is definitely more skewed than the Normal distribution. sample_lognormal = np.random.lognormal(size=N)plot_comparison(sample_lognormal, 'Log-normal Distribution') In the previous two examples, we have already seen that the violin plots contain more information than the box plot. This is even more apparent when we consider a multimodal distribution. In this example, we create a bimodal distribution as a mixture of two Gaussian distributions. Without looking at a histogram/density plot, it would be impossible to spot the two peaks in our data. Violin plots are often used to compare the distribution of a given variable across some categories. We present a few of the possibilities below. To do so, we load the tips dataset from seaborn. tips = sns.load_dataset("tips") In the first example, we look at the distribution of the tips per gender. Additionally, we change the structure of the violin plot to display the quartiles only. Some other possibilities include point for showing all the observations or box for drawing a small box plot inside the violin plot. ax = sns.violinplot(x="sex", y="tip", inner='quartile', data=tips)ax.set_title('Distribution of tips', fontsize=16); We see that the overall shape and distribution of the tips are similar for both genders (quartiles very close to each other), but there are more outliers in the case of males. In the second example, we investigate the distribution of the total bill amount per day. Additionally, we split by gender. Immediately we see that the largest difference in the shape of the distribution between genders happens on Fridays. ax = sns.violinplot(x="day", y="total_bill", hue="sex", data=tips)ax.set_title('Distribution of total bill amount per day', fontsize=16); In the last example, we investigate the same thing as in the previous case, however, we set split=True. By doing so, instead of 8 violins, we end up with four — each side of the violin corresponds to a different gender. ax = sns.violinplot(x="day", y="total_bill", hue="sex", split=True, data=tips)ax.set_title('Distribution of total bill amount per day', fontsize=16); In this article, I showed what are the violin plots, how to interpret them and what are their advantages over the box plots. One last remark worth making is that the box plots do not adapt as long as the quartiles stay the same. We can modify the data in a way that the quartiles do not change, but the shape of the distribution differs dramatically. The following GIF illustrates the point. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments. You can find the code used for this article on my GitHub. Liked the article? Become a Medium member to continue learning by reading without limits. If you use this link to become a member, you will support me at no extra cost to you. Thanks in advance and see you around!
[ { "code": null, "e": 389, "s": 172, "text": "In general, violin plots are a method of plotting numeric data and can be considered a combination of the box plot with a kernel density plot. In the violin plot, we can find the same information as in the box plots:" }, { "code": null, "e": 429, "s": 389, "text": "median (a white dot on the violin plot)" }, { "code": null, "e": 489, "s": 429, "text": "interquartile range (the black bar in the center of violin)" }, { "code": null, "e": 800, "s": 489, "text": "the lower/upper adjacent values (the black lines stretched from the bar) — defined as first quartile — 1.5 IQR and third quartile + 1.5 IQR respectively. These values can be used in a simple outlier detection technique (Tukey’s fences) — observations lying outside of these “fences” can be considered outliers." }, { "code": null, "e": 1087, "s": 800, "text": "The unquestionable advantage of the violin plot over the box plot is that aside from showing the abovementioned statistics it also shows the entire distribution of the data. This is of interest, especially when dealing with multimodal data, i.e., a distribution with more than one peak." }, { "code": null, "e": 1135, "s": 1087, "text": "In this article we use the following libraries:" }, { "code": null, "e": 1202, "s": 1135, "text": "seaborn 0.9.0numpy 1.17.2pandas 0.25.1matplotlib 3.1.1" }, { "code": null, "e": 1362, "s": 1202, "text": "We start by defining the number of random observations we will draw from certain distributions, as well as setting the seed for reproducibility of the results." }, { "code": null, "e": 1392, "s": 1362, "text": "N = 10 ** 4np.random.seed(42)" }, { "code": null, "e": 1443, "s": 1392, "text": "Then, we define a function plotting the following:" }, { "code": null, "e": 1492, "s": 1443, "text": "a histogram with a kernel density estimate (KDE)" }, { "code": null, "e": 1502, "s": 1492, "text": "a boxplot" }, { "code": null, "e": 1516, "s": 1502, "text": "a violin plot" }, { "code": null, "e": 1587, "s": 1516, "text": "We will use this function for inspecting the randomly created samples." }, { "code": null, "e": 1903, "s": 1587, "text": "def plot_comparison(x, title): fig, ax = plt.subplots(3, 1, sharex=True) sns.distplot(x, ax=ax[0]) ax[0].set_title('Histogram + KDE') sns.boxplot(x, ax=ax[1]) ax[1].set_title('Boxplot') sns.violinplot(x, ax=ax[2]) ax[2].set_title('Violin plot') fig.suptitle(title, fontsize=16) plt.show()" }, { "code": null, "e": 2018, "s": 1903, "text": "We start with the most basic distribution — Standard Normal. We draw 10000 numbers at random and plot the results." }, { "code": null, "e": 2125, "s": 2018, "text": "sample_gaussian = np.random.normal(size=N)plot_comparison(sample_gaussian, 'Standard Normal Distribution')" }, { "code": null, "e": 2163, "s": 2125, "text": "Some of the observations we can make:" }, { "code": null, "e": 2227, "s": 2163, "text": "in the histogram we see the symmetric shape of the distribution" }, { "code": null, "e": 2349, "s": 2227, "text": "we can see the previously mentioned metrics (median, IQR, Tukey’s fences) in both the box plot as well as the violin plot" }, { "code": null, "e": 2620, "s": 2349, "text": "the kernel density plot used for creating the violin plot is the same as the one added on top of the histogram. Wider sections of the violin plot represent a higher probability of observations taking a given value, the thinner sections correspond to a lower probability." }, { "code": null, "e": 2770, "s": 2620, "text": "I believe that showing these three plots together provides good intuition to what a violin plot actually is and what kind of information it contains." }, { "code": null, "e": 2896, "s": 2770, "text": "In the second example, we consider the log-normal distribution, which is definitely more skewed than the Normal distribution." }, { "code": null, "e": 3003, "s": 2896, "text": "sample_lognormal = np.random.lognormal(size=N)plot_comparison(sample_lognormal, 'Log-normal Distribution')" }, { "code": null, "e": 3285, "s": 3003, "text": "In the previous two examples, we have already seen that the violin plots contain more information than the box plot. This is even more apparent when we consider a multimodal distribution. In this example, we create a bimodal distribution as a mixture of two Gaussian distributions." }, { "code": null, "e": 3388, "s": 3285, "text": "Without looking at a histogram/density plot, it would be impossible to spot the two peaks in our data." }, { "code": null, "e": 3582, "s": 3388, "text": "Violin plots are often used to compare the distribution of a given variable across some categories. We present a few of the possibilities below. To do so, we load the tips dataset from seaborn." }, { "code": null, "e": 3614, "s": 3582, "text": "tips = sns.load_dataset(\"tips\")" }, { "code": null, "e": 3908, "s": 3614, "text": "In the first example, we look at the distribution of the tips per gender. Additionally, we change the structure of the violin plot to display the quartiles only. Some other possibilities include point for showing all the observations or box for drawing a small box plot inside the violin plot." }, { "code": null, "e": 4025, "s": 3908, "text": "ax = sns.violinplot(x=\"sex\", y=\"tip\", inner='quartile', data=tips)ax.set_title('Distribution of tips', fontsize=16);" }, { "code": null, "e": 4201, "s": 4025, "text": "We see that the overall shape and distribution of the tips are similar for both genders (quartiles very close to each other), but there are more outliers in the case of males." }, { "code": null, "e": 4440, "s": 4201, "text": "In the second example, we investigate the distribution of the total bill amount per day. Additionally, we split by gender. Immediately we see that the largest difference in the shape of the distribution between genders happens on Fridays." }, { "code": null, "e": 4578, "s": 4440, "text": "ax = sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"sex\", data=tips)ax.set_title('Distribution of total bill amount per day', fontsize=16);" }, { "code": null, "e": 4798, "s": 4578, "text": "In the last example, we investigate the same thing as in the previous case, however, we set split=True. By doing so, instead of 8 violins, we end up with four — each side of the violin corresponds to a different gender." }, { "code": null, "e": 4948, "s": 4798, "text": "ax = sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"sex\", split=True, data=tips)ax.set_title('Distribution of total bill amount per day', fontsize=16);" }, { "code": null, "e": 5340, "s": 4948, "text": "In this article, I showed what are the violin plots, how to interpret them and what are their advantages over the box plots. One last remark worth making is that the box plots do not adapt as long as the quartiles stay the same. We can modify the data in a way that the quartiles do not change, but the shape of the distribution differs dramatically. The following GIF illustrates the point." }, { "code": null, "e": 5502, "s": 5340, "text": "As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments. You can find the code used for this article on my GitHub." } ]
NHibernate - Native Sql
In this chapter, we will be covering how to use the native SQL queries in NHibernate. If you have been using handwritten SQL for a number of years, you may be concerned that ORM will take away some of the expressiveness and flexibility you are used to. NHibernate’s powerful query facilities allow you to do almost anything you would in SQL, and in some cases more. NHibernate’s powerful query facilities allow you to do almost anything you would in SQL, and in some cases more. For the rare cases where you can’t make NHibernate’s own query facilities do exactly what you want. For the rare cases where you can’t make NHibernate’s own query facilities do exactly what you want. NHibernate allows you to retrieve objects using your database’s native SQL dialect. NHibernate allows you to retrieve objects using your database’s native SQL dialect. Let’s have a look into a simple example of the Native SQL queries in NHibernate. using System; using System.Data; using System.Linq; using System.Reflection; using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; using NHibernate; namespace NHibernateDemo { internal class Program { private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { IQuery sqlQuery = session.CreateSQLQuery("SELECT * FROM CUSTOMER").AddEntity(typeof(Customer)); var customers = sqlQuery.List<Customer>(); foreach (var customer in customers) { Console.WriteLine(customer); } tx.Commit(); } Console.WriteLine("Press <ENTER> to exit..."); Console.ReadLine(); } private static Configuration ConfigureNHibernate() { NHibernateProfiler.Initialize(); var cfg = new Configuration(); cfg.DataBaseIntegration(x => { x.ConnectionStringName = "default"; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.IsolationLevel = IsolationLevel.RepeatableRead; x.Timeout = 10; x.BatchSize = 10; }); cfg.SessionFactory().GenerateStatistics(); cfg.AddAssembly(Assembly.GetExecutingAssembly()); return cfg; } } } The above example uses CreateSQLQuery() to get back a list of objects, and you will also notice that the root entity type you want the query to return is specified as Customer. Let’s run your application and you will see that all the customers are retrieved from the database. Emerson Prosacco (4ec2a0e0-6bce-11e1-b2cf-6cf049ee52be) Points: 17 HasGoldStatus: False MemberSince: 6/22/2007 12:00:00 AM (Utc) CreditRating: Excellent AverageRating: 0 Orders: Order Id: 4ec2a0e0-6bce-11e1-b2d0-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2d1-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2d2-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2d3-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2d4-6cf049ee52be Kaci Friesen (4ec2a0e0-6bce-11e1-b2d5-6cf049ee52be) Points: 30 HasGoldStatus: True MemberSince: 5/25/2007 12:00:00 AM (Utc) CreditRating: VeryVeryGood AverageRating: 0 Orders: Order Id: 4ec2a0e0-6bce-11e1-b2d6-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2d7-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2d8-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2d9-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2da-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2db-6cf049ee52be Eveline Waters (4ec2a0e0-6bce-11e1-b2dc-6cf049ee52be) Points: 58 HasGoldStatus: False MemberSince: 10/29/2009 12:00:00 AM (Utc) CreditRating: Good AverageRating: 0 Orders: Order Id: 4ec2a0e0-6bce-11e1-b2dd-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2de-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2df-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2e0-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2e2-6cf049ee52be Molly Kuhn (4ec2a0e0-6bce-11e1-b2e3-6cf049ee52be) Points: 73 HasGoldStatus: False MemberSince: 12/16/2007 12:00:00 AM (Utc) CreditRating: VeryGood AverageRating: 0 Orders: Order Id: 4ec2a0e0-6bce-11e1-b2e4-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2e5-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2e6-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2e7-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2e8-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2e9-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2ea-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2eb-6cf049ee52be Order Id: 4ec2a0e0-6bce-11e1-b2ec-6cf049ee52be Here is another way of writing native SQL query as shown below. IList<Customer> customers = session.CreateSQLQuery("SELECT * FROM CUSTOMER") .AddScalar("Id", NHibernateUtil.Guid) .AddScalar("FirstName", NHibernateUtil.String) .AddScalar("LastName", NHibernateUtil.String) .List<Customer>(); As you can see that the above query specified the SQL query string and the columns and types to return. As you can see that the above query specified the SQL query string and the columns and types to return. This will return an IList of Object arrays with scalar values for each column in the Customer table. This will return an IList of Object arrays with scalar values for each column in the Customer table. Only these three columns will be returned, even though the query is using * and could return more than the three listed columns. Only these three columns will be returned, even though the query is using * and could return more than the three listed columns. Let’s have a look into another simple example. IList<Customer> customers = session.CreateSQLQuery("SELECT * FROM CUSTOMER WHERE FirstName = 'Laverne'") .AddEntity(typeof(Customer)) .List<Customer>(); foreach (var customer in customers) { Console.WriteLine(customer); } Let’s run your application again and you will see the following output. Laverne Hegmann (4e97c816-6bce-11e1-b095-6cf049ee52be) Points: 74 HasGoldStatus: True MemberSince: 4/4/2009 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ea14d96-6bce-11e1-b095-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b096-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b097-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b098-6cf049ee52be Press <ENTER> to exit... Similarly, you can specify any type of SQL query to retrieve data from the database. Print Add Notes Bookmark this page
[ { "code": null, "e": 2586, "s": 2333, "text": "In this chapter, we will be covering how to use the native SQL queries in NHibernate. If you have been using handwritten SQL for a number of years, you may be concerned that ORM will take away some of the expressiveness and flexibility you are used to." }, { "code": null, "e": 2699, "s": 2586, "text": "NHibernate’s powerful query facilities allow you to do almost anything you would in SQL, and in some cases more." }, { "code": null, "e": 2812, "s": 2699, "text": "NHibernate’s powerful query facilities allow you to do almost anything you would in SQL, and in some cases more." }, { "code": null, "e": 2912, "s": 2812, "text": "For the rare cases where you can’t make NHibernate’s own query facilities do exactly what you want." }, { "code": null, "e": 3012, "s": 2912, "text": "For the rare cases where you can’t make NHibernate’s own query facilities do exactly what you want." }, { "code": null, "e": 3096, "s": 3012, "text": "NHibernate allows you to retrieve objects using your database’s native SQL dialect." }, { "code": null, "e": 3180, "s": 3096, "text": "NHibernate allows you to retrieve objects using your database’s native SQL dialect." }, { "code": null, "e": 3261, "s": 3180, "text": "Let’s have a look into a simple example of the Native SQL queries in NHibernate." }, { "code": null, "e": 4943, "s": 3261, "text": "using System; \nusing System.Data; \nusing System.Linq; \nusing System.Reflection; \n\nusing HibernatingRhinos.Profiler.Appender.NHibernate; \nusing NHibernate.Cfg; \nusing NHibernate.Criterion; \nusing NHibernate.Dialect; \nusing NHibernate.Driver; \nusing NHibernate.Linq; \nusing NHibernate;\n\nnamespace NHibernateDemo {\n\n internal class Program { \n\t\n private static void Main() { \n\t\t\n var cfg = ConfigureNHibernate(); \n var sessionFactory = cfg.BuildSessionFactory();\n using(var session = sessionFactory.OpenSession()) \n \n using(var tx = session.BeginTransaction()) {\n IQuery sqlQuery = session.CreateSQLQuery(\"SELECT * FROM\n CUSTOMER\").AddEntity(typeof(Customer));\n var customers = sqlQuery.List<Customer>();\n\t\t\t\t\n foreach (var customer in customers) { \n Console.WriteLine(customer); \n } \n\t\t\t\t\n tx.Commit(); \n }\n \n Console.WriteLine(\"Press <ENTER> to exit...\"); \n Console.ReadLine(); \n }\n\t\t\n private static Configuration ConfigureNHibernate() { \n\t\t\n NHibernateProfiler.Initialize(); \n var cfg = new Configuration(); \n \n cfg.DataBaseIntegration(x => { \n x.ConnectionStringName = \"default\"; \n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n x.IsolationLevel = IsolationLevel.RepeatableRead; \n x.Timeout = 10; \n x.BatchSize = 10; \n }); \n \n cfg.SessionFactory().GenerateStatistics();\n cfg.AddAssembly(Assembly.GetExecutingAssembly()); \n return cfg; \n } \n } \n}" }, { "code": null, "e": 5120, "s": 4943, "text": "The above example uses CreateSQLQuery() to get back a list of objects, and you will also notice that the root entity type you want the query to return is specified as Customer." }, { "code": null, "e": 5220, "s": 5120, "text": "Let’s run your application and you will see that all the customers are retrieved from the database." }, { "code": null, "e": 7323, "s": 5220, "text": "Emerson Prosacco (4ec2a0e0-6bce-11e1-b2cf-6cf049ee52be)\n Points: 17\n HasGoldStatus: False\n MemberSince: 6/22/2007 12:00:00 AM (Utc)\n CreditRating: Excellent\n AverageRating: 0\n\n Orders:\n Order Id: 4ec2a0e0-6bce-11e1-b2d0-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2d1-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2d2-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2d3-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2d4-6cf049ee52be\n\nKaci Friesen (4ec2a0e0-6bce-11e1-b2d5-6cf049ee52be)\n Points: 30\n HasGoldStatus: True\n MemberSince: 5/25/2007 12:00:00 AM (Utc)\n CreditRating: VeryVeryGood\n AverageRating: 0\n\n Orders:\n Order Id: 4ec2a0e0-6bce-11e1-b2d6-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2d7-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2d8-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2d9-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2da-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2db-6cf049ee52be\n\nEveline Waters (4ec2a0e0-6bce-11e1-b2dc-6cf049ee52be)\n Points: 58\n HasGoldStatus: False\n MemberSince: 10/29/2009 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 0\n\n Orders:\n Order Id: 4ec2a0e0-6bce-11e1-b2dd-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2de-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2df-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2e0-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2e2-6cf049ee52be\n\nMolly Kuhn (4ec2a0e0-6bce-11e1-b2e3-6cf049ee52be)\n Points: 73\n HasGoldStatus: False\n MemberSince: 12/16/2007 12:00:00 AM (Utc)\n CreditRating: VeryGood\n AverageRating: 0\n\n Orders:\n Order Id: 4ec2a0e0-6bce-11e1-b2e4-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2e5-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2e6-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2e7-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2e8-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2e9-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2ea-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2eb-6cf049ee52be\n Order Id: 4ec2a0e0-6bce-11e1-b2ec-6cf049ee52be\n" }, { "code": null, "e": 7387, "s": 7323, "text": "Here is another way of writing native SQL query as shown below." }, { "code": null, "e": 7625, "s": 7387, "text": "IList<Customer> customers = session.CreateSQLQuery(\"SELECT * FROM CUSTOMER\")\n .AddScalar(\"Id\", NHibernateUtil.Guid) \n .AddScalar(\"FirstName\", NHibernateUtil.String) \n .AddScalar(\"LastName\", NHibernateUtil.String) .List<Customer>();" }, { "code": null, "e": 7729, "s": 7625, "text": "As you can see that the above query specified the SQL query string and the columns and types to return." }, { "code": null, "e": 7833, "s": 7729, "text": "As you can see that the above query specified the SQL query string and the columns and types to return." }, { "code": null, "e": 7934, "s": 7833, "text": "This will return an IList of Object arrays with scalar values for each column in the Customer table." }, { "code": null, "e": 8035, "s": 7934, "text": "This will return an IList of Object arrays with scalar values for each column in the Customer table." }, { "code": null, "e": 8164, "s": 8035, "text": "Only these three columns will be returned, even though the query is using * and could return more than the three listed columns." }, { "code": null, "e": 8293, "s": 8164, "text": "Only these three columns will be returned, even though the query is using * and could return more than the three listed columns." }, { "code": null, "e": 8340, "s": 8293, "text": "Let’s have a look into another simple example." }, { "code": null, "e": 8579, "s": 8340, "text": "IList<Customer> customers = session.CreateSQLQuery(\"SELECT * FROM CUSTOMER WHERE \n FirstName = 'Laverne'\") \n .AddEntity(typeof(Customer)) .List<Customer>(); \n\t\nforeach (var customer in customers) { \n Console.WriteLine(customer); \n}" }, { "code": null, "e": 8651, "s": 8579, "text": "Let’s run your application again and you will see the following output." }, { "code": null, "e": 9084, "s": 8651, "text": "Laverne Hegmann (4e97c816-6bce-11e1-b095-6cf049ee52be)\n Points: 74\n HasGoldStatus: True\n MemberSince: 4/4/2009 12:00:00 AM (Utc)\n CreditRating: Neutral\n AverageRating: 0\n\n Orders:\n Order Id: 4ea14d96-6bce-11e1-b095-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b096-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b097-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b098-6cf049ee52be\n\t\t\nPress <ENTER> to exit...\n" }, { "code": null, "e": 9169, "s": 9084, "text": "Similarly, you can specify any type of SQL query to retrieve data from the database." }, { "code": null, "e": 9176, "s": 9169, "text": " Print" }, { "code": null, "e": 9187, "s": 9176, "text": " Add Notes" } ]
How to Delete Files and Directories in Linux? - GeeksforGeeks
18 May, 2021 Linux comes with several tools that can assist us in removing files. We always need to delete many files and folders based on a set of requirements. To complete our mission quickly, knowing a few basic commands and their variations is beneficial. Use caution when using the commands below, particularly those that use regular expressions or search patterns with the find command. An incorrect expression or pattern will result in the deletion of important data/system files and non-intended files. Often have a current copy of critical data and device files. Use caution when running those commands, particularly if you’re using Sudo or as the superuser (root). Not so well-liked. We may use the unlink command to permanently delete a single file. $ unlink {file-name} The rm command, which facilitates deleting one or more files simultaneously, is a more widely used command for removing files. $ rm {file-name} If the file is write-protected, rm will ask you to validate its deletion; otherwise, it will delete it without prompting. Using the “-i” flag to force rm to prompt for confirmation before removing a file: $ rm -i {file-name} The rm command deletes files without showing any messages. Using the rm command with the -v flag to see what the rm command is currently doing. $ rm -v {file-name} Using the -f flag to remove write-protected files without asking for clarification. $ rm -f {file-name} Bypassing multiple filenames as arguments to rm, you can delete multiple files. $ rm {file-name-1} {file-name-2} {file-name-3} ... {file-name-N} Regular expressions are also supported by rm. If you want to delete all files with the name file-name-*, type: $ rm file-name*.ext Regular expressions may also be used to define different directories. We can use something like to delete three files that fit file-name-1, file-name-2, and file-name-3. $ rm file-name-[123] The rm command with the -d flag can be used to remove an empty directory. $ rm -d {dir-name} Supported options for file deletion can also be combined with deleting the directory with the -d flag. $ rm -idv {dir-name} Using the -r flag to deleting a non-empty directory. $ rm -r {dir-name} If you do not want a prompt before deleting the directory and its contents, use the -rf flag. This will remove everything inside the directory, including the directory itself, without any confirmation. Use caution especially when using as a root. $ rm -rf {dir-name} We can use the locate command with various choices for more complicated specifications. To delete all files in a path specified by {dir-to-search} that follow a pattern {pattern}. $ find {dir-to-search} -type f -name {pattern} -exec rm -f {} \; Example: $ find luv -type f -name "*.txt" -exec rm -f {} \; We may slightly change the above command to delete everything that fits the sequence {pattern}, including directories within {dir-to-search}: $ find {dir-to-search} -name {pattern} -exec rm -rf {} \; Internally, modern implementations of the find command support the delete feature. The -delete flag is used to override the rm instruction, while the –depth flag tells find to process the contents of the directory before the directory itself: $ find {dir-to-search} -type f -name {file-name-pattern} -depth -delete You may use the following command to remove all empty directories within a given path dir-to-search: $ find {dir-to-search} -type d -empty -delete Instead, use the following command to remove all empty files within a given path dir-to-search: $ find {dir-to-search} -type f -empty -delete We can now remove files based on special permissions, such as: $ find {dir-to-search} -name {pattern} -perm {NNN} -delete Consider the following scenario: $ find /var/tmp -name "temp*" -perm 755 -delete Easy (unlink), (rm), and (rmdir) commands are available in Linux, and they can be quickly expanded with regular expressions. For more specialized needs, you should use a variety of techniques such as (find) to accomplish your goals. Aside from the examples in this post, you can configure your quest by using find with any of the available flags. Often run find commands without the rm or -delete flags and examine the output to determine which files or folders may be affected by the execution of a program. Backup setup and procedure are beneficial not just in the event of unintentional deletions, but also in the event of hardware errors and cyber-attacks. How To Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to Install Jupyter Notebook on MacOS? How to Create and Setup Spring Boot Project in Eclipse IDE? Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 26197, "s": 26169, "text": "\n18 May, 2021" }, { "code": null, "e": 26444, "s": 26197, "text": "Linux comes with several tools that can assist us in removing files. We always need to delete many files and folders based on a set of requirements. To complete our mission quickly, knowing a few basic commands and their variations is beneficial." }, { "code": null, "e": 26695, "s": 26444, "text": "Use caution when using the commands below, particularly those that use regular expressions or search patterns with the find command. An incorrect expression or pattern will result in the deletion of important data/system files and non-intended files." }, { "code": null, "e": 26756, "s": 26695, "text": "Often have a current copy of critical data and device files." }, { "code": null, "e": 26859, "s": 26756, "text": "Use caution when running those commands, particularly if you’re using Sudo or as the superuser (root)." }, { "code": null, "e": 26945, "s": 26859, "text": "Not so well-liked. We may use the unlink command to permanently delete a single file." }, { "code": null, "e": 26966, "s": 26945, "text": "$ unlink {file-name}" }, { "code": null, "e": 27093, "s": 26966, "text": "The rm command, which facilitates deleting one or more files simultaneously, is a more widely used command for removing files." }, { "code": null, "e": 27110, "s": 27093, "text": "$ rm {file-name}" }, { "code": null, "e": 27315, "s": 27110, "text": "If the file is write-protected, rm will ask you to validate its deletion; otherwise, it will delete it without prompting. Using the “-i” flag to force rm to prompt for confirmation before removing a file:" }, { "code": null, "e": 27335, "s": 27315, "text": "$ rm -i {file-name}" }, { "code": null, "e": 27479, "s": 27335, "text": "The rm command deletes files without showing any messages. Using the rm command with the -v flag to see what the rm command is currently doing." }, { "code": null, "e": 27499, "s": 27479, "text": "$ rm -v {file-name}" }, { "code": null, "e": 27583, "s": 27499, "text": "Using the -f flag to remove write-protected files without asking for clarification." }, { "code": null, "e": 27603, "s": 27583, "text": "$ rm -f {file-name}" }, { "code": null, "e": 27683, "s": 27603, "text": "Bypassing multiple filenames as arguments to rm, you can delete multiple files." }, { "code": null, "e": 27748, "s": 27683, "text": "$ rm {file-name-1} {file-name-2} {file-name-3} ... {file-name-N}" }, { "code": null, "e": 27859, "s": 27748, "text": "Regular expressions are also supported by rm. If you want to delete all files with the name file-name-*, type:" }, { "code": null, "e": 27879, "s": 27859, "text": "$ rm file-name*.ext" }, { "code": null, "e": 28049, "s": 27879, "text": "Regular expressions may also be used to define different directories. We can use something like to delete three files that fit file-name-1, file-name-2, and file-name-3." }, { "code": null, "e": 28070, "s": 28049, "text": "$ rm file-name-[123]" }, { "code": null, "e": 28144, "s": 28070, "text": "The rm command with the -d flag can be used to remove an empty directory." }, { "code": null, "e": 28163, "s": 28144, "text": "$ rm -d {dir-name}" }, { "code": null, "e": 28266, "s": 28163, "text": "Supported options for file deletion can also be combined with deleting the directory with the -d flag." }, { "code": null, "e": 28287, "s": 28266, "text": "$ rm -idv {dir-name}" }, { "code": null, "e": 28340, "s": 28287, "text": "Using the -r flag to deleting a non-empty directory." }, { "code": null, "e": 28359, "s": 28340, "text": "$ rm -r {dir-name}" }, { "code": null, "e": 28606, "s": 28359, "text": "If you do not want a prompt before deleting the directory and its contents, use the -rf flag. This will remove everything inside the directory, including the directory itself, without any confirmation. Use caution especially when using as a root." }, { "code": null, "e": 28626, "s": 28606, "text": "$ rm -rf {dir-name}" }, { "code": null, "e": 28806, "s": 28626, "text": "We can use the locate command with various choices for more complicated specifications. To delete all files in a path specified by {dir-to-search} that follow a pattern {pattern}." }, { "code": null, "e": 28871, "s": 28806, "text": "$ find {dir-to-search} -type f -name {pattern} -exec rm -f {} \\;" }, { "code": null, "e": 28880, "s": 28871, "text": "Example:" }, { "code": null, "e": 28931, "s": 28880, "text": "$ find luv -type f -name \"*.txt\" -exec rm -f {} \\;" }, { "code": null, "e": 29073, "s": 28931, "text": "We may slightly change the above command to delete everything that fits the sequence {pattern}, including directories within {dir-to-search}:" }, { "code": null, "e": 29131, "s": 29073, "text": "$ find {dir-to-search} -name {pattern} -exec rm -rf {} \\;" }, { "code": null, "e": 29374, "s": 29131, "text": "Internally, modern implementations of the find command support the delete feature. The -delete flag is used to override the rm instruction, while the –depth flag tells find to process the contents of the directory before the directory itself:" }, { "code": null, "e": 29446, "s": 29374, "text": "$ find {dir-to-search} -type f -name {file-name-pattern} -depth -delete" }, { "code": null, "e": 29547, "s": 29446, "text": "You may use the following command to remove all empty directories within a given path dir-to-search:" }, { "code": null, "e": 29593, "s": 29547, "text": "$ find {dir-to-search} -type d -empty -delete" }, { "code": null, "e": 29689, "s": 29593, "text": "Instead, use the following command to remove all empty files within a given path dir-to-search:" }, { "code": null, "e": 29735, "s": 29689, "text": "$ find {dir-to-search} -type f -empty -delete" }, { "code": null, "e": 29798, "s": 29735, "text": "We can now remove files based on special permissions, such as:" }, { "code": null, "e": 29857, "s": 29798, "text": "$ find {dir-to-search} -name {pattern} -perm {NNN} -delete" }, { "code": null, "e": 29890, "s": 29857, "text": "Consider the following scenario:" }, { "code": null, "e": 29938, "s": 29890, "text": "$ find /var/tmp -name \"temp*\" -perm 755 -delete" }, { "code": null, "e": 30285, "s": 29938, "text": "Easy (unlink), (rm), and (rmdir) commands are available in Linux, and they can be quickly expanded with regular expressions. For more specialized needs, you should use a variety of techniques such as (find) to accomplish your goals. Aside from the examples in this post, you can configure your quest by using find with any of the available flags." }, { "code": null, "e": 30599, "s": 30285, "text": "Often run find commands without the rm or -delete flags and examine the output to determine which files or folders may be affected by the execution of a program. Backup setup and procedure are beneficial not just in the event of unintentional deletions, but also in the event of hardware errors and cyber-attacks." }, { "code": null, "e": 30606, "s": 30599, "text": "How To" }, { "code": null, "e": 30617, "s": 30606, "text": "Linux-Unix" }, { "code": null, "e": 30715, "s": 30617, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30749, "s": 30715, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 30807, "s": 30749, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 30856, "s": 30807, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 30898, "s": 30856, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 30958, "s": 30898, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 30998, "s": 30958, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 31038, "s": 30998, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 31065, "s": 31038, "text": "grep command in Unix/Linux" }, { "code": null, "e": 31100, "s": 31065, "text": "cut command in Linux with examples" } ]
Sorting a vector in C++ - GeeksforGeeks
28 Jan, 2022 Prerequisites : std::sort in C++, vector in C++, initialize a vector in C++. CPP // C++ program to sort a vector in non-decreasing// order.#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; sort(v.begin(), v.end()); cout << "Sorted \n"; for (auto x : v) cout << x << " "; return 0;} Sorted 0 1 2 3 4 5 6 7 8 9 How to sort in descending order? sort() takes a third parameter that is used to specify the order in which elements are to be sorted. We can pass “greater()” function to sort in descending order. This function does comparison in a way that puts greater elements before. CPP // C++ program to sort a vector in non-increasing// order.#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; sort(v.begin(), v.end(), greater<int>()); cout << "Sorted \n"; for (auto x : v) cout << x << " "; return 0;} Sorted 9 8 7 6 5 4 3 2 1 0 How to sort in a particular order? We can also write our own comparator function and pass it as a third parameter. The comparator function checks if the statement returned is true or false and returns a bool value which is passed to the sort function. For example, lets say Interval i1 = { 6 , 8 } and Interval i2 = { 1, 9 }. When this is passed to the comparator function, it compares i1.start and i2.start. Since, i1.start (=6) < i2.start (=1), the comparator function returns false. This means that Interval i1 should not be placed before Interval i2. Below is the code for this function. CPP // A C++ program to sort vector using// our own comparator#include <bits/stdc++.h>using namespace std; // An interval has start time and end timestruct Interval { int start, end;}; // Compares two intervals according to starting times.bool compareInterval(Interval i1, Interval i2){ return (i1.start < i2.start);} int main(){ vector<Interval> v { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; // sort the intervals in increasing order of // start time sort(v.begin(), v.end(), compareInterval); cout << "Intervals sorted by start time : \n"; for (auto x : v) cout << "[" << x.start << ", " << x.end << "] "; return 0;} Intervals sorted by start time : [1, 9] [2, 4] [4, 7] [6, 8] How to sort the array in descending order based on some parameter using a comparator function? A comparator function can be passed in such a manner so that the elements in the array get sorted in descending order. C++ // A C++ program to sort vector using// our own comparator#include <bits/stdc++.h>using namespace std; // An interval has start time and end timestruct Interval { int start, end;}; // Compares two intervals according to ending times in descending order.bool compareInterval(Interval i1, Interval i2){ return (i1.end > i2.end);} int main(){ vector<Interval> v { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; // sort the intervals in decreasing order of // end time sort(v.begin(), v.end(), compareInterval); cout << "Intervals sorted by ending time in descending order : \n"; for (auto x : v) cout << "[" << x.start << ", " << x.end << "] "; return 0;} Intervals sorted by ending time in descending order : [1, 9] [6, 8] [4, 7] [2, 4] Related Articles : Sorting a vector of pairs | Set 1 Sorting a vector of pairs | Set 2 gulshankumarar231 souvikm02 ishikamittal117 cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Virtual Function in C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ Object Oriented Programming in C++ Copy Constructor in C++ Substring in C++
[ { "code": null, "e": 25595, "s": 25567, "text": "\n28 Jan, 2022" }, { "code": null, "e": 25673, "s": 25595, "text": "Prerequisites : std::sort in C++, vector in C++, initialize a vector in C++. " }, { "code": null, "e": 25677, "s": 25673, "text": "CPP" }, { "code": "// C++ program to sort a vector in non-decreasing// order.#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; sort(v.begin(), v.end()); cout << \"Sorted \\n\"; for (auto x : v) cout << x << \" \"; return 0;}", "e": 25957, "s": 25677, "text": null }, { "code": null, "e": 25986, "s": 25957, "text": "Sorted \n0 1 2 3 4 5 6 7 8 9 " }, { "code": null, "e": 26257, "s": 25986, "text": "How to sort in descending order? sort() takes a third parameter that is used to specify the order in which elements are to be sorted. We can pass “greater()” function to sort in descending order. This function does comparison in a way that puts greater elements before. " }, { "code": null, "e": 26261, "s": 26257, "text": "CPP" }, { "code": "// C++ program to sort a vector in non-increasing// order.#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; sort(v.begin(), v.end(), greater<int>()); cout << \"Sorted \\n\"; for (auto x : v) cout << x << \" \"; return 0;}", "e": 26557, "s": 26261, "text": null }, { "code": null, "e": 26586, "s": 26557, "text": "Sorted \n9 8 7 6 5 4 3 2 1 0 " }, { "code": null, "e": 26701, "s": 26586, "text": "How to sort in a particular order? We can also write our own comparator function and pass it as a third parameter." }, { "code": null, "e": 26838, "s": 26701, "text": "The comparator function checks if the statement returned is true or false and returns a bool value which is passed to the sort function." }, { "code": null, "e": 27179, "s": 26838, "text": "For example, lets say Interval i1 = { 6 , 8 } and Interval i2 = { 1, 9 }. When this is passed to the comparator function, it compares i1.start and i2.start. Since, i1.start (=6) < i2.start (=1), the comparator function returns false. This means that Interval i1 should not be placed before Interval i2. Below is the code for this function. " }, { "code": null, "e": 27183, "s": 27179, "text": "CPP" }, { "code": "// A C++ program to sort vector using// our own comparator#include <bits/stdc++.h>using namespace std; // An interval has start time and end timestruct Interval { int start, end;}; // Compares two intervals according to starting times.bool compareInterval(Interval i1, Interval i2){ return (i1.start < i2.start);} int main(){ vector<Interval> v { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; // sort the intervals in increasing order of // start time sort(v.begin(), v.end(), compareInterval); cout << \"Intervals sorted by start time : \\n\"; for (auto x : v) cout << \"[\" << x.start << \", \" << x.end << \"] \"; return 0;}", "e": 27835, "s": 27183, "text": null }, { "code": null, "e": 27898, "s": 27835, "text": "Intervals sorted by start time : \n[1, 9] [2, 4] [4, 7] [6, 8] " }, { "code": null, "e": 27993, "s": 27898, "text": "How to sort the array in descending order based on some parameter using a comparator function?" }, { "code": null, "e": 28112, "s": 27993, "text": "A comparator function can be passed in such a manner so that the elements in the array get sorted in descending order." }, { "code": null, "e": 28116, "s": 28112, "text": "C++" }, { "code": "// A C++ program to sort vector using// our own comparator#include <bits/stdc++.h>using namespace std; // An interval has start time and end timestruct Interval { int start, end;}; // Compares two intervals according to ending times in descending order.bool compareInterval(Interval i1, Interval i2){ return (i1.end > i2.end);} int main(){ vector<Interval> v { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; // sort the intervals in decreasing order of // end time sort(v.begin(), v.end(), compareInterval); cout << \"Intervals sorted by ending time in descending order : \\n\"; for (auto x : v) cout << \"[\" << x.start << \", \" << x.end << \"] \"; return 0;}", "e": 28801, "s": 28116, "text": null }, { "code": null, "e": 28885, "s": 28801, "text": "Intervals sorted by ending time in descending order : \n[1, 9] [6, 8] [4, 7] [2, 4] " }, { "code": null, "e": 28973, "s": 28885, "text": "Related Articles : Sorting a vector of pairs | Set 1 Sorting a vector of pairs | Set 2 " }, { "code": null, "e": 28991, "s": 28973, "text": "gulshankumarar231" }, { "code": null, "e": 29001, "s": 28991, "text": "souvikm02" }, { "code": null, "e": 29017, "s": 29001, "text": "ishikamittal117" }, { "code": null, "e": 29028, "s": 29017, "text": "cpp-vector" }, { "code": null, "e": 29032, "s": 29028, "text": "STL" }, { "code": null, "e": 29036, "s": 29032, "text": "C++" }, { "code": null, "e": 29040, "s": 29036, "text": "STL" }, { "code": null, "e": 29044, "s": 29040, "text": "CPP" }, { "code": null, "e": 29142, "s": 29044, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29161, "s": 29142, "text": "Inheritance in C++" }, { "code": null, "e": 29185, "s": 29161, "text": "C++ Classes and Objects" }, { "code": null, "e": 29209, "s": 29185, "text": "Virtual Function in C++" }, { "code": null, "e": 29240, "s": 29209, "text": "Templates in C++ with Examples" }, { "code": null, "e": 29260, "s": 29240, "text": "Constructors in C++" }, { "code": null, "e": 29288, "s": 29260, "text": "Operator Overloading in C++" }, { "code": null, "e": 29316, "s": 29288, "text": "Socket Programming in C/C++" }, { "code": null, "e": 29351, "s": 29316, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 29375, "s": 29351, "text": "Copy Constructor in C++" } ]
Object Oriented Programming in C++ - GeeksforGeeks
28 Apr, 2020 TABLE OF CONTENT: IntroductionClassObjectsEncapsulationAbstractionPolymorphismInheritanceDynamic BindingMessage Passing Introduction Class Objects Encapsulation Abstraction Polymorphism Inheritance Dynamic Binding Message Passing Object-oriented programming – As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function. Characteristics of an Object Oriented Programming language Class: The building block of C++ that leads to Object-Oriented programming is a Class. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object. For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits, mileage are their properties. A Class is a user-defined data-type which has data members and member functions. Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions define the properties and behaviour of the objects in a Class. In the above example of class Car, the data member will be speed limit, mileage etc and member functions can apply brakes, increase speed etc. We can say that a Class in C++ is a blue-print representing a group of objects which shares some common properties and behaviours. Object: An Object is an identifiable entity with some characteristics and behaviour. An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated. class person{ char name[20]; int id;public: void getdetails(){}}; int main(){ person p1; // p1 is a object } Object take up space in memory and have an associated address like a record in pascal or structure or union in C. When a program is executed the objects interact by sending messages to one another. Each object contains data and code to manipulate the data. Objects can interact without having to know details of each other’s data or code, it is sufficient to know the type of message accepted and type of response returned by the objects. Encapsulation: 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 manipulate 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 keeps records of all the data related to finance. Similarly, the sales section handles all the sales-related activities and keeps records of all the sales. Now there may arise a situation when for some reason an official from the 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 the 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 the sales section and the employees that can manipulate them are wrapped under a single name “sales section”. Encapsulation in C++ Encapsulation also leads 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 are hidden from any other section. Abstraction: Data abstraction is one of the most essential and important features of object-oriented programming in C++. Abstraction means displaying only essential information and hiding the details. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation. Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of the car or applying brakes will stop the car but he does not know about how on pressing accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is. Abstraction using Classes: We can implement Abstraction in C++ using classes. The class helps us to group data members and member functions using available access specifiers. A Class can decide which data member will be visible to the outside world and which is not. Abstraction in Header files: One more type of abstraction in C++ can be header files. For example, consider the pow() method present in math.h header file. Whenever we need to calculate the power of a number, we simply call the function pow() present in the math.h header file and pass the numbers as arguments without knowing the underlying algorithm according to which the function is actually calculating the power of numbers. Polymorphism: The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person posses different behaviour in different situations. This is called polymorphism. An operation may exhibit different behaviours in different instances. The behaviour depends upon the types of data used in the operation. C++ supports operator overloading and function overloading. Operator Overloading: The process of making an operator to exhibit different behaviours in different instances is known as operator overloading. Function Overloading: Function overloading is using a single function name to perform different types of tasks.Polymorphism is extensively used in implementing inheritance. Example: Suppose we have to write a function to add some integers, some times there are 2 integers, some times there are 3 integers. We can write the Addition Method with the same name having different parameters, the concerned method will be called according to parameters. Inheritance: The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming. Sub Class: The class that inherits properties from another class is called Sub class or Derived Class. Super Class:The class whose properties are inherited by sub class is called Base Class or Super class. Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. Example: Dog, Cat, Cow can be Derived Class of Animal Base Class. Dynamic Binding: In dynamic binding, the code to be executed in response to function call is decided at runtime. C++ has virtual functions to support this. Message Passing: Objects communicate with one another by sending and receiving information to each other. A message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving object that generates the desired results. Message passing involves specifying the name of the object, the name of the function and the information to be sent. Related Articles: Classes and Objects Inheritance Access Modifiers Abstraction This article is contributed by Vankayala Karunakar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akshit Agarwal 3 CPP-Basics cpp-class cpp-inheritance C++ School Programming 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 Virtual Function in C++ Bitwise Operators in C/C++ Python Dictionary Reverse a string in Java Interfaces in Java Friend class and function in C++ Introduction To PYTHON
[ { "code": null, "e": 28205, "s": 28177, "text": "\n28 Apr, 2020" }, { "code": null, "e": 28223, "s": 28205, "text": "TABLE OF CONTENT:" }, { "code": null, "e": 28325, "s": 28223, "text": "IntroductionClassObjectsEncapsulationAbstractionPolymorphismInheritanceDynamic BindingMessage Passing" }, { "code": null, "e": 28338, "s": 28325, "text": "Introduction" }, { "code": null, "e": 28344, "s": 28338, "text": "Class" }, { "code": null, "e": 28352, "s": 28344, "text": "Objects" }, { "code": null, "e": 28366, "s": 28352, "text": "Encapsulation" }, { "code": null, "e": 28378, "s": 28366, "text": "Abstraction" }, { "code": null, "e": 28391, "s": 28378, "text": "Polymorphism" }, { "code": null, "e": 28403, "s": 28391, "text": "Inheritance" }, { "code": null, "e": 28419, "s": 28403, "text": "Dynamic Binding" }, { "code": null, "e": 28435, "s": 28419, "text": "Message Passing" }, { "code": null, "e": 28806, "s": 28435, "text": "Object-oriented programming – As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function." }, { "code": null, "e": 28865, "s": 28806, "text": "Characteristics of an Object Oriented Programming language" }, { "code": null, "e": 29152, "s": 28865, "text": "Class: The building block of C++ that leads to Object-Oriented programming is a Class. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object." }, { "code": null, "e": 29448, "s": 29152, "text": "For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits, mileage are their properties." }, { "code": null, "e": 29529, "s": 29448, "text": "A Class is a user-defined data-type which has data members and member functions." }, { "code": null, "e": 29755, "s": 29529, "text": "Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions define the properties and behaviour of the objects in a Class." }, { "code": null, "e": 29898, "s": 29755, "text": "In the above example of class Car, the data member will be speed limit, mileage etc and member functions can apply brakes, increase speed etc." }, { "code": null, "e": 30029, "s": 29898, "text": "We can say that a Class in C++ is a blue-print representing a group of objects which shares some common properties and behaviours." }, { "code": null, "e": 30276, "s": 30029, "text": "Object: An Object is an identifiable entity with some characteristics and behaviour. An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated." }, { "code": "class person{ char name[20]; int id;public: void getdetails(){}}; int main(){ person p1; // p1 is a object }", "e": 30397, "s": 30276, "text": null }, { "code": null, "e": 30511, "s": 30397, "text": "Object take up space in memory and have an associated address like a record in pascal or structure or union in C." }, { "code": null, "e": 30595, "s": 30511, "text": "When a program is executed the objects interact by sending messages to one another." }, { "code": null, "e": 30836, "s": 30595, "text": "Each object contains data and code to manipulate the data. Objects can interact without having to know details of each other’s data or code, it is sufficient to know the type of message accepted and type of response returned by the objects." }, { "code": null, "e": 31079, "s": 30836, "text": "Encapsulation: 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 manipulate them." }, { "code": null, "e": 31955, "s": 31079, "text": "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 keeps records of all the data related to finance. Similarly, the sales section handles all the sales-related activities and keeps records of all the sales. Now there may arise a situation when for some reason an official from the 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 the 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 the sales section and the employees that can manipulate them are wrapped under a single name “sales section”." }, { "code": null, "e": 31976, "s": 31955, "text": "Encapsulation in C++" }, { "code": null, "e": 32196, "s": 31976, "text": "Encapsulation also leads 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 are hidden from any other section." }, { "code": null, "e": 32547, "s": 32196, "text": "Abstraction: Data abstraction is one of the most essential and important features of object-oriented programming in C++. Abstraction means displaying only essential information and hiding the details. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation." }, { "code": null, "e": 32955, "s": 32547, "text": "Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of the car or applying brakes will stop the car but he does not know about how on pressing accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is." }, { "code": null, "e": 33222, "s": 32955, "text": "Abstraction using Classes: We can implement Abstraction in C++ using classes. The class helps us to group data members and member functions using available access specifiers. A Class can decide which data member will be visible to the outside world and which is not." }, { "code": null, "e": 33652, "s": 33222, "text": "Abstraction in Header files: One more type of abstraction in C++ can be header files. For example, consider the pow() method present in math.h header file. Whenever we need to calculate the power of a number, we simply call the function pow() present in the math.h header file and pass the numbers as arguments without knowing the underlying algorithm according to which the function is actually calculating the power of numbers." }, { "code": null, "e": 33824, "s": 33652, "text": "Polymorphism: The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form." }, { "code": null, "e": 34050, "s": 33824, "text": "A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person posses different behaviour in different situations. This is called polymorphism." }, { "code": null, "e": 34188, "s": 34050, "text": "An operation may exhibit different behaviours in different instances. The behaviour depends upon the types of data used in the operation." }, { "code": null, "e": 34248, "s": 34188, "text": "C++ supports operator overloading and function overloading." }, { "code": null, "e": 34393, "s": 34248, "text": "Operator Overloading: The process of making an operator to exhibit different behaviours in different instances is known as operator overloading." }, { "code": null, "e": 34566, "s": 34393, "text": "Function Overloading: Function overloading is using a single function name to perform different types of tasks.Polymorphism is extensively used in implementing inheritance." }, { "code": null, "e": 34841, "s": 34566, "text": "Example: Suppose we have to write a function to add some integers, some times there are 2 integers, some times there are 3 integers. We can write the Addition Method with the same name having different parameters, the concerned method will be called according to parameters." }, { "code": null, "e": 35045, "s": 34841, "text": "Inheritance: The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming." }, { "code": null, "e": 35148, "s": 35045, "text": "Sub Class: The class that inherits properties from another class is called Sub class or Derived Class." }, { "code": null, "e": 35251, "s": 35148, "text": "Super Class:The class whose properties are inherited by sub class is called Base Class or Super class." }, { "code": null, "e": 35558, "s": 35251, "text": "Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class." }, { "code": null, "e": 35624, "s": 35558, "text": "Example: Dog, Cat, Cow can be Derived Class of Animal Base Class." }, { "code": null, "e": 35780, "s": 35624, "text": "Dynamic Binding: In dynamic binding, the code to be executed in response to function call is decided at runtime. C++ has virtual functions to support this." }, { "code": null, "e": 36166, "s": 35780, "text": "Message Passing: Objects communicate with one another by sending and receiving information to each other. A message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving object that generates the desired results. Message passing involves specifying the name of the object, the name of the function and the information to be sent." }, { "code": null, "e": 36184, "s": 36166, "text": "Related Articles:" }, { "code": null, "e": 36204, "s": 36184, "text": "Classes and Objects" }, { "code": null, "e": 36216, "s": 36204, "text": "Inheritance" }, { "code": null, "e": 36233, "s": 36216, "text": "Access Modifiers" }, { "code": null, "e": 36245, "s": 36233, "text": "Abstraction" }, { "code": null, "e": 36422, "s": 36245, "text": "This article is contributed by Vankayala Karunakar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 36439, "s": 36422, "text": "Akshit Agarwal 3" }, { "code": null, "e": 36450, "s": 36439, "text": "CPP-Basics" }, { "code": null, "e": 36460, "s": 36450, "text": "cpp-class" }, { "code": null, "e": 36476, "s": 36460, "text": "cpp-inheritance" }, { "code": null, "e": 36480, "s": 36476, "text": "C++" }, { "code": null, "e": 36499, "s": 36480, "text": "School Programming" }, { "code": null, "e": 36503, "s": 36499, "text": "CPP" }, { "code": null, "e": 36601, "s": 36503, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36619, "s": 36601, "text": "Vector in C++ STL" }, { "code": null, "e": 36665, "s": 36619, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 36688, "s": 36665, "text": "std::sort() in C++ STL" }, { "code": null, "e": 36712, "s": 36688, "text": "Virtual Function in C++" }, { "code": null, "e": 36739, "s": 36712, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 36757, "s": 36739, "text": "Python Dictionary" }, { "code": null, "e": 36782, "s": 36757, "text": "Reverse a string in Java" }, { "code": null, "e": 36801, "s": 36782, "text": "Interfaces in Java" }, { "code": null, "e": 36834, "s": 36801, "text": "Friend class and function in C++" } ]
Automation Using Selenium in C# With Example - GeeksforGeeks
22 Oct, 2021 Selenium is an open-source Web UI automation testing suite. It was developed by Jason Huggins in 2004 as an internal tool at Thought Works. It supports automation across different browsers, platforms, and programming languages which includes Java, Python, C#, etc. It can be easily be deployed on Windows, Linux, Solaris, and Macintosh Operating Systems. It also provides the support for different OS (Operating System) for mobile applications like iOS, windows mobile and android.Selenium consists of drivers specific to each language. Selenium Web driver is mostly used with Java and C#. Test scripts can be coded in selenium in any of the supported programming languages and can be run directly in most of the modern web browsers which include Internet Explorer, Mozilla Firefox, Google Chrome, Safari, etc. Selenium WebDriver is set up for C# in which test cases are made for testing. For this first, make a new project in C# in visual studio. For installing and setting up Visual Studio, you can read the article How to Install and Setup Visual Studio for C#?. We make this project with the name Selenium Automation, and make it as a C# application. Proceed the steps as follows:Step 1: First download the Selenium Web Driver. For Downloading the WebDriver go to Tools option then select Nuget Package Manager and then Manage Nuget Packages for Solution. Step 2: In the Search Bar on the top, search for Selenium. Select Selenium.WebDriver and check the Project checkbox, here it will be Selenium Automation and click on Install. Step 3: After that, a dialogue box will open asking to accept the licenses. This will start the installation process and install the selenium WebDriver. Once Visual Studio is finished with the successful installation of the Selenium WebDriver, it will show output in logs After setting up the selenium on C#, its ready for working. In the following steps it is a guide to make the first test case. At the top of your project import two namespaces as following: using OpenQA.Selenium; using OpenQA.Selenium.ChromeDriver; Download the Chrome driver from ChromeWebDriver according to the Chrome browser version. Unzip the file and copy the path of the file into the ‘ChromeDriver’ Constructor in the code written below. Add the following code in your static void Main section to test it. The final code look like: csharp using OpenQA.Selenium;using OpenQA.Selenium.Chrome;using System; namespace Selenium_Automation{ class Program { static void Main(string[] args) { IWebDriver driver = new ChromeDriver("Path to Chrome Driver"); // This will open up the URL driver.Url = "https://www.geeksforgeeks.org/"; } }} Output: After the above procedure run the test case. Note that this code will not execute unless Chrome driver for the Selenium is not downloaded and unzipped on the system. anikakapoor adnanirshad158 Picked Technical Scripter 2019 C# Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# C# | How to insert an element in an Array? Convert String to Character Array in C# Linked List Implementation in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n22 Oct, 2021" }, { "code": null, "e": 26359, "s": 25547, "text": "Selenium is an open-source Web UI automation testing suite. It was developed by Jason Huggins in 2004 as an internal tool at Thought Works. It supports automation across different browsers, platforms, and programming languages which includes Java, Python, C#, etc. It can be easily be deployed on Windows, Linux, Solaris, and Macintosh Operating Systems. It also provides the support for different OS (Operating System) for mobile applications like iOS, windows mobile and android.Selenium consists of drivers specific to each language. Selenium Web driver is mostly used with Java and C#. Test scripts can be coded in selenium in any of the supported programming languages and can be run directly in most of the modern web browsers which include Internet Explorer, Mozilla Firefox, Google Chrome, Safari, etc. " }, { "code": null, "e": 26910, "s": 26359, "text": "Selenium WebDriver is set up for C# in which test cases are made for testing. For this first, make a new project in C# in visual studio. For installing and setting up Visual Studio, you can read the article How to Install and Setup Visual Studio for C#?. We make this project with the name Selenium Automation, and make it as a C# application. Proceed the steps as follows:Step 1: First download the Selenium Web Driver. For Downloading the WebDriver go to Tools option then select Nuget Package Manager and then Manage Nuget Packages for Solution. " }, { "code": null, "e": 27087, "s": 26910, "text": "Step 2: In the Search Bar on the top, search for Selenium. Select Selenium.WebDriver and check the Project checkbox, here it will be Selenium Automation and click on Install. " }, { "code": null, "e": 27241, "s": 27087, "text": "Step 3: After that, a dialogue box will open asking to accept the licenses. This will start the installation process and install the selenium WebDriver. " }, { "code": null, "e": 27363, "s": 27243, "text": "Once Visual Studio is finished with the successful installation of the Selenium WebDriver, it will show output in logs " }, { "code": null, "e": 27553, "s": 27363, "text": "After setting up the selenium on C#, its ready for working. In the following steps it is a guide to make the first test case. At the top of your project import two namespaces as following: " }, { "code": null, "e": 27612, "s": 27553, "text": "using OpenQA.Selenium;\nusing OpenQA.Selenium.ChromeDriver;" }, { "code": null, "e": 27904, "s": 27612, "text": "Download the Chrome driver from ChromeWebDriver according to the Chrome browser version. Unzip the file and copy the path of the file into the ‘ChromeDriver’ Constructor in the code written below. Add the following code in your static void Main section to test it. The final code look like: " }, { "code": null, "e": 27911, "s": 27904, "text": "csharp" }, { "code": "using OpenQA.Selenium;using OpenQA.Selenium.Chrome;using System; namespace Selenium_Automation{ class Program { static void Main(string[] args) { IWebDriver driver = new ChromeDriver(\"Path to Chrome Driver\"); // This will open up the URL driver.Url = \"https://www.geeksforgeeks.org/\"; } }}", "e": 28265, "s": 27911, "text": null }, { "code": null, "e": 28274, "s": 28265, "text": "Output: " }, { "code": null, "e": 28444, "s": 28276, "text": "After the above procedure run the test case. Note that this code will not execute unless Chrome driver for the Selenium is not downloaded and unzipped on the system. " }, { "code": null, "e": 28456, "s": 28444, "text": "anikakapoor" }, { "code": null, "e": 28471, "s": 28456, "text": "adnanirshad158" }, { "code": null, "e": 28478, "s": 28471, "text": "Picked" }, { "code": null, "e": 28502, "s": 28478, "text": "Technical Scripter 2019" }, { "code": null, "e": 28505, "s": 28502, "text": "C#" }, { "code": null, "e": 28524, "s": 28505, "text": "Technical Scripter" }, { "code": null, "e": 28622, "s": 28524, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28645, "s": 28622, "text": "Extension Method in C#" }, { "code": null, "e": 28673, "s": 28645, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28690, "s": 28673, "text": "C# | Inheritance" }, { "code": null, "e": 28712, "s": 28690, "text": "Partial Classes in C#" }, { "code": null, "e": 28741, "s": 28712, "text": "C# | Generics - Introduction" }, { "code": null, "e": 28781, "s": 28741, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28804, "s": 28781, "text": "Switch Statement in C#" }, { "code": null, "e": 28847, "s": 28804, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 28887, "s": 28847, "text": "Convert String to Character Array in C#" } ]
Python program to create a list of tuples from given list having number and its cube in each tuple - GeeksforGeeks
21 Nov, 2018 Given a list of numbers of list, write a Python program to create a list of tuples having first element as the number and second element as the cube of the number. Example: Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] Input: list = [9, 5, 6] Output: [(9, 729), (5, 125), (6, 216)] We can use list comprehension to create a list of tuples. The first element will be simply an element and second element will be cube of that number. Below is the Python implementation: # Python program to create a list of tuples# from given list having number and# its cube in each tuple # creating a listlist1 = [1, 2, 5, 6] # using list comprehension to iterate each# values in list and create a tuple as specifiedres = [(val, pow(val, 3)) for val in list1] # print the resultprint(res) Output: [(1, 1), (2, 8), (5, 125), (6, 216)] Python list-programs Python tuple-programs python-list python-tuple Python Python Programs School Programming python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26303, "s": 26275, "text": "\n21 Nov, 2018" }, { "code": null, "e": 26467, "s": 26303, "text": "Given a list of numbers of list, write a Python program to create a list of tuples having first element as the number and second element as the cube of the number." }, { "code": null, "e": 26476, "s": 26467, "text": "Example:" }, { "code": null, "e": 26598, "s": 26476, "text": "Input: list = [1, 2, 3]\nOutput: [(1, 1), (2, 8), (3, 27)]\n\nInput: list = [9, 5, 6]\nOutput: [(9, 729), (5, 125), (6, 216)]" }, { "code": null, "e": 26748, "s": 26598, "text": "We can use list comprehension to create a list of tuples. The first element will be simply an element and second element will be cube of that number." }, { "code": null, "e": 26784, "s": 26748, "text": "Below is the Python implementation:" }, { "code": "# Python program to create a list of tuples# from given list having number and# its cube in each tuple # creating a listlist1 = [1, 2, 5, 6] # using list comprehension to iterate each# values in list and create a tuple as specifiedres = [(val, pow(val, 3)) for val in list1] # print the resultprint(res)", "e": 27091, "s": 26784, "text": null }, { "code": null, "e": 27099, "s": 27091, "text": "Output:" }, { "code": null, "e": 27136, "s": 27099, "text": "[(1, 1), (2, 8), (5, 125), (6, 216)]" }, { "code": null, "e": 27157, "s": 27136, "text": "Python list-programs" }, { "code": null, "e": 27179, "s": 27157, "text": "Python tuple-programs" }, { "code": null, "e": 27191, "s": 27179, "text": "python-list" }, { "code": null, "e": 27204, "s": 27191, "text": "python-tuple" }, { "code": null, "e": 27211, "s": 27204, "text": "Python" }, { "code": null, "e": 27227, "s": 27211, "text": "Python Programs" }, { "code": null, "e": 27246, "s": 27227, "text": "School Programming" }, { "code": null, "e": 27258, "s": 27246, "text": "python-list" }, { "code": null, "e": 27356, "s": 27258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27374, "s": 27356, "text": "Python Dictionary" }, { "code": null, "e": 27409, "s": 27374, "text": "Read a file line by line in Python" }, { "code": null, "e": 27441, "s": 27409, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27463, "s": 27441, "text": "Enumerate() in Python" }, { "code": null, "e": 27505, "s": 27463, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27548, "s": 27505, "text": "Python program to convert a list to string" }, { "code": null, "e": 27570, "s": 27548, "text": "Defaultdict in Python" }, { "code": null, "e": 27609, "s": 27570, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27655, "s": 27609, "text": "Python | Split string into list of characters" } ]
Button in wxPython - Python - GeeksforGeeks
10 May, 2020 In this article we are going to learn how can we add buttons to a frame in wxPython. This can be done by using using the Button() constructor of wx.Button class. Following styles are supported in this class: wx.BU_LEFT: Left-justifies the label. Windows and GTK+ only. wx.BU_TOP: Aligns the label to the top of the button. Windows and GTK+ only. wx.BU_RIGHT: Right-justifies the bitmap label. Windows and GTK+ only. wx.BU_BOTTOM: Aligns the label to the bottom of the button. Windows and GTK+ only. wx.BU_EXACTFIT: By default, all buttons are made of at least the standard button size, even if their contents is small enough to fit into a smaller size. This is done for consistency as most platforms use buttons of the same size in the native dialogs, but can be overridden by specifying this flag. If it is given, the button will be made just big enough for its contents. Notice that under MSW the button will still have at least the standard height, even with this style, if it has a non-empty label. wx.BU_NOTEXT: Disables the display of the text label in the button even if it has one or its id is one of the standard stock ids with an associated label: without using this style a button which is only supposed to show a bitmap but uses a standard id would display a label too. wx.BORDER_NONE: Creates a button without border. This is currently implemented in MSW, GTK2 and OSX/Cocoa. Syntax : wx.StaticText(self, parent, id=ID_ANY, label=””, pos=DefaultPosition, size=DefaultSize, style=0, validator= DefaultVadator, name=StaticTextNameStr) Parameters : Example #1: # import wxPythondef onButton(event): print( "Button pressed.") app = wx.App()frame = wx.Frame(None, -1, 'win.py')frame.SetDimensions(200, 0, 200, 50) panel = wx.Panel(frame, wx.ID_ANY)button = wx.Button(panel, wx.ID_ANY, 'Test', (10, 10))button.Bind(wx.EVT_BUTTON, onButton) frame.Show()app.MainLoop() Output : Python-gui Python-wxPython Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26083, "s": 26055, "text": "\n10 May, 2020" }, { "code": null, "e": 26245, "s": 26083, "text": "In this article we are going to learn how can we add buttons to a frame in wxPython. This can be done by using using the Button() constructor of wx.Button class." }, { "code": null, "e": 26291, "s": 26245, "text": "Following styles are supported in this class:" }, { "code": null, "e": 26352, "s": 26291, "text": "wx.BU_LEFT: Left-justifies the label. Windows and GTK+ only." }, { "code": null, "e": 26429, "s": 26352, "text": "wx.BU_TOP: Aligns the label to the top of the button. Windows and GTK+ only." }, { "code": null, "e": 26499, "s": 26429, "text": "wx.BU_RIGHT: Right-justifies the bitmap label. Windows and GTK+ only." }, { "code": null, "e": 26582, "s": 26499, "text": "wx.BU_BOTTOM: Aligns the label to the bottom of the button. Windows and GTK+ only." }, { "code": null, "e": 27086, "s": 26582, "text": "wx.BU_EXACTFIT: By default, all buttons are made of at least the standard button size, even if their contents is small enough to fit into a smaller size. This is done for consistency as most platforms use buttons of the same size in the native dialogs, but can be overridden by specifying this flag. If it is given, the button will be made just big enough for its contents. Notice that under MSW the button will still have at least the standard height, even with this style, if it has a non-empty label." }, { "code": null, "e": 27365, "s": 27086, "text": "wx.BU_NOTEXT: Disables the display of the text label in the button even if it has one or its id is one of the standard stock ids with an associated label: without using this style a button which is only supposed to show a bitmap but uses a standard id would display a label too." }, { "code": null, "e": 27472, "s": 27365, "text": "wx.BORDER_NONE: Creates a button without border. This is currently implemented in MSW, GTK2 and OSX/Cocoa." }, { "code": null, "e": 27481, "s": 27472, "text": "Syntax :" }, { "code": null, "e": 27692, "s": 27481, "text": "wx.StaticText(self, parent, id=ID_ANY, label=””, \n pos=DefaultPosition, size=DefaultSize, \n style=0, validator= DefaultVadator, \n name=StaticTextNameStr)\n" }, { "code": null, "e": 27705, "s": 27692, "text": "Parameters :" }, { "code": null, "e": 27717, "s": 27705, "text": "Example #1:" }, { "code": "# import wxPythondef onButton(event): print( \"Button pressed.\") app = wx.App()frame = wx.Frame(None, -1, 'win.py')frame.SetDimensions(200, 0, 200, 50) panel = wx.Panel(frame, wx.ID_ANY)button = wx.Button(panel, wx.ID_ANY, 'Test', (10, 10))button.Bind(wx.EVT_BUTTON, onButton) frame.Show()app.MainLoop()", "e": 28026, "s": 27717, "text": null }, { "code": null, "e": 28035, "s": 28026, "text": "Output :" }, { "code": null, "e": 28046, "s": 28035, "text": "Python-gui" }, { "code": null, "e": 28062, "s": 28046, "text": "Python-wxPython" }, { "code": null, "e": 28069, "s": 28062, "text": "Python" }, { "code": null, "e": 28167, "s": 28069, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28185, "s": 28167, "text": "Python Dictionary" }, { "code": null, "e": 28220, "s": 28185, "text": "Read a file line by line in Python" }, { "code": null, "e": 28252, "s": 28220, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28274, "s": 28252, "text": "Enumerate() in Python" }, { "code": null, "e": 28316, "s": 28274, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28346, "s": 28316, "text": "Iterate over a list in Python" }, { "code": null, "e": 28372, "s": 28346, "text": "Python String | replace()" }, { "code": null, "e": 28401, "s": 28372, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28445, "s": 28401, "text": "Reading and Writing to text files in Python" } ]
Python | Reading contents of PDF using OCR (Optical Character Recognition) - GeeksforGeeks
17 Jan, 2019 Python is widely used for analyzing the data but the data need not be in the required format always. In such cases, we convert that format (like PDF or JPG etc.) to the text format, in order to analyze the data in better way. Python offers many libraries to do this task. There are several ways of doing this, including using libraries like PyPDF2 in Python. The major disadvantage of using these libraries is the encoding scheme. PDF documents can come in a variety of encodings including UTF-8, ASCII, Unicode, etc. So, converting the PDF to text might result in the loss of data due to the encoding scheme. Let’s see how to read all the contents of a PDF file and store it in a text document using OCR. Firstly, we need to convert the pages of the PDF to images and then, use OCR (Optical Character Recognition) to read the content from the image and store it in a text file. Required Installations: pip3 install PIL pip3 install pytesseract pip3 install pdf2image sudo apt-get install tesseract-ocr There are two parts to the program. Part #1 deals with converting the PDF into image files. Each page of the PDF is stored as an image file. The names of the images stored are:PDF page 1 -> page_1.jpgPDF page 2 -> page_2.jpgPDF page 3 -> page_3.jpg....PDF page n -> page_n.jpg Part #2 deals with recognizing text from the image files and storing it into a text file. Here, we process the images and convert it into text. Once we have the text as a string variable, we can do any processing on the text. For example, in many PDFs, when a line is completed, but a particular word cannot be written entirely in the same line, a hyphen (‘-‘) is added, and the word is continued on the next line. For example – This is some sample text but this parti- cular word could not be written in the same line. Now for such words, a fundamental pre-processing is done to convert the hyphen and the new line into a full word. After all the pre-processing is done, this text is stored in a separate text file. To get the input PDF files used in the code, click d.pdf Below is the implementation: # Import librariesfrom PIL import Imageimport pytesseractimport sysfrom pdf2image import convert_from_pathimport os # Path of the pdfPDF_file = "d.pdf" '''Part #1 : Converting PDF to images''' # Store all the pages of the PDF in a variablepages = convert_from_path(PDF_file, 500) # Counter to store images of each page of PDF to imageimage_counter = 1 # Iterate through all the pages stored abovefor page in pages: # Declaring filename for each page of PDF as JPG # For each page, filename will be: # PDF page 1 -> page_1.jpg # PDF page 2 -> page_2.jpg # PDF page 3 -> page_3.jpg # .... # PDF page n -> page_n.jpg filename = "page_"+str(image_counter)+".jpg" # Save the image of the page in system page.save(filename, 'JPEG') # Increment the counter to update filename image_counter = image_counter + 1 '''Part #2 - Recognizing text from the images using OCR''' 3# Variable to get count of total number of pagesfilelimit = image_counter-1 # Creating a text file to write the outputoutfile = "out_text.txt" # Open the file in append mode so that # All contents of all images are added to the same filef = open(outfile, "a") # Iterate from 1 to total number of pagesfor i in range(1, filelimit + 1): # Set filename to recognize text from # Again, these files will be: # page_1.jpg # page_2.jpg # .... # page_n.jpg filename = "page_"+str(i)+".jpg" # Recognize the text as string in image using pytesserct text = str(((pytesseract.image_to_string(Image.open(filename))))) # The recognized text is stored in variable text # Any string processing may be applied on text # Here, basic formatting has been done: # In many PDFs, at line ending, if a word can't # be written fully, a 'hyphen' is added. # The rest of the word is written in the next line # Eg: This is a sample text this word here GeeksF- # orGeeks is half on first line, remaining on next. # To remove this, we replace every '-\n' to ''. text = text.replace('-\n', '') # Finally, write the processed text to the file. f.write(text) # Close the file after writing all the text.f.close() Output: Input PDF file: Output Text file:As we see, the pages of the PDF were converted to images. Then the images were read, and the content was written into a text file. Advantages of this method include: Avoiding text-based conversion because of encoding scheme resulting in loss of data.Even handwritten content in PDF can be recognized due to the usage of OCR.Recognizing only particular pages of the PDF is also possible.Getting the text as a variable so that any amount of required pre-processing can be done. Avoiding text-based conversion because of encoding scheme resulting in loss of data. Even handwritten content in PDF can be recognized due to the usage of OCR. Recognizing only particular pages of the PDF is also possible. Getting the text as a variable so that any amount of required pre-processing can be done. Disadvantages of this method include: Disk storage is used to store the images in the local system. Although these images are tiny in size.Using OCR cannot guarantee 100% accuracy. Given a computer typed PDF document results in very high accuracy.Handwritten PDFs are still recognized, but the accuracy depends on various factors like handwriting, page color, etc. Disk storage is used to store the images in the local system. Although these images are tiny in size. Using OCR cannot guarantee 100% accuracy. Given a computer typed PDF document results in very high accuracy. Handwritten PDFs are still recognized, but the accuracy depends on various factors like handwriting, page color, etc. Image-Processing python-utility Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26179, "s": 26151, "text": "\n17 Jan, 2019" }, { "code": null, "e": 26451, "s": 26179, "text": "Python is widely used for analyzing the data but the data need not be in the required format always. In such cases, we convert that format (like PDF or JPG etc.) to the text format, in order to analyze the data in better way. Python offers many libraries to do this task." }, { "code": null, "e": 26789, "s": 26451, "text": "There are several ways of doing this, including using libraries like PyPDF2 in Python. The major disadvantage of using these libraries is the encoding scheme. PDF documents can come in a variety of encodings including UTF-8, ASCII, Unicode, etc. So, converting the PDF to text might result in the loss of data due to the encoding scheme." }, { "code": null, "e": 26885, "s": 26789, "text": "Let’s see how to read all the contents of a PDF file and store it in a text document using OCR." }, { "code": null, "e": 27058, "s": 26885, "text": "Firstly, we need to convert the pages of the PDF to images and then, use OCR (Optical Character Recognition) to read the content from the image and store it in a text file." }, { "code": null, "e": 27082, "s": 27058, "text": "Required Installations:" }, { "code": null, "e": 27182, "s": 27082, "text": "pip3 install PIL\npip3 install pytesseract\npip3 install pdf2image\nsudo apt-get install tesseract-ocr" }, { "code": null, "e": 27218, "s": 27182, "text": "There are two parts to the program." }, { "code": null, "e": 27459, "s": 27218, "text": "Part #1 deals with converting the PDF into image files. Each page of the PDF is stored as an image file. The names of the images stored are:PDF page 1 -> page_1.jpgPDF page 2 -> page_2.jpgPDF page 3 -> page_3.jpg....PDF page n -> page_n.jpg" }, { "code": null, "e": 27888, "s": 27459, "text": "Part #2 deals with recognizing text from the image files and storing it into a text file. Here, we process the images and convert it into text. Once we have the text as a string variable, we can do any processing on the text. For example, in many PDFs, when a line is completed, but a particular word cannot be written entirely in the same line, a hyphen (‘-‘) is added, and the word is continued on the next line. For example –" }, { "code": null, "e": 27979, "s": 27888, "text": "This is some sample text but this parti-\ncular word could not be written in the same line." }, { "code": null, "e": 28176, "s": 27979, "text": "Now for such words, a fundamental pre-processing is done to convert the hyphen and the new line into a full word. After all the pre-processing is done, this text is stored in a separate text file." }, { "code": null, "e": 28233, "s": 28176, "text": "To get the input PDF files used in the code, click d.pdf" }, { "code": null, "e": 28262, "s": 28233, "text": "Below is the implementation:" }, { "code": "# Import librariesfrom PIL import Imageimport pytesseractimport sysfrom pdf2image import convert_from_pathimport os # Path of the pdfPDF_file = \"d.pdf\" '''Part #1 : Converting PDF to images''' # Store all the pages of the PDF in a variablepages = convert_from_path(PDF_file, 500) # Counter to store images of each page of PDF to imageimage_counter = 1 # Iterate through all the pages stored abovefor page in pages: # Declaring filename for each page of PDF as JPG # For each page, filename will be: # PDF page 1 -> page_1.jpg # PDF page 2 -> page_2.jpg # PDF page 3 -> page_3.jpg # .... # PDF page n -> page_n.jpg filename = \"page_\"+str(image_counter)+\".jpg\" # Save the image of the page in system page.save(filename, 'JPEG') # Increment the counter to update filename image_counter = image_counter + 1 '''Part #2 - Recognizing text from the images using OCR''' 3# Variable to get count of total number of pagesfilelimit = image_counter-1 # Creating a text file to write the outputoutfile = \"out_text.txt\" # Open the file in append mode so that # All contents of all images are added to the same filef = open(outfile, \"a\") # Iterate from 1 to total number of pagesfor i in range(1, filelimit + 1): # Set filename to recognize text from # Again, these files will be: # page_1.jpg # page_2.jpg # .... # page_n.jpg filename = \"page_\"+str(i)+\".jpg\" # Recognize the text as string in image using pytesserct text = str(((pytesseract.image_to_string(Image.open(filename))))) # The recognized text is stored in variable text # Any string processing may be applied on text # Here, basic formatting has been done: # In many PDFs, at line ending, if a word can't # be written fully, a 'hyphen' is added. # The rest of the word is written in the next line # Eg: This is a sample text this word here GeeksF- # orGeeks is half on first line, remaining on next. # To remove this, we replace every '-\\n' to ''. text = text.replace('-\\n', '') # Finally, write the processed text to the file. f.write(text) # Close the file after writing all the text.f.close()", "e": 30447, "s": 28262, "text": null }, { "code": null, "e": 30455, "s": 30447, "text": "Output:" }, { "code": null, "e": 30471, "s": 30455, "text": "Input PDF file:" }, { "code": null, "e": 30619, "s": 30471, "text": "Output Text file:As we see, the pages of the PDF were converted to images. Then the images were read, and the content was written into a text file." }, { "code": null, "e": 30654, "s": 30619, "text": "Advantages of this method include:" }, { "code": null, "e": 30964, "s": 30654, "text": "Avoiding text-based conversion because of encoding scheme resulting in loss of data.Even handwritten content in PDF can be recognized due to the usage of OCR.Recognizing only particular pages of the PDF is also possible.Getting the text as a variable so that any amount of required pre-processing can be done." }, { "code": null, "e": 31049, "s": 30964, "text": "Avoiding text-based conversion because of encoding scheme resulting in loss of data." }, { "code": null, "e": 31124, "s": 31049, "text": "Even handwritten content in PDF can be recognized due to the usage of OCR." }, { "code": null, "e": 31187, "s": 31124, "text": "Recognizing only particular pages of the PDF is also possible." }, { "code": null, "e": 31277, "s": 31187, "text": "Getting the text as a variable so that any amount of required pre-processing can be done." }, { "code": null, "e": 31315, "s": 31277, "text": "Disadvantages of this method include:" }, { "code": null, "e": 31642, "s": 31315, "text": "Disk storage is used to store the images in the local system. Although these images are tiny in size.Using OCR cannot guarantee 100% accuracy. Given a computer typed PDF document results in very high accuracy.Handwritten PDFs are still recognized, but the accuracy depends on various factors like handwriting, page color, etc." }, { "code": null, "e": 31744, "s": 31642, "text": "Disk storage is used to store the images in the local system. Although these images are tiny in size." }, { "code": null, "e": 31853, "s": 31744, "text": "Using OCR cannot guarantee 100% accuracy. Given a computer typed PDF document results in very high accuracy." }, { "code": null, "e": 31971, "s": 31853, "text": "Handwritten PDFs are still recognized, but the accuracy depends on various factors like handwriting, page color, etc." }, { "code": null, "e": 31988, "s": 31971, "text": "Image-Processing" }, { "code": null, "e": 32003, "s": 31988, "text": "python-utility" }, { "code": null, "e": 32010, "s": 32003, "text": "Python" }, { "code": null, "e": 32026, "s": 32010, "text": "Python Programs" }, { "code": null, "e": 32124, "s": 32026, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32142, "s": 32124, "text": "Python Dictionary" }, { "code": null, "e": 32177, "s": 32142, "text": "Read a file line by line in Python" }, { "code": null, "e": 32209, "s": 32177, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32231, "s": 32209, "text": "Enumerate() in Python" }, { "code": null, "e": 32273, "s": 32231, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32316, "s": 32273, "text": "Python program to convert a list to string" }, { "code": null, "e": 32338, "s": 32316, "text": "Defaultdict in Python" }, { "code": null, "e": 32377, "s": 32338, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 32423, "s": 32377, "text": "Python | Split string into list of characters" } ]
matplotlib.pyplot.clabel() in Python - GeeksforGeeks
29 Aug, 2020 Contour plots or Level plots are a way to display a three-dimensional surface on a two-dimensional plane. It graphs as contours as one output variable z and two predictor variables x and y on the y-axis. Often such contours are also known as z-slices.The clabel() method in mathplotlib.pyplot is used add labels to line contours in instances of the classes to support contour plotting. Syntax: matplotlib.pyplot.clabel(CS, levels=None, **kwargs) Parameters: CS: The ContourSet to label. levels: A list of level values, that should be labeled. The list must be a subset of CS.levels. If not given,all levels are labeled. It is an optional argument(default value is None). fontsize: Size in points or relative size e.g., ‘smaller’, ‘x-large’. See Text.set_size for accepted string values. colors: The label colors- If None, the color of each label matches the color of the corresponding contour.If one string color, e.g., colors = ‘r’ or colors = ‘red’, all labels will be plotted in this color.If a tuple of matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified. If None, the color of each label matches the color of the corresponding contour.If one string color, e.g., colors = ‘r’ or colors = ‘red’, all labels will be plotted in this color.If a tuple of matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified. If None, the color of each label matches the color of the corresponding contour. If one string color, e.g., colors = ‘r’ or colors = ‘red’, all labels will be plotted in this color. If a tuple of matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified. Below are some programs to illustrate the use of matplotlib.pyplot.clabel() : Example 1: Create a simple contour plot with labels using default colors. The inline argument to clabel will control whether the labels are draw over the line segments of the contour, removing the lines beneath the label. Python3 # importing the required librariesimport numpy import matplotlib.pyplot # creating the graphdelta = 0.025x = numpy.arange(-3.0, 3.0, delta)y = numpy.arange(-2.0, 2.0, delta)X, Y = numpy.meshgrid(x, y) Z1 = numpy.exp(-X**2 - Y**2)Z2 = numpy.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2 # adding labels to the line contoursfig, ax = matplotlib.pyplot.subplots()CS = ax.contour(X, Y, Z)ax.clabel(CS, inline=1, fontsize=10)ax.set_title('Simplest default with labels') Output: Example 2: Contour labels can be placed manually by providing a list of positions (in data coordinate). See ginput_manual_clabel.py for interactive placement. Python3 # importing the required librariesimport numpy import matplotlib.pyplot # creating the graphdelta = 0.025x = numpy.arange(-3.0, 3.0, delta)y = numpy.arange(-2.0, 2.0, delta)X, Y = numpy.meshgrid(x, y) Z1 = numpy.exp(-X**2 - Y**2)Z2 = numpy.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2 # adding labels to the line contoursfig, ax = matplotlib.pyplot.subplots()CS = ax.contour(X, Y, Z)manual_locations = [(-1, -1.4), (-0.62, -0.7), (-2, 0.5), (1.7, 1.2), (2.0, 1.4), (2.4, 1.7)] ax.clabel(CS, inline=1, fontsize=10, manual=manual_locations)ax.set_title('labels at selected locations') Output: Example 3: You can force all the contours to be the same color. Python3 # importing the required librariesimport numpy import matplotlib.pyplot # creating the graphdelta = 0.025x = numpy.arange(-3.0, 3.0, delta)y = numpy.arange(-2.0, 2.0, delta)X, Y = numpy.meshgrid(x, y) Z1 = numpy.exp(-X**2 - Y**2)Z2 = numpy.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2 # adding labels to the line contoursfig, ax = matplotlib.pyplot.subplots()CS = ax.contour(X, Y, Z, 6, colors='k', ) ax.clabel(CS, fontsize=9, inline=1)ax.set_title('Single color - negative contours dashed') Output: Example 4: You can set negative contours to be solid instead of dashed: Python3 # importing the required librariesimport numpy import matplotlib.pyplot # creating the graphdelta = 0.025x = numpy.arange(-3.0, 3.0, delta)y = numpy.arange(-2.0, 2.0, delta)X, Y = numpy.meshgrid(x, y) Z1 = numpy.exp(-X**2 - Y**2)Z2 = numpy.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2 # adding labels to the line contoursmatplotlib.rcParams['contour.negative_linestyle'] = 'solid'fig, ax = matplotlib.pyplot.subplots()CS = ax.contour(X, Y, Z, 6, colors='k', ) ax.clabel(CS, fontsize=9, inline=1)ax.set_title('Single color - negative contours solid') Output: Example 5: You can manually specify the colors of the contour. Python3 # importing the required librariesimport numpy import matplotlib.pyplot # creating the graphdelta = 0.025x = numpy.arange(-3.0, 3.0, delta)y = numpy.arange(-2.0, 2.0, delta)X, Y = numpy.meshgrid(x, y) Z1 = numpy.exp(-X**2 - Y**2)Z2 = numpy.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2 # adding labels to the line contoursfig, ax = matplotlib.pyplot.subplots()CS = ax.contour(X, Y, Z, 6, linewidths=np.arange(.5, 4, .5), colors=('r', 'green', 'blue', (1, 1, 0), '#afeeee', '0.5') ) ax.clabel(CS, fontsize=9, inline=1)ax.set_title('Crazy lines') Output: Matplotlib Pyplot-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? 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": "\n29 Aug, 2020" }, { "code": null, "e": 25924, "s": 25537, "text": "Contour plots or Level plots are a way to display a three-dimensional surface on a two-dimensional plane. It graphs as contours as one output variable z and two predictor variables x and y on the y-axis. Often such contours are also known as z-slices.The clabel() method in mathplotlib.pyplot is used add labels to line contours in instances of the classes to support contour plotting. " }, { "code": null, "e": 25985, "s": 25924, "text": "Syntax: matplotlib.pyplot.clabel(CS, levels=None, **kwargs)" }, { "code": null, "e": 25998, "s": 25985, "text": "Parameters: " }, { "code": null, "e": 26027, "s": 25998, "text": "CS: The ContourSet to label." }, { "code": null, "e": 26211, "s": 26027, "text": "levels: A list of level values, that should be labeled. The list must be a subset of CS.levels. If not given,all levels are labeled. It is an optional argument(default value is None)." }, { "code": null, "e": 26327, "s": 26211, "text": "fontsize: Size in points or relative size e.g., ‘smaller’, ‘x-large’. See Text.set_size for accepted string values." }, { "code": null, "e": 26673, "s": 26327, "text": "colors: The label colors- If None, the color of each label matches the color of the corresponding contour.If one string color, e.g., colors = ‘r’ or colors = ‘red’, all labels will be plotted in this color.If a tuple of matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified." }, { "code": null, "e": 26993, "s": 26673, "text": "If None, the color of each label matches the color of the corresponding contour.If one string color, e.g., colors = ‘r’ or colors = ‘red’, all labels will be plotted in this color.If a tuple of matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified." }, { "code": null, "e": 27074, "s": 26993, "text": "If None, the color of each label matches the color of the corresponding contour." }, { "code": null, "e": 27175, "s": 27074, "text": "If one string color, e.g., colors = ‘r’ or colors = ‘red’, all labels will be plotted in this color." }, { "code": null, "e": 27315, "s": 27175, "text": "If a tuple of matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified." }, { "code": null, "e": 27393, "s": 27315, "text": "Below are some programs to illustrate the use of matplotlib.pyplot.clabel() :" }, { "code": null, "e": 27618, "s": 27393, "text": " Example 1: Create a simple contour plot with labels using default colors. The inline argument to clabel will control whether the labels are draw over the line segments of the contour, removing the lines beneath the label. " }, { "code": null, "e": 27626, "s": 27618, "text": "Python3" }, { "code": "# importing the required librariesimport numpy import matplotlib.pyplot # creating the graphdelta = 0.025x = numpy.arange(-3.0, 3.0, delta)y = numpy.arange(-2.0, 2.0, delta)X, Y = numpy.meshgrid(x, y) Z1 = numpy.exp(-X**2 - Y**2)Z2 = numpy.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2 # adding labels to the line contoursfig, ax = matplotlib.pyplot.subplots()CS = ax.contour(X, Y, Z)ax.clabel(CS, inline=1, fontsize=10)ax.set_title('Simplest default with labels')", "e": 28096, "s": 27626, "text": null }, { "code": null, "e": 28105, "s": 28096, "text": "Output: " }, { "code": null, "e": 28265, "s": 28105, "text": "Example 2: Contour labels can be placed manually by providing a list of positions (in data coordinate). See ginput_manual_clabel.py for interactive placement. " }, { "code": null, "e": 28273, "s": 28265, "text": "Python3" }, { "code": "# importing the required librariesimport numpy import matplotlib.pyplot # creating the graphdelta = 0.025x = numpy.arange(-3.0, 3.0, delta)y = numpy.arange(-2.0, 2.0, delta)X, Y = numpy.meshgrid(x, y) Z1 = numpy.exp(-X**2 - Y**2)Z2 = numpy.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2 # adding labels to the line contoursfig, ax = matplotlib.pyplot.subplots()CS = ax.contour(X, Y, Z)manual_locations = [(-1, -1.4), (-0.62, -0.7), (-2, 0.5), (1.7, 1.2), (2.0, 1.4), (2.4, 1.7)] ax.clabel(CS, inline=1, fontsize=10, manual=manual_locations)ax.set_title('labels at selected locations')", "e": 28903, "s": 28273, "text": null }, { "code": null, "e": 28912, "s": 28903, "text": "Output: " }, { "code": null, "e": 28978, "s": 28912, "text": "Example 3: You can force all the contours to be the same color. " }, { "code": null, "e": 28986, "s": 28978, "text": "Python3" }, { "code": "# importing the required librariesimport numpy import matplotlib.pyplot # creating the graphdelta = 0.025x = numpy.arange(-3.0, 3.0, delta)y = numpy.arange(-2.0, 2.0, delta)X, Y = numpy.meshgrid(x, y) Z1 = numpy.exp(-X**2 - Y**2)Z2 = numpy.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2 # adding labels to the line contoursfig, ax = matplotlib.pyplot.subplots()CS = ax.contour(X, Y, Z, 6, colors='k', ) ax.clabel(CS, fontsize=9, inline=1)ax.set_title('Single color - negative contours dashed')", "e": 29517, "s": 28986, "text": null }, { "code": null, "e": 29525, "s": 29517, "text": "Output:" }, { "code": null, "e": 29599, "s": 29525, "text": "Example 4: You can set negative contours to be solid instead of dashed: " }, { "code": null, "e": 29607, "s": 29599, "text": "Python3" }, { "code": "# importing the required librariesimport numpy import matplotlib.pyplot # creating the graphdelta = 0.025x = numpy.arange(-3.0, 3.0, delta)y = numpy.arange(-2.0, 2.0, delta)X, Y = numpy.meshgrid(x, y) Z1 = numpy.exp(-X**2 - Y**2)Z2 = numpy.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2 # adding labels to the line contoursmatplotlib.rcParams['contour.negative_linestyle'] = 'solid'fig, ax = matplotlib.pyplot.subplots()CS = ax.contour(X, Y, Z, 6, colors='k', ) ax.clabel(CS, fontsize=9, inline=1)ax.set_title('Single color - negative contours solid')", "e": 30196, "s": 29607, "text": null }, { "code": null, "e": 30204, "s": 30196, "text": "Output:" }, { "code": null, "e": 30268, "s": 30204, "text": "Example 5: You can manually specify the colors of the contour. " }, { "code": null, "e": 30276, "s": 30268, "text": "Python3" }, { "code": "# importing the required librariesimport numpy import matplotlib.pyplot # creating the graphdelta = 0.025x = numpy.arange(-3.0, 3.0, delta)y = numpy.arange(-2.0, 2.0, delta)X, Y = numpy.meshgrid(x, y) Z1 = numpy.exp(-X**2 - Y**2)Z2 = numpy.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2 # adding labels to the line contoursfig, ax = matplotlib.pyplot.subplots()CS = ax.contour(X, Y, Z, 6, linewidths=np.arange(.5, 4, .5), colors=('r', 'green', 'blue', (1, 1, 0), '#afeeee', '0.5') ) ax.clabel(CS, fontsize=9, inline=1)ax.set_title('Crazy lines')", "e": 30899, "s": 30276, "text": null }, { "code": null, "e": 30907, "s": 30899, "text": "Output:" }, { "code": null, "e": 30931, "s": 30907, "text": "Matplotlib Pyplot-class" }, { "code": null, "e": 30949, "s": 30931, "text": "Python-matplotlib" }, { "code": null, "e": 30956, "s": 30949, "text": "Python" }, { "code": null, "e": 31054, "s": 30956, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31086, "s": 31054, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31128, "s": 31086, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31170, "s": 31128, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31197, "s": 31170, "text": "Python Classes and Objects" }, { "code": null, "e": 31253, "s": 31197, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31275, "s": 31253, "text": "Defaultdict in Python" }, { "code": null, "e": 31314, "s": 31275, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31345, "s": 31314, "text": "Python | os.path.join() method" }, { "code": null, "e": 31374, "s": 31345, "text": "Create a directory in Python" } ]
Program to calculate the value of sin(x) and cos(x) using Expansion - GeeksforGeeks
14 Dec, 2021 Given a value of angle, you need to calculate Sin and Cos values corresponding to it. For sin function Examples: Input : 90 Output : 1 C++ Java Python3 C# PHP Javascript // CPP code for implementing sin function#include <iostream>#include <math.h>using namespace std; // Function for calculating sin valuevoid cal_sin(float n){ float accuracy = 0.0001, denominator, sinx, sinval; // Converting degrees to radian n = n * (3.142 / 180.0); float x1 = n; // maps the sum along the series sinx = n; // holds the actual value of sin(n) sinval = sin(n); int i = 1; do { denominator = 2 * i * (2 * i + 1); x1 = -x1 * n * n / denominator; sinx = sinx + x1; i = i + 1; } while (accuracy <= fabs(sinval - sinx)); cout << sinx;} // Main functionint main(){ float n = 90; cal_sin(n); return 0;} import static java.lang.Math.sin; // JAVA code for implementing sin function class GFG { // Function for calculating sin valuestatic void cal_sin(float n){ float accuracy = (float) 0.0001, denominator, sinx, sinval; // Converting degrees to radian n = n * (float)(3.142 / 180.0); float x1 = n; // maps the sum along the series sinx = n; // holds the actual value of sin(n) sinval = (float)sin(n); int i = 1; do { denominator = 2 * i * (2 * i + 1); x1 = -x1 * n * n / denominator; sinx = sinx + x1; i = i + 1; } while (accuracy <= sinval - sinx); System.out.println(sinx);} // Main function public static void main(String[] args) { float n = 90; cal_sin(n); }} # Python3 code for implementing# sin functionimport math; # Function for calculating sin valuedef cal_sin(n): accuracy = 0.0001; # Converting degrees to radian n = n * (3.142 / 180.0); x1 = n; # maps the sum along the series sinx = n; # holds the actual value of sin(n) sinval = math.sin(n); i = 1; while(True): denominator = 2 * i * (2 * i + 1); x1 = -x1 * n * n / denominator; sinx = sinx + x1; i = i + 1; if(accuracy <= abs(sinval - sinx)): break; print(round(sinx)); # Driver Coden = 90;cal_sin(n); # This code is contributed by mits // C# code for implementing sin functionusing System; class GFG{// Function for calculating sin valuestatic void cal_sin(float n){ float accuracy = (float) 0.0001, denominator, sinx, sinval; // Converting degrees to radian n = n * (float)(3.142 / 180.0); float x1 = n; // maps the sum along the series sinx = n; // holds the actual value of sin(n) sinval = (float)Math.Sin(n); int i = 1; do { denominator = 2 * i * (2 * i + 1); x1 = -x1 * n * n / denominator; sinx = sinx + x1; i = i + 1; } while (accuracy <= sinval - sinx); Console.WriteLine(sinx);} // Driver Codestatic public void Main (){ float n = 90; cal_sin(n);}} // This code is contributed by jit_t <?php// PHP code for implementing sin function // Function for calculating sin valuefunction cal_sin($n){ $accuracy = 0.0001; // Converting degrees to radian $n = $n * (3.142 / 180.0); $x1 = $n; // maps the sum along the series $sinx = $n; // holds the actual value of sin(n) $sinval = sin($n); $i = 1; do { $denominator = 2 * $i * (2 * $i + 1); $x1 = -$x1 * $n * $n / $denominator; $sinx = $sinx + $x1; $i = $i + 1; } while ($accuracy <= abs($sinval - $sinx)); echo round($sinx);} // Main function $n = 90; cal_sin($n); // This code is contributed by mits?> <script> // javascript code for implementing sin function // Function for calculating sin value function cal_sin(n) { var accuracy = 0.0001, denominator, sinx, sinval; // Converting degrees to radian n = n * (3.142 / 180.0); var x1 = n; // maps the sum along the series sinx = n; // holds the actual value of sin(n) sinval = Math.sin(n); var i = 1; do { denominator = 2 * i * (2 * i + 1); x1 = -x1 * n * n / denominator; sinx = (sinx + x1); i = i + 1; } while (accuracy <= sinval - sinx); document.write(sinx.toFixed(0)); } // Main function var n = 90; cal_sin(n); // This code is contributed by todaysgaurav </script> Output: 1 For cos function Examples: Input : 30 Output : 0.86602 C++ Java Python3 C# PHP Javascript // CPP code for implementing cos function#include <iostream>#include <math.h>using namespace std; // Function for calculationvoid cal_cos(float n){ float accuracy = 0.0001, x1, denominator, cosx, cosval; // Converting degrees to radian n = n * (3.142 / 180.0); x1 = 1; // maps the sum along the series cosx = x1; // holds the actual value of sin(n) cosval = cos(n); int i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= fabs(cosval - cosx)); cout << cosx;} // Main functionint main(){ float n = 30; cal_cos(n);} // Java code for implementing cos function import static java.lang.Math.cos; class GFG {// Function for calculation static void cal_cos(float n) { float accuracy = (float) 0.0001, x1, denominator, cosx, cosval; // Converting degrees to radian n = n * (float) (3.142 / 180.0); x1 = 1; // maps the sum along the series cosx = x1; // holds the actual value of sin(n) cosval = (float) cos(n); int i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= cosval - cosx); System.out.println(cosx); } // Main functionpublic static void main(String[] args) { float n = 30; cal_cos(n); }} # Python 3 code for implementing cos function from math import fabs, cos # Function for calculationdef cal_cos(n): accuracy = 0.0001 # Converting degrees to radian n = n * (3.142 / 180.0) x1 = 1 # maps the sum along the series cosx = x1 # holds the actual value of sin(n) cosval = cos(n) i = 1 denominator = 2 * i * (2 * i - 1) x1 = -x1 * n * n / denominator cosx = cosx + x1 i = i + 1 while (accuracy <= fabs(cosval - cosx)): denominator = 2 * i * (2 * i - 1) x1 = -x1 * n * n / denominator cosx = cosx + x1 i = i + 1 print('{0:.6}'.format(cosx)) # Driver Codeif __name__ == '__main__': n = 30 cal_cos(n) # This code is contributed by# Sahil_Shelangia // C# code for implementing cos function using System;class GFG {// Function for calculation static void cal_cos(float n) { float accuracy = (float) 0.0001, x1, denominator, cosx, cosval; // Converting degrees to radian n = n * (float) (3.142 / 180.0); x1 = 1; // maps the sum along the series cosx = x1; // holds the actual value of sin(n) cosval = (float) Math.Cos(n); int i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= cosval - cosx); Console.WriteLine(cosx); } // Main functionstatic void Main() { float n = 30; cal_cos(n); }}// This code is contributed by mits <?php// PHP code for implementing cos function // Function for calculationfunction cal_cos($n){ $accuracy = 0.0001; // Converting degrees to radian $n = $n * (3.142 / 180.0); $x1 = 1; // maps the sum along the series $cosx = $x1; // holds the actual value of sin(n) $cosval = cos($n); $i = 1; do { $denominator = 2 * $i * (2 * $i - 1); $x1 = -$x1 * $n * $n / $denominator; $cosx = $cosx + $x1; $i = $i + 1; } while ($accuracy <= abs($cosval - $cosx)); echo round($cosx, 6);} // Driver Code$n = 30;cal_cos($n); // This code is contributed by mits?> <script> // JavaScript code for implementing cos function // Function for calculationfunction cal_cos(n){ let accuracy = 0.0001, x1, denominator, cosx, cosval; // Converting degrees to radian n = n * (3.142 / 180.0); x1 = 1; // maps the sum along the series cosx = x1; // holds the actual value of sin(n) cosval = Math.cos(n); let i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= Math.abs(cosval - cosx)); document.write(cosx.toFixed(5));} // Main function let n = 30; cal_cos(n); // This code is contributed by Surbhi Tyagi. </script> Output: 0.86602 This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) 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. 29AjayKumar jit_t Mithun Kumar sahilshelangia todaysgaurav surbhityagi15 arorakashish0911 Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n The Knight's tour problem | Backtracking-1 Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26033, "s": 26005, "text": "\n14 Dec, 2021" }, { "code": null, "e": 26119, "s": 26033, "text": "Given a value of angle, you need to calculate Sin and Cos values corresponding to it." }, { "code": null, "e": 26136, "s": 26119, "text": "For sin function" }, { "code": null, "e": 26148, "s": 26136, "text": "Examples: " }, { "code": null, "e": 26170, "s": 26148, "text": "Input : 90\nOutput : 1" }, { "code": null, "e": 26174, "s": 26170, "text": "C++" }, { "code": null, "e": 26179, "s": 26174, "text": "Java" }, { "code": null, "e": 26187, "s": 26179, "text": "Python3" }, { "code": null, "e": 26190, "s": 26187, "text": "C#" }, { "code": null, "e": 26194, "s": 26190, "text": "PHP" }, { "code": null, "e": 26205, "s": 26194, "text": "Javascript" }, { "code": "// CPP code for implementing sin function#include <iostream>#include <math.h>using namespace std; // Function for calculating sin valuevoid cal_sin(float n){ float accuracy = 0.0001, denominator, sinx, sinval; // Converting degrees to radian n = n * (3.142 / 180.0); float x1 = n; // maps the sum along the series sinx = n; // holds the actual value of sin(n) sinval = sin(n); int i = 1; do { denominator = 2 * i * (2 * i + 1); x1 = -x1 * n * n / denominator; sinx = sinx + x1; i = i + 1; } while (accuracy <= fabs(sinval - sinx)); cout << sinx;} // Main functionint main(){ float n = 90; cal_sin(n); return 0;}", "e": 26923, "s": 26205, "text": null }, { "code": "import static java.lang.Math.sin; // JAVA code for implementing sin function class GFG { // Function for calculating sin valuestatic void cal_sin(float n){ float accuracy = (float) 0.0001, denominator, sinx, sinval; // Converting degrees to radian n = n * (float)(3.142 / 180.0); float x1 = n; // maps the sum along the series sinx = n; // holds the actual value of sin(n) sinval = (float)sin(n); int i = 1; do { denominator = 2 * i * (2 * i + 1); x1 = -x1 * n * n / denominator; sinx = sinx + x1; i = i + 1; } while (accuracy <= sinval - sinx); System.out.println(sinx);} // Main function public static void main(String[] args) { float n = 90; cal_sin(n); }}", "e": 27708, "s": 26923, "text": null }, { "code": "# Python3 code for implementing# sin functionimport math; # Function for calculating sin valuedef cal_sin(n): accuracy = 0.0001; # Converting degrees to radian n = n * (3.142 / 180.0); x1 = n; # maps the sum along the series sinx = n; # holds the actual value of sin(n) sinval = math.sin(n); i = 1; while(True): denominator = 2 * i * (2 * i + 1); x1 = -x1 * n * n / denominator; sinx = sinx + x1; i = i + 1; if(accuracy <= abs(sinval - sinx)): break; print(round(sinx)); # Driver Coden = 90;cal_sin(n); # This code is contributed by mits", "e": 28368, "s": 27708, "text": null }, { "code": "// C# code for implementing sin functionusing System; class GFG{// Function for calculating sin valuestatic void cal_sin(float n){ float accuracy = (float) 0.0001, denominator, sinx, sinval; // Converting degrees to radian n = n * (float)(3.142 / 180.0); float x1 = n; // maps the sum along the series sinx = n; // holds the actual value of sin(n) sinval = (float)Math.Sin(n); int i = 1; do { denominator = 2 * i * (2 * i + 1); x1 = -x1 * n * n / denominator; sinx = sinx + x1; i = i + 1; } while (accuracy <= sinval - sinx); Console.WriteLine(sinx);} // Driver Codestatic public void Main (){ float n = 90; cal_sin(n);}} // This code is contributed by jit_t", "e": 29150, "s": 28368, "text": null }, { "code": "<?php// PHP code for implementing sin function // Function for calculating sin valuefunction cal_sin($n){ $accuracy = 0.0001; // Converting degrees to radian $n = $n * (3.142 / 180.0); $x1 = $n; // maps the sum along the series $sinx = $n; // holds the actual value of sin(n) $sinval = sin($n); $i = 1; do { $denominator = 2 * $i * (2 * $i + 1); $x1 = -$x1 * $n * $n / $denominator; $sinx = $sinx + $x1; $i = $i + 1; } while ($accuracy <= abs($sinval - $sinx)); echo round($sinx);} // Main function $n = 90; cal_sin($n); // This code is contributed by mits?>", "e": 29811, "s": 29150, "text": null }, { "code": "<script> // javascript code for implementing sin function // Function for calculating sin value function cal_sin(n) { var accuracy = 0.0001, denominator, sinx, sinval; // Converting degrees to radian n = n * (3.142 / 180.0); var x1 = n; // maps the sum along the series sinx = n; // holds the actual value of sin(n) sinval = Math.sin(n); var i = 1; do { denominator = 2 * i * (2 * i + 1); x1 = -x1 * n * n / denominator; sinx = (sinx + x1); i = i + 1; } while (accuracy <= sinval - sinx); document.write(sinx.toFixed(0)); } // Main function var n = 90; cal_sin(n); // This code is contributed by todaysgaurav </script>", "e": 30600, "s": 29811, "text": null }, { "code": null, "e": 30609, "s": 30600, "text": "Output: " }, { "code": null, "e": 30611, "s": 30609, "text": "1" }, { "code": null, "e": 30628, "s": 30611, "text": "For cos function" }, { "code": null, "e": 30640, "s": 30628, "text": "Examples: " }, { "code": null, "e": 30668, "s": 30640, "text": "Input : 30\nOutput : 0.86602" }, { "code": null, "e": 30672, "s": 30668, "text": "C++" }, { "code": null, "e": 30677, "s": 30672, "text": "Java" }, { "code": null, "e": 30685, "s": 30677, "text": "Python3" }, { "code": null, "e": 30688, "s": 30685, "text": "C#" }, { "code": null, "e": 30692, "s": 30688, "text": "PHP" }, { "code": null, "e": 30703, "s": 30692, "text": "Javascript" }, { "code": "// CPP code for implementing cos function#include <iostream>#include <math.h>using namespace std; // Function for calculationvoid cal_cos(float n){ float accuracy = 0.0001, x1, denominator, cosx, cosval; // Converting degrees to radian n = n * (3.142 / 180.0); x1 = 1; // maps the sum along the series cosx = x1; // holds the actual value of sin(n) cosval = cos(n); int i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= fabs(cosval - cosx)); cout << cosx;} // Main functionint main(){ float n = 30; cal_cos(n);}", "e": 31395, "s": 30703, "text": null }, { "code": "// Java code for implementing cos function import static java.lang.Math.cos; class GFG {// Function for calculation static void cal_cos(float n) { float accuracy = (float) 0.0001, x1, denominator, cosx, cosval; // Converting degrees to radian n = n * (float) (3.142 / 180.0); x1 = 1; // maps the sum along the series cosx = x1; // holds the actual value of sin(n) cosval = (float) cos(n); int i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= cosval - cosx); System.out.println(cosx); } // Main functionpublic static void main(String[] args) { float n = 30; cal_cos(n); }}", "e": 32137, "s": 31395, "text": null }, { "code": "# Python 3 code for implementing cos function from math import fabs, cos # Function for calculationdef cal_cos(n): accuracy = 0.0001 # Converting degrees to radian n = n * (3.142 / 180.0) x1 = 1 # maps the sum along the series cosx = x1 # holds the actual value of sin(n) cosval = cos(n) i = 1 denominator = 2 * i * (2 * i - 1) x1 = -x1 * n * n / denominator cosx = cosx + x1 i = i + 1 while (accuracy <= fabs(cosval - cosx)): denominator = 2 * i * (2 * i - 1) x1 = -x1 * n * n / denominator cosx = cosx + x1 i = i + 1 print('{0:.6}'.format(cosx)) # Driver Codeif __name__ == '__main__': n = 30 cal_cos(n) # This code is contributed by# Sahil_Shelangia", "e": 32887, "s": 32137, "text": null }, { "code": "// C# code for implementing cos function using System;class GFG {// Function for calculation static void cal_cos(float n) { float accuracy = (float) 0.0001, x1, denominator, cosx, cosval; // Converting degrees to radian n = n * (float) (3.142 / 180.0); x1 = 1; // maps the sum along the series cosx = x1; // holds the actual value of sin(n) cosval = (float) Math.Cos(n); int i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= cosval - cosx); Console.WriteLine(cosx); } // Main functionstatic void Main() { float n = 30; cal_cos(n); }}// This code is contributed by mits", "e": 33625, "s": 32887, "text": null }, { "code": "<?php// PHP code for implementing cos function // Function for calculationfunction cal_cos($n){ $accuracy = 0.0001; // Converting degrees to radian $n = $n * (3.142 / 180.0); $x1 = 1; // maps the sum along the series $cosx = $x1; // holds the actual value of sin(n) $cosval = cos($n); $i = 1; do { $denominator = 2 * $i * (2 * $i - 1); $x1 = -$x1 * $n * $n / $denominator; $cosx = $cosx + $x1; $i = $i + 1; } while ($accuracy <= abs($cosval - $cosx)); echo round($cosx, 6);} // Driver Code$n = 30;cal_cos($n); // This code is contributed by mits?>", "e": 34268, "s": 33625, "text": null }, { "code": "<script> // JavaScript code for implementing cos function // Function for calculationfunction cal_cos(n){ let accuracy = 0.0001, x1, denominator, cosx, cosval; // Converting degrees to radian n = n * (3.142 / 180.0); x1 = 1; // maps the sum along the series cosx = x1; // holds the actual value of sin(n) cosval = Math.cos(n); let i = 1; do { denominator = 2 * i * (2 * i - 1); x1 = -x1 * n * n / denominator; cosx = cosx + x1; i = i + 1; } while (accuracy <= Math.abs(cosval - cosx)); document.write(cosx.toFixed(5));} // Main function let n = 30; cal_cos(n); // This code is contributed by Surbhi Tyagi. </script>", "e": 34985, "s": 34268, "text": null }, { "code": null, "e": 34994, "s": 34985, "text": "Output: " }, { "code": null, "e": 35002, "s": 34994, "text": "0.86602" }, { "code": null, "e": 35441, "s": 35002, "text": "This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) 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": 35453, "s": 35441, "text": "29AjayKumar" }, { "code": null, "e": 35459, "s": 35453, "text": "jit_t" }, { "code": null, "e": 35472, "s": 35459, "text": "Mithun Kumar" }, { "code": null, "e": 35487, "s": 35472, "text": "sahilshelangia" }, { "code": null, "e": 35500, "s": 35487, "text": "todaysgaurav" }, { "code": null, "e": 35514, "s": 35500, "text": "surbhityagi15" }, { "code": null, "e": 35531, "s": 35514, "text": "arorakashish0911" }, { "code": null, "e": 35544, "s": 35531, "text": "Mathematical" }, { "code": null, "e": 35563, "s": 35544, "text": "School Programming" }, { "code": null, "e": 35576, "s": 35563, "text": "Mathematical" }, { "code": null, "e": 35674, "s": 35576, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35698, "s": 35674, "text": "Merge two sorted arrays" }, { "code": null, "e": 35741, "s": 35698, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 35755, "s": 35741, "text": "Prime Numbers" }, { "code": null, "e": 35828, "s": 35755, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 35871, "s": 35828, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 35889, "s": 35871, "text": "Python Dictionary" }, { "code": null, "e": 35905, "s": 35889, "text": "Arrays in C/C++" }, { "code": null, "e": 35924, "s": 35905, "text": "Inheritance in C++" }, { "code": null, "e": 35949, "s": 35924, "text": "Reverse a string in Java" } ]
Difference between npm install and npm update in Node.js - GeeksforGeeks
25 Jan, 2021 NPM is like a powerhouse for Node.js that contains all the necessary modules for the smooth running of the node.js application. It gets installed on our machine when we install Node.js on our Windows, Linux or MAC OS. How to install Node on the machine? Refer to this article. NPM has 580096 registered packages. The average rate of growth of this number is 291/day that means the growth of different kind of packages increasing drastically, so we have to update our node every time on our machine ? The answer is No! NPM allows us to install third-party modules on our machine according to the need of our work. Another reason is predefined modules cannot be able to fulfill the need for big projects for e.g. HTTP modules cannot differentiate the multiple kinds of requests, so we have to install externally another popular module. i.e express module. We can access third party modules using some predefined commands provided by Node Package Manager are given below: Initial Project Structure : npm install command: This npm command is used for installing the third party modules in our current directory. There are two different ways to use this command: Without ParameterWith Parameter Without Parameter With Parameter Without Parameter: When we use the npm command without a parameter this command automatically downloads all the dependencies that are written in the package.json file in our directory. Package.json: create a package.json file in the directory and mention express dependencies in this file. { "name": "gfg", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "express": "^4.17.1" } } Run npm install command: npm i or npm install Updated Project Structure: package-lock.json file and node_modules created package-lock.json file contains all the necessary information of downloaded extra dependencies and node_modules folder contains all the different types of packages that installed along with our specified module in the package.json. With Parameter: We can use the npm install command by specifying the name of the third-party module that we want to install for particular work. For e.g. let’s download MongoDB module for Node.js Parameter: Parameter can be the name of the module that we want to install or folder name in which we want to install all third-party modules in the directory. By default, the folder is node_modules that contains all the installed modules. This folder is automatically generated when we install any external module the first time. Syntax: npm install [-g] [<package>..] Syntax for installing module: Module will get install in the node_modules folder in the present directory. npm install <module-name> Syntax for installing any module globally: Globally installing means we can access the module without installing that module in a particular directory. For eg Nodemon module etc. npm install -g <module-name> Syntax for change the directory path of modules: This command will change the installing path of the external modules from node_modules to <dirname> folder in the working directory. npm install <dirname> Explanation: After installing any new module new packages are added to the node_modules folder and dependencies are updated to the package.json file. Installing module using npm command: Installing module using npm command: npm install mongodb package.json file: npm update command: This npm command is used for updating the dependencies that are mention in the package.json file as well as install all the missing packages in the directory and also used for updating the current node version on the machine.This command used in two different ways: Without ParameterWith Parameter Without Parameter With Parameter Without Parameter: npm update without parameter works on all globally installed packages and update all the versions of the globally packages available on our machine. Syntax: npm update -g Updating nodemon module that was installed globally: With parameter: npm update command takes the second parameter as a dependency name that we want to update the next version or latest version. We can also restrict the updating of the dependencies to the latest version with the help of some reserved symbols. If we install dependencies simply by mention its name, the latest patch of the dependencies will get install but it might create some problem because when we’re working on a project and want nearly equal to the current version dependence it. We cannot be able to come to install that particular dependency we will use reserved symbols to convert the updating track of the dependency There are mainly types of dependencies used in Node.js: 1. Caret Dependencies: When dependencies present in the package.json or package.lock.json file with ^ called Caret Symbol is called Caret Dependencies.These dependencies are updated to the latest version compatible to that version. "dependencies": { "dep11": "^2.2.2" } This npm update command will update to 2.3.3 (consider this version exists) and 2.3.3 satisfy previous version 2.Tilde Dependencies: npm update command will update these dependencies to the highest sorted version. These dependencies use ~ symbol. "dependencies": { "dep11": "^2.2.2" } If we update this dependency, it will get updated to 2.2.3 version in this case. Difference: The npm install installs all modules that are listed on package.json file and their dependencies. npm update updates all packages in the node_modules directory and their dependencies. NodeJS-Questions Picked Technical Scripter 2020 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect Node.js with React.js ? Node.js Export Module Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26293, "s": 26265, "text": "\n25 Jan, 2021" }, { "code": null, "e": 26513, "s": 26293, "text": "NPM is like a powerhouse for Node.js that contains all the necessary modules for the smooth running of the node.js application. It gets installed on our machine when we install Node.js on our Windows, Linux or MAC OS. " }, { "code": null, "e": 26573, "s": 26513, "text": "How to install Node on the machine? Refer to this article. " }, { "code": null, "e": 26910, "s": 26573, "text": "NPM has 580096 registered packages. The average rate of growth of this number is 291/day that means the growth of different kind of packages increasing drastically, so we have to update our node every time on our machine ? The answer is No! NPM allows us to install third-party modules on our machine according to the need of our work. " }, { "code": null, "e": 27152, "s": 26910, "text": "Another reason is predefined modules cannot be able to fulfill the need for big projects for e.g. HTTP modules cannot differentiate the multiple kinds of requests, so we have to install externally another popular module. i.e express module. " }, { "code": null, "e": 27267, "s": 27152, "text": "We can access third party modules using some predefined commands provided by Node Package Manager are given below:" }, { "code": null, "e": 27295, "s": 27267, "text": "Initial Project Structure :" }, { "code": null, "e": 27456, "s": 27295, "text": "npm install command: This npm command is used for installing the third party modules in our current directory. There are two different ways to use this command:" }, { "code": null, "e": 27488, "s": 27456, "text": "Without ParameterWith Parameter" }, { "code": null, "e": 27506, "s": 27488, "text": "Without Parameter" }, { "code": null, "e": 27521, "s": 27506, "text": "With Parameter" }, { "code": null, "e": 27706, "s": 27521, "text": "Without Parameter: When we use the npm command without a parameter this command automatically downloads all the dependencies that are written in the package.json file in our directory." }, { "code": null, "e": 27811, "s": 27706, "text": "Package.json: create a package.json file in the directory and mention express dependencies in this file." }, { "code": null, "e": 28060, "s": 27811, "text": "{\n \"name\": \"gfg\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"author\": \"\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"express\": \"^4.17.1\"\n }\n}" }, { "code": null, "e": 28085, "s": 28060, "text": "Run npm install command:" }, { "code": null, "e": 28107, "s": 28085, "text": "npm i \nor\nnpm install" }, { "code": null, "e": 28135, "s": 28107, "text": "Updated Project Structure: " }, { "code": null, "e": 28416, "s": 28135, "text": "package-lock.json file and node_modules created package-lock.json file contains all the necessary information of downloaded extra dependencies and node_modules folder contains all the different types of packages that installed along with our specified module in the package.json. " }, { "code": null, "e": 28612, "s": 28416, "text": "With Parameter: We can use the npm install command by specifying the name of the third-party module that we want to install for particular work. For e.g. let’s download MongoDB module for Node.js" }, { "code": null, "e": 28944, "s": 28612, "text": " Parameter: Parameter can be the name of the module that we want to install or folder name in which we want to install all third-party modules in the directory. By default, the folder is node_modules that contains all the installed modules. This folder is automatically generated when we install any external module the first time." }, { "code": null, "e": 28952, "s": 28944, "text": "Syntax:" }, { "code": null, "e": 28983, "s": 28952, "text": "npm install [-g] [<package>..]" }, { "code": null, "e": 29090, "s": 28983, "text": "Syntax for installing module: Module will get install in the node_modules folder in the present directory." }, { "code": null, "e": 29116, "s": 29090, "text": "npm install <module-name>" }, { "code": null, "e": 29295, "s": 29116, "text": "Syntax for installing any module globally: Globally installing means we can access the module without installing that module in a particular directory. For eg Nodemon module etc." }, { "code": null, "e": 29324, "s": 29295, "text": "npm install -g <module-name>" }, { "code": null, "e": 29507, "s": 29324, "text": " Syntax for change the directory path of modules: This command will change the installing path of the external modules from node_modules to <dirname> folder in the working directory." }, { "code": null, "e": 29529, "s": 29507, "text": "npm install <dirname>" }, { "code": null, "e": 29679, "s": 29529, "text": "Explanation: After installing any new module new packages are added to the node_modules folder and dependencies are updated to the package.json file." }, { "code": null, "e": 29716, "s": 29679, "text": "Installing module using npm command:" }, { "code": null, "e": 29753, "s": 29716, "text": "Installing module using npm command:" }, { "code": null, "e": 29773, "s": 29753, "text": "npm install mongodb" }, { "code": null, "e": 29792, "s": 29773, "text": "package.json file:" }, { "code": null, "e": 30078, "s": 29792, "text": "npm update command: This npm command is used for updating the dependencies that are mention in the package.json file as well as install all the missing packages in the directory and also used for updating the current node version on the machine.This command used in two different ways:" }, { "code": null, "e": 30110, "s": 30078, "text": "Without ParameterWith Parameter" }, { "code": null, "e": 30128, "s": 30110, "text": "Without Parameter" }, { "code": null, "e": 30143, "s": 30128, "text": "With Parameter" }, { "code": null, "e": 30311, "s": 30143, "text": "Without Parameter: npm update without parameter works on all globally installed packages and update all the versions of the globally packages available on our machine." }, { "code": null, "e": 30319, "s": 30311, "text": "Syntax:" }, { "code": null, "e": 30333, "s": 30319, "text": "npm update -g" }, { "code": null, "e": 30386, "s": 30333, "text": "Updating nodemon module that was installed globally:" }, { "code": null, "e": 31027, "s": 30386, "text": "With parameter: npm update command takes the second parameter as a dependency name that we want to update the next version or latest version. We can also restrict the updating of the dependencies to the latest version with the help of some reserved symbols. If we install dependencies simply by mention its name, the latest patch of the dependencies will get install but it might create some problem because when we’re working on a project and want nearly equal to the current version dependence it. We cannot be able to come to install that particular dependency we will use reserved symbols to convert the updating track of the dependency" }, { "code": null, "e": 31083, "s": 31027, "text": "There are mainly types of dependencies used in Node.js:" }, { "code": null, "e": 31319, "s": 31083, "text": " 1. Caret Dependencies: When dependencies present in the package.json or package.lock.json file with ^ called Caret Symbol is called Caret Dependencies.These dependencies are updated to the latest version compatible to that version." }, { "code": null, "e": 31359, "s": 31319, "text": "\"dependencies\": {\n \"dep11\": \"^2.2.2\"\n}" }, { "code": null, "e": 31470, "s": 31359, "text": "This npm update command will update to 2.3.3 (consider this version exists) and 2.3.3 satisfy previous version" }, { "code": null, "e": 31612, "s": 31470, "text": " 2.Tilde Dependencies: npm update command will update these dependencies to the highest sorted version. These dependencies use ~ symbol." }, { "code": null, "e": 31652, "s": 31612, "text": "\"dependencies\": {\n \"dep11\": \"^2.2.2\"\n}" }, { "code": null, "e": 31733, "s": 31652, "text": "If we update this dependency, it will get updated to 2.2.3 version in this case." }, { "code": null, "e": 31745, "s": 31733, "text": "Difference:" }, { "code": null, "e": 31843, "s": 31745, "text": "The npm install installs all modules that are listed on package.json file and their dependencies." }, { "code": null, "e": 31929, "s": 31843, "text": "npm update updates all packages in the node_modules directory and their dependencies." }, { "code": null, "e": 31946, "s": 31929, "text": "NodeJS-Questions" }, { "code": null, "e": 31953, "s": 31946, "text": "Picked" }, { "code": null, "e": 31977, "s": 31953, "text": "Technical Scripter 2020" }, { "code": null, "e": 31985, "s": 31977, "text": "Node.js" }, { "code": null, "e": 32004, "s": 31985, "text": "Technical Scripter" }, { "code": null, "e": 32021, "s": 32004, "text": "Web Technologies" }, { "code": null, "e": 32119, "s": 32021, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32158, "s": 32119, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 32180, "s": 32158, "text": "Node.js Export Module" }, { "code": null, "e": 32250, "s": 32180, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 32277, "s": 32250, "text": "Mongoose Populate() Method" }, { "code": null, "e": 32302, "s": 32277, "text": "Mongoose find() Function" }, { "code": null, "e": 32342, "s": 32302, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32387, "s": 32342, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32430, "s": 32387, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 32492, "s": 32430, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Data Structure alignment - GeeksforGeeks
08 Oct, 2021 Data structure alignment is the way data is arranged and accessed in computer memory. Data alignment and Data structure padding are two different issues but are related to each other and together known as Data Structure alignment. Data alignment: Data alignment means putting the data in memory at address equal to some multiple of the word size. This increases the performance of system due to the way the CPU handles memory. Data Structure Padding: Now, to align the data, it may be necessary to insert some extra bytes between the end of the last data structure and the start of the next data structure as the data is placed in memory as multiples of fixed word size. This insertion of extra bytes of memory to align the data is called data structure padding.Consider the structure as shown below: struct { char a; short int b; int c; char d; } Now we may think that the processor will allocate memory to this structure as shown below: The total memory allocated in this case is 8 bytes. But this never happens as the processor can access memory as fixed word size of 4 bytes. So, the integer variable c can not be allocated memory as shown above. An integer variable requires 4 bytes. The correct way of allocation of memory is shown below for this structure using padding bytes. The processor will require a total of 12 bytes for the above structure to maintain the data alignment. Look at the below C++ program: CPP // CPP program to test// size of struct#include <iostream>using namespace std; // first structurestruct test1{ short s; int i; char c;}; // second structurestruct test2{ int i; char c; short s;}; // driver programint main(){ test1 t1; test2 t2; cout << "size of struct test1 is " << sizeof(t1) << "\n"; cout << "size of struct test2 is " << sizeof(t2) << "\n"; return 0;} Output: size of struct test1 is 12 size of struct test2 is 8 For the first structure test1 the short variable takes 2 byte. Now the next variable is int which requires 4 bytes. So, 2 bytes padding is added after short variable. Now, the char variable requires 1 byte but memory will be accessed in word size of 4 byte so 3 byte of padding is added again. So, total 12 bytes of memory is required. We can similarly calculate the padding for the second structure also. Padding for both of the structures is shown below: struct test1 { short s; // 2 bytes // 2 padding bytes int i; // 4 bytes char c; // 1 byte // 3 padding bytes }; struct test2 { int i; // 4 bytes char c; // 1 byte // 1 padding byte short s; // 2 bytes }; Note :You can minimize the size of memory allocated for a structure by sorting members by alignment.References : 1) https://en.wikipedia.org/wiki/Data_structure_alignment 2) https://stackoverflow.com/a/119134/6942060This article is contributed by Mandeep Singh. 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. anandjadhav19 Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Activation Functions Characteristics of Internet of Things Advantages and Disadvantages of OOP Sensors in Internet of Things(IoT) Challenges in Internet of things (IoT) Introduction to Electronic Mail Election algorithm and distributed processing Introduction to Internet of Things (IoT) | Set 1 Communication Models in IoT (Internet of Things ) Introduction to Parallel Computing
[ { "code": null, "e": 25919, "s": 25891, "text": "\n08 Oct, 2021" }, { "code": null, "e": 26722, "s": 25919, "text": "Data structure alignment is the way data is arranged and accessed in computer memory. Data alignment and Data structure padding are two different issues but are related to each other and together known as Data Structure alignment. Data alignment: Data alignment means putting the data in memory at address equal to some multiple of the word size. This increases the performance of system due to the way the CPU handles memory. Data Structure Padding: Now, to align the data, it may be necessary to insert some extra bytes between the end of the last data structure and the start of the next data structure as the data is placed in memory as multiples of fixed word size. This insertion of extra bytes of memory to align the data is called data structure padding.Consider the structure as shown below: " }, { "code": null, "e": 26786, "s": 26722, "text": "struct \n{\n char a;\n short int b;\n int c;\n char d;\n}" }, { "code": null, "e": 26879, "s": 26786, "text": "Now we may think that the processor will allocate memory to this structure as shown below: " }, { "code": null, "e": 27226, "s": 26879, "text": "The total memory allocated in this case is 8 bytes. But this never happens as the processor can access memory as fixed word size of 4 bytes. So, the integer variable c can not be allocated memory as shown above. An integer variable requires 4 bytes. The correct way of allocation of memory is shown below for this structure using padding bytes. " }, { "code": null, "e": 27362, "s": 27226, "text": "The processor will require a total of 12 bytes for the above structure to maintain the data alignment. Look at the below C++ program: " }, { "code": null, "e": 27366, "s": 27362, "text": "CPP" }, { "code": "// CPP program to test// size of struct#include <iostream>using namespace std; // first structurestruct test1{ short s; int i; char c;}; // second structurestruct test2{ int i; char c; short s;}; // driver programint main(){ test1 t1; test2 t2; cout << \"size of struct test1 is \" << sizeof(t1) << \"\\n\"; cout << \"size of struct test2 is \" << sizeof(t2) << \"\\n\"; return 0;}", "e": 27771, "s": 27366, "text": null }, { "code": null, "e": 27781, "s": 27771, "text": "Output: " }, { "code": null, "e": 27834, "s": 27781, "text": "size of struct test1 is 12\nsize of struct test2 is 8" }, { "code": null, "e": 28293, "s": 27834, "text": "For the first structure test1 the short variable takes 2 byte. Now the next variable is int which requires 4 bytes. So, 2 bytes padding is added after short variable. Now, the char variable requires 1 byte but memory will be accessed in word size of 4 byte so 3 byte of padding is added again. So, total 12 bytes of memory is required. We can similarly calculate the padding for the second structure also. Padding for both of the structures is shown below: " }, { "code": null, "e": 28559, "s": 28293, "text": "struct test1\n{\n short s; \n // 2 bytes\n // 2 padding bytes\n int i;\n // 4 bytes\n char c;\n // 1 byte\n // 3 padding bytes\n};\n\nstruct test2\n{\n int i;\n // 4 bytes\n char c;\n // 1 byte\n // 1 padding byte\n short s;\n // 2 bytes\n};" }, { "code": null, "e": 29197, "s": 28559, "text": "Note :You can minimize the size of memory allocated for a structure by sorting members by alignment.References : 1) https://en.wikipedia.org/wiki/Data_structure_alignment 2) https://stackoverflow.com/a/119134/6942060This article is contributed by Mandeep Singh. 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": 29211, "s": 29197, "text": "anandjadhav19" }, { "code": null, "e": 29216, "s": 29211, "text": "Misc" }, { "code": null, "e": 29221, "s": 29216, "text": "Misc" }, { "code": null, "e": 29226, "s": 29221, "text": "Misc" }, { "code": null, "e": 29324, "s": 29226, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29345, "s": 29324, "text": "Activation Functions" }, { "code": null, "e": 29383, "s": 29345, "text": "Characteristics of Internet of Things" }, { "code": null, "e": 29419, "s": 29383, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 29454, "s": 29419, "text": "Sensors in Internet of Things(IoT)" }, { "code": null, "e": 29493, "s": 29454, "text": "Challenges in Internet of things (IoT)" }, { "code": null, "e": 29525, "s": 29493, "text": "Introduction to Electronic Mail" }, { "code": null, "e": 29571, "s": 29525, "text": "Election algorithm and distributed processing" }, { "code": null, "e": 29620, "s": 29571, "text": "Introduction to Internet of Things (IoT) | Set 1" }, { "code": null, "e": 29670, "s": 29620, "text": "Communication Models in IoT (Internet of Things )" } ]
Print different star patterns in SQL - GeeksforGeeks
21 Mar, 2018 Let’s see how we can print the pattern of various type using SQL. Syntax : Declare @variable_name DATATYPE -- first declare all the -- variables with datatype -- like (int) select @variable = WITH_ANY_VALUE -- select the variable and -- initialize with value while CONDITION -- condition like @variable > 0 begin -- begin print replicate('*', @variable) -- replicate insert the * -- character in variable times set increment/decrement -- in increment/decrement -- @variable= @variable+1 END -- end while loop DECLARE @var int -- DeclareSELECT @var = 5 -- InitializationWHILE @var > 0 -- conditionBEGIN -- BeginPRINT replicate('* ', @var) -- PrintSET @var = @var - 1 -- decrementEND -- END Output : * * * * * * * * * * * * * * * Second Pattern : DECLARE @var int -- Declare SELECT @var = 1 -- initialization WHILE @var <= 5 -- ConditionBEGIN -- BeginPRINT replicate('* ', @var) -- PrintSET @var = @var + 1 -- SetEND -- end Output : * * * * * * * * * * * * * * * Third Pattern : DECLARE @var int, @x int -- declare two variableSELECT @var = 4,@x = 1 -- initializationWHILE @x <=5 -- conditionBEGINPRINT space(@var) + replicate('*', @x) -- here space for -- create spaces SET @var = @var - 1 -- setset @x = @x + 1 -- setEND -- End Output : * ** *** **** ***** Fourth Pattern : DECLARE @var int, @x int -- declare two variableSELECT @var = 0,@x = 5 -- initializationWHILE @x > 0 -- conditionBEGINPRINT space(@var) + replicate('*', @x) -- here space for -- create spaces SET @var = @var + 1 -- setset @x = @x - 1 -- setEND -- End Output : ***** **** *** ** * pattern-printing SQL-PL/SQL SQL pattern-printing SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? Difference between SQL and NoSQL Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL?
[ { "code": null, "e": 25561, "s": 25533, "text": "\n21 Mar, 2018" }, { "code": null, "e": 25627, "s": 25561, "text": "Let’s see how we can print the pattern of various type using SQL." }, { "code": null, "e": 25636, "s": 25627, "text": "Syntax :" }, { "code": null, "e": 26364, "s": 25636, "text": "\nDeclare @variable_name DATATYPE -- first declare all the\n -- variables with datatype\n -- like (int)\n\nselect @variable = WITH_ANY_VALUE -- select the variable and \n -- initialize with value\n\nwhile CONDITION -- condition like @variable > 0 \n\nbegin -- begin\n\nprint replicate('*', @variable) -- replicate insert the *\n -- character in variable times\n\nset increment/decrement -- in increment/decrement\n -- @variable= @variable+1\nEND -- end while loop\n\n" }, { "code": "DECLARE @var int -- DeclareSELECT @var = 5 -- InitializationWHILE @var > 0 -- conditionBEGIN -- BeginPRINT replicate('* ', @var) -- PrintSET @var = @var - 1 -- decrementEND -- END", "e": 26655, "s": 26364, "text": null }, { "code": null, "e": 26664, "s": 26655, "text": "Output :" }, { "code": null, "e": 26698, "s": 26664, "text": "* * * * *\n* * * * \n* * * \n* * \n*\n" }, { "code": null, "e": 26715, "s": 26698, "text": "Second Pattern :" }, { "code": "DECLARE @var int -- Declare SELECT @var = 1 -- initialization WHILE @var <= 5 -- ConditionBEGIN -- BeginPRINT replicate('* ', @var) -- PrintSET @var = @var + 1 -- SetEND -- end", "e": 27023, "s": 26715, "text": null }, { "code": null, "e": 27032, "s": 27023, "text": "Output :" }, { "code": null, "e": 27063, "s": 27032, "text": "*\n* *\n* * *\n* * * *\n* * * * *\n" }, { "code": null, "e": 27079, "s": 27063, "text": "Third Pattern :" }, { "code": "DECLARE @var int, @x int -- declare two variableSELECT @var = 4,@x = 1 -- initializationWHILE @x <=5 -- conditionBEGINPRINT space(@var) + replicate('*', @x) -- here space for -- create spaces SET @var = @var - 1 -- setset @x = @x + 1 -- setEND -- End", "e": 27518, "s": 27079, "text": null }, { "code": null, "e": 27527, "s": 27518, "text": "Output :" }, { "code": null, "e": 27558, "s": 27527, "text": " *\n **\n ***\n ****\n*****\n" }, { "code": null, "e": 27575, "s": 27558, "text": "Fourth Pattern :" }, { "code": "DECLARE @var int, @x int -- declare two variableSELECT @var = 0,@x = 5 -- initializationWHILE @x > 0 -- conditionBEGINPRINT space(@var) + replicate('*', @x) -- here space for -- create spaces SET @var = @var + 1 -- setset @x = @x - 1 -- setEND -- End", "e": 28013, "s": 27575, "text": null }, { "code": null, "e": 28022, "s": 28013, "text": "Output :" }, { "code": null, "e": 28053, "s": 28022, "text": "*****\n ****\n ***\n **\n *\n" }, { "code": null, "e": 28070, "s": 28053, "text": "pattern-printing" }, { "code": null, "e": 28081, "s": 28070, "text": "SQL-PL/SQL" }, { "code": null, "e": 28085, "s": 28081, "text": "SQL" }, { "code": null, "e": 28102, "s": 28085, "text": "pattern-printing" }, { "code": null, "e": 28106, "s": 28102, "text": "SQL" }, { "code": null, "e": 28204, "s": 28106, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28228, "s": 28204, "text": "SQL Interview Questions" }, { "code": null, "e": 28239, "s": 28228, "text": "CTE in SQL" }, { "code": null, "e": 28305, "s": 28239, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28338, "s": 28305, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 28383, "s": 28338, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 28415, "s": 28383, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 28454, "s": 28415, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 28469, "s": 28454, "text": "SQL | Subquery" }, { "code": null, "e": 28526, "s": 28469, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" } ]
ReactJS componentWillUnmount() Method - GeeksforGeeks
18 Jan, 2021 The componentWillUnmount() method allows us to execute the React code when the component gets destroyed or unmounted from the DOM (Document Object Model). This method is called during the Unmounting phase of the React Life-cycle i.e before the component gets unmounted. All the cleanups such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount() should be coded in the componentWillUnmount() method block. Tip: Never call setState() in componentWillUnmount() method. Syntax: componentWillUnmount() Creating React Application: Step 1: Create a React application using the following command: npx create-react-app functiondemo Step 2: After creating your project folder i.e. functiondemo, move to it using the following command: cd functiondemo Project Structure: It will look like the following. Project Structure Example: In this example, we are going to build a name color application that changes the color of the text when the component is rendered in the DOM tree. App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react';class ComponentOne extends React.Component { // Defining the componentWillUnmount method componentWillUnmount() { alert('The component is going to be unmounted'); } render() { return <h1>Hello Geeks!</h1>; }} class App extends React.Component { state = { display: true }; delete = () => { this.setState({ display: false }); }; render() { let comp; if (this.state.display) { comp = <ComponentOne />; } return ( <div> {comp} <button onClick={this.delete}> Delete the component </button> </div> ); }} export default App; Note: You can define your own styling in the App.css file. Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Reference: https://reactjs.org/docs/react-component.html#componentwillunmount rbbansal react-js Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array How to apply style to parent if it has child with CSS? How to convert array to string in PHP ? What is web socket and how it is different from the HTTP? How to set space between the flexbox ? Design a web page using HTML and CSS How to install the previous version of node.js and npm ? How to get selected value in dropdown list using JavaScript ? How to Fix a 401 Unauthorized Error? How to change selected value of a drop-down list using jQuery?
[ { "code": null, "e": 26557, "s": 26529, "text": "\n18 Jan, 2021" }, { "code": null, "e": 26827, "s": 26557, "text": "The componentWillUnmount() method allows us to execute the React code when the component gets destroyed or unmounted from the DOM (Document Object Model). This method is called during the Unmounting phase of the React Life-cycle i.e before the component gets unmounted." }, { "code": null, "e": 27035, "s": 26827, "text": "All the cleanups such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount() should be coded in the componentWillUnmount() method block." }, { "code": null, "e": 27096, "s": 27035, "text": "Tip: Never call setState() in componentWillUnmount() method." }, { "code": null, "e": 27104, "s": 27096, "text": "Syntax:" }, { "code": null, "e": 27127, "s": 27104, "text": "componentWillUnmount()" }, { "code": null, "e": 27155, "s": 27127, "text": "Creating React Application:" }, { "code": null, "e": 27219, "s": 27155, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 27253, "s": 27219, "text": "npx create-react-app functiondemo" }, { "code": null, "e": 27355, "s": 27253, "text": "Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:" }, { "code": null, "e": 27371, "s": 27355, "text": "cd functiondemo" }, { "code": null, "e": 27423, "s": 27371, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 27441, "s": 27423, "text": "Project Structure" }, { "code": null, "e": 27597, "s": 27441, "text": "Example: In this example, we are going to build a name color application that changes the color of the text when the component is rendered in the DOM tree." }, { "code": null, "e": 27726, "s": 27597, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 27737, "s": 27726, "text": "Javascript" }, { "code": "import React from 'react';class ComponentOne extends React.Component { // Defining the componentWillUnmount method componentWillUnmount() { alert('The component is going to be unmounted'); } render() { return <h1>Hello Geeks!</h1>; }} class App extends React.Component { state = { display: true }; delete = () => { this.setState({ display: false }); }; render() { let comp; if (this.state.display) { comp = <ComponentOne />; } return ( <div> {comp} <button onClick={this.delete}> Delete the component </button> </div> ); }} export default App;", "e": 28363, "s": 27737, "text": null }, { "code": null, "e": 28424, "s": 28363, "text": " Note: You can define your own styling in the App.css file." }, { "code": null, "e": 28538, "s": 28424, "text": "Step to Run Application: Run the application using the following command from the root directory of the project: " }, { "code": null, "e": 28548, "s": 28538, "text": "npm start" }, { "code": null, "e": 28557, "s": 28548, "text": "Output: " }, { "code": null, "e": 28639, "s": 28561, "text": "Reference: https://reactjs.org/docs/react-component.html#componentwillunmount" }, { "code": null, "e": 28650, "s": 28641, "text": "rbbansal" }, { "code": null, "e": 28659, "s": 28650, "text": "react-js" }, { "code": null, "e": 28686, "s": 28659, "text": "Web technologies Questions" }, { "code": null, "e": 28784, "s": 28686, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28824, "s": 28784, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28879, "s": 28824, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 28919, "s": 28879, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28977, "s": 28919, "text": "What is web socket and how it is different from the HTTP?" }, { "code": null, "e": 29016, "s": 28977, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29053, "s": 29016, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29110, "s": 29053, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 29172, "s": 29110, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 29209, "s": 29172, "text": "How to Fix a 401 Unauthorized Error?" } ]
Matplotlib.figure.Figure.text() in Python - GeeksforGeeks
03 May, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. The text() method figure module of matplotlib library is used to Add text to figure. Syntax: text(self, x, y, s, fontdict=None, withdash=, **kwargs) Parameters: This method accept the following parameters that are discussed below: x: This parameter is the x position to place the text. y: This parameter is the y position to place the text. s: This parameter is the text string. fontdict : This parameter is the dictionary to override the default text properties. withdash : This parameter is used to create a TextWithDash instance instead of a Text instance. Returns: This method returns the Text. Below examples illustrate the matplotlib.figure.Figure.text() function in matplotlib.figure: Example 1: #Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots() fig.text(0.28, 0.5, 'GeeksforGeeks', style = 'italic', fontsize = 30, color = "green") ax.set(xlim = (0, 8), ylim = (0, 8)) fig.suptitle("""matplotlib.figure.Figure.text()function Example\n\n""",fontweight="bold") fig.show() Output: Example 2: # Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.set_xlabel('xlabel')ax.set_ylabel('ylabel') fig.text(0.3, 0.7, 'GeeksforGeeks', style = 'italic', fontsize = 30, bbox ={'facecolor':'green', 'alpha':0.6, 'pad':10}) fig.text(0.35, 0.6, 'Python matplotlib Module', fontsize = 15) fig.text(0.35, 0.3, 'Figure Class - Text Function') fig.text(0, 0, 'by-Shubham Singh', verticalalignment ='bottom', horizontalalignment ='left', transform = ax.transAxes, color ='green', fontsize = 5) ax.set(xlim =(0, 10), ylim =(0, 10)) fig.suptitle("""matplotlib.figure.Figure.text()function Example\n\n""", fontweight ="bold") fig.show() Output: Matplotlib figure-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26203, "s": 26175, "text": "\n03 May, 2020" }, { "code": null, "e": 26514, "s": 26203, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements." }, { "code": null, "e": 26599, "s": 26514, "text": "The text() method figure module of matplotlib library is used to Add text to figure." }, { "code": null, "e": 26663, "s": 26599, "text": "Syntax: text(self, x, y, s, fontdict=None, withdash=, **kwargs)" }, { "code": null, "e": 26745, "s": 26663, "text": "Parameters: This method accept the following parameters that are discussed below:" }, { "code": null, "e": 26800, "s": 26745, "text": "x: This parameter is the x position to place the text." }, { "code": null, "e": 26855, "s": 26800, "text": "y: This parameter is the y position to place the text." }, { "code": null, "e": 26893, "s": 26855, "text": "s: This parameter is the text string." }, { "code": null, "e": 26978, "s": 26893, "text": "fontdict : This parameter is the dictionary to override the default text properties." }, { "code": null, "e": 27074, "s": 26978, "text": "withdash : This parameter is used to create a TextWithDash instance instead of a Text instance." }, { "code": null, "e": 27113, "s": 27074, "text": "Returns: This method returns the Text." }, { "code": null, "e": 27206, "s": 27113, "text": "Below examples illustrate the matplotlib.figure.Figure.text() function in matplotlib.figure:" }, { "code": null, "e": 27217, "s": 27206, "text": "Example 1:" }, { "code": "#Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots() fig.text(0.28, 0.5, 'GeeksforGeeks', style = 'italic', fontsize = 30, color = \"green\") ax.set(xlim = (0, 8), ylim = (0, 8)) fig.suptitle(\"\"\"matplotlib.figure.Figure.text()function Example\\n\\n\"\"\",fontweight=\"bold\") fig.show()", "e": 27593, "s": 27217, "text": null }, { "code": null, "e": 27601, "s": 27593, "text": "Output:" }, { "code": null, "e": 27612, "s": 27601, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.set_xlabel('xlabel')ax.set_ylabel('ylabel') fig.text(0.3, 0.7, 'GeeksforGeeks', style = 'italic', fontsize = 30, bbox ={'facecolor':'green', 'alpha':0.6, 'pad':10}) fig.text(0.35, 0.6, 'Python matplotlib Module', fontsize = 15) fig.text(0.35, 0.3, 'Figure Class - Text Function') fig.text(0, 0, 'by-Shubham Singh', verticalalignment ='bottom', horizontalalignment ='left', transform = ax.transAxes, color ='green', fontsize = 5) ax.set(xlim =(0, 10), ylim =(0, 10)) fig.suptitle(\"\"\"matplotlib.figure.Figure.text()function Example\\n\\n\"\"\", fontweight =\"bold\") fig.show()", "e": 28422, "s": 27612, "text": null }, { "code": null, "e": 28430, "s": 28422, "text": "Output:" }, { "code": null, "e": 28454, "s": 28430, "text": "Matplotlib figure-class" }, { "code": null, "e": 28472, "s": 28454, "text": "Python-matplotlib" }, { "code": null, "e": 28479, "s": 28472, "text": "Python" }, { "code": null, "e": 28577, "s": 28479, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28595, "s": 28577, "text": "Python Dictionary" }, { "code": null, "e": 28630, "s": 28595, "text": "Read a file line by line in Python" }, { "code": null, "e": 28662, "s": 28630, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28684, "s": 28662, "text": "Enumerate() in Python" }, { "code": null, "e": 28726, "s": 28684, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28756, "s": 28726, "text": "Iterate over a list in Python" }, { "code": null, "e": 28782, "s": 28756, "text": "Python String | replace()" }, { "code": null, "e": 28811, "s": 28782, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28855, "s": 28811, "text": "Reading and Writing to text files in Python" } ]
JavaScript | Difference between String.slice and String.substring
21 Apr, 2022 These 2 functions are quite similar in their Syntax But are different in some cases. Let’s see difference between them. slice():This method selects the part of a string and returns the selected part as a new string. Start and end parameters are used to specify the extracted part.The first character starts with index 0.Syntax:str.slice(start, end) Parameter:start:This parameter is required. It specifies the position from where to start the extraction. First character starts at position 0.end:This parameter is optional. The position (up to, but excluding) where to stop the selection. If parameter is omitted, function selects all characters from the start parameter till the end of the string.substring():This function have the same syntax as of slice()This method selects the part of a string and returns the selected part as a new string. Start and end parameters are used to specify the extracted part.The first character starts with index 0.Syntax:str.substring(start, end) Parameter:start:This parameter is required. It specifies the position from where to start the extraction. First character starts at position 0.end:This parameter is optional. The position (up to, but excluding) where to stop the selection. If parameter is omitted, function selects all characters from the start parameter till the end of the string. slice():This method selects the part of a string and returns the selected part as a new string. Start and end parameters are used to specify the extracted part.The first character starts with index 0.Syntax:str.slice(start, end) Parameter:start:This parameter is required. It specifies the position from where to start the extraction. First character starts at position 0.end:This parameter is optional. The position (up to, but excluding) where to stop the selection. If parameter is omitted, function selects all characters from the start parameter till the end of the string. Syntax: str.slice(start, end) Parameter: start:This parameter is required. It specifies the position from where to start the extraction. First character starts at position 0. end:This parameter is optional. The position (up to, but excluding) where to stop the selection. If parameter is omitted, function selects all characters from the start parameter till the end of the string. substring():This function have the same syntax as of slice()This method selects the part of a string and returns the selected part as a new string. Start and end parameters are used to specify the extracted part.The first character starts with index 0.Syntax:str.substring(start, end) Parameter:start:This parameter is required. It specifies the position from where to start the extraction. First character starts at position 0.end:This parameter is optional. The position (up to, but excluding) where to stop the selection. If parameter is omitted, function selects all characters from the start parameter till the end of the string. Syntax: str.substring(start, end) Parameter: start:This parameter is required. It specifies the position from where to start the extraction. First character starts at position 0. end:This parameter is optional. The position (up to, but excluding) where to stop the selection. If parameter is omitted, function selects all characters from the start parameter till the end of the string. Common ResultBoth give same results in the given cases. If start == stop, both returns an empty stringIf stop is omitted, both extracts characters till the end of the stringIf any argument is greater than the string’s length, the string’s length will be used in that case. If start == stop, both returns an empty string If stop is omitted, both extracts characters till the end of the string If any argument is greater than the string’s length, the string’s length will be used in that case. substring()Separate results of substring() If start > stop, then function swaps both arguments.If any argument is negative or is NaN, it is treated as 0. If start > stop, then function swaps both arguments. If any argument is negative or is NaN, it is treated as 0. slice()Separate results of slice() If start > stop, This function will return an empty string. (“”)If start is negative, It sets char from the end of string, like substr().If stop is negative, It sets stop = string.length – Math.abs(stop) (original value) If start > stop, This function will return an empty string. (“”) If start is negative, It sets char from the end of string, like substr(). If stop is negative, It sets stop = string.length – Math.abs(stop) (original value) Here are a few of the examples.Example-1: This examples give the same results in both the cases. <!DOCTYPE html><html> <head> <title> JavaScript | difference between String.slice and String.substring </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick="Geeks()"> click Here </button> <p id="GFG_DOWN" style="color:green;"> </p> <script> var str = "This is GeeksForGeeks"; var up = document.getElementById("GFG_UP"); var down = document.getElementById("GFG_DOWN"); up.innerHTML = "Str = '" + str + "'"; function Geeks() { down.innerHTML = "str.slice() = " + str.slice(0, 13) + "<br>str.substring() = " + str.substring(0, 13); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example-2:In this Example, In case of substring() it swaps the arguments when start>stop where the slice() returns the empty string. <!DOCTYPE html><html> <head> <title> JavaScript | difference between String.slice and String.substring </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick="Geeks()"> click Here </button> <p id="GFG_DOWN" style="color:green;"> </p> <script> var str = "This is GeeksForGeeks"; var up = document.getElementById("GFG_UP"); var down = document.getElementById("GFG_DOWN"); up.innerHTML = "Str = '" + str + "'"; function Geeks() { down.innerHTML = "str.slice() = " + str.slice(13, 0) + "<br>str.substring() = " + str.substring(13, 0); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example-3:In this Example, In case of substring() negative arguments are treated as 0 where the slice() returns the empty string. <!DOCTYPE html><html> <head> <title> JavaScript | difference between String.slice and String.substring </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick="Geeks()"> click Here </button> <p id="GFG_DOWN" style="color:green;"> </p> <script> var str = "This is GeeksForGeeks"; var up = document.getElementById("GFG_UP"); var down = document.getElementById("GFG_DOWN"); up.innerHTML = "Str = '" + str + "'"; function Geeks() { down.innerHTML = "str.slice() = " + str.slice(-13, 7) + "<br>str.substring() = " + str.substring(-13, 7); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Syntax -: string_name.slice(index1 , index2) Syntax – : string.substring(start, end) mayank007rawa JavaScript-Misc javascript-string JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2022" }, { "code": null, "e": 148, "s": 28, "text": "These 2 functions are quite similar in their Syntax But are different in some cases. Let’s see difference between them." }, { "code": null, "e": 1361, "s": 148, "text": "slice():This method selects the part of a string and returns the selected part as a new string. Start and end parameters are used to specify the extracted part.The first character starts with index 0.Syntax:str.slice(start, end)\nParameter:start:This parameter is required. It specifies the position from where to start the extraction. First character starts at position 0.end:This parameter is optional. The position (up to, but excluding) where to stop the selection. If parameter is omitted, function selects all characters from the start parameter till the end of the string.substring():This function have the same syntax as of slice()This method selects the part of a string and returns the selected part as a new string. Start and end parameters are used to specify the extracted part.The first character starts with index 0.Syntax:str.substring(start, end)\nParameter:start:This parameter is required. It specifies the position from where to start the extraction. First character starts at position 0.end:This parameter is optional. The position (up to, but excluding) where to stop the selection. If parameter is omitted, function selects all characters from the start parameter till the end of the string." }, { "code": null, "e": 1940, "s": 1361, "text": "slice():This method selects the part of a string and returns the selected part as a new string. Start and end parameters are used to specify the extracted part.The first character starts with index 0.Syntax:str.slice(start, end)\nParameter:start:This parameter is required. It specifies the position from where to start the extraction. First character starts at position 0.end:This parameter is optional. The position (up to, but excluding) where to stop the selection. If parameter is omitted, function selects all characters from the start parameter till the end of the string." }, { "code": null, "e": 1948, "s": 1940, "text": "Syntax:" }, { "code": null, "e": 1971, "s": 1948, "text": "str.slice(start, end)\n" }, { "code": null, "e": 1982, "s": 1971, "text": "Parameter:" }, { "code": null, "e": 2116, "s": 1982, "text": "start:This parameter is required. It specifies the position from where to start the extraction. First character starts at position 0." }, { "code": null, "e": 2323, "s": 2116, "text": "end:This parameter is optional. The position (up to, but excluding) where to stop the selection. If parameter is omitted, function selects all characters from the start parameter till the end of the string." }, { "code": null, "e": 2958, "s": 2323, "text": "substring():This function have the same syntax as of slice()This method selects the part of a string and returns the selected part as a new string. Start and end parameters are used to specify the extracted part.The first character starts with index 0.Syntax:str.substring(start, end)\nParameter:start:This parameter is required. It specifies the position from where to start the extraction. First character starts at position 0.end:This parameter is optional. The position (up to, but excluding) where to stop the selection. If parameter is omitted, function selects all characters from the start parameter till the end of the string." }, { "code": null, "e": 2966, "s": 2958, "text": "Syntax:" }, { "code": null, "e": 2993, "s": 2966, "text": "str.substring(start, end)\n" }, { "code": null, "e": 3004, "s": 2993, "text": "Parameter:" }, { "code": null, "e": 3138, "s": 3004, "text": "start:This parameter is required. It specifies the position from where to start the extraction. First character starts at position 0." }, { "code": null, "e": 3345, "s": 3138, "text": "end:This parameter is optional. The position (up to, but excluding) where to stop the selection. If parameter is omitted, function selects all characters from the start parameter till the end of the string." }, { "code": null, "e": 3401, "s": 3345, "text": "Common ResultBoth give same results in the given cases." }, { "code": null, "e": 3618, "s": 3401, "text": "If start == stop, both returns an empty stringIf stop is omitted, both extracts characters till the end of the stringIf any argument is greater than the string’s length, the string’s length will be used in that case." }, { "code": null, "e": 3665, "s": 3618, "text": "If start == stop, both returns an empty string" }, { "code": null, "e": 3737, "s": 3665, "text": "If stop is omitted, both extracts characters till the end of the string" }, { "code": null, "e": 3837, "s": 3737, "text": "If any argument is greater than the string’s length, the string’s length will be used in that case." }, { "code": null, "e": 3880, "s": 3837, "text": "substring()Separate results of substring()" }, { "code": null, "e": 3991, "s": 3880, "text": "If start > stop, then function swaps both arguments.If any argument is negative or is NaN, it is treated as 0." }, { "code": null, "e": 4044, "s": 3991, "text": "If start > stop, then function swaps both arguments." }, { "code": null, "e": 4103, "s": 4044, "text": "If any argument is negative or is NaN, it is treated as 0." }, { "code": null, "e": 4138, "s": 4103, "text": "slice()Separate results of slice()" }, { "code": null, "e": 4359, "s": 4138, "text": "If start > stop, This function will return an empty string. (“”)If start is negative, It sets char from the end of string, like substr().If stop is negative, It sets stop = string.length – Math.abs(stop) (original value)" }, { "code": null, "e": 4424, "s": 4359, "text": "If start > stop, This function will return an empty string. (“”)" }, { "code": null, "e": 4498, "s": 4424, "text": "If start is negative, It sets char from the end of string, like substr()." }, { "code": null, "e": 4582, "s": 4498, "text": "If stop is negative, It sets stop = string.length – Math.abs(stop) (original value)" }, { "code": null, "e": 4679, "s": 4582, "text": "Here are a few of the examples.Example-1: This examples give the same results in both the cases." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | difference between String.slice and String.substring </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"Geeks()\"> click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"> </p> <script> var str = \"This is GeeksForGeeks\"; var up = document.getElementById(\"GFG_UP\"); var down = document.getElementById(\"GFG_DOWN\"); up.innerHTML = \"Str = '\" + str + \"'\"; function Geeks() { down.innerHTML = \"str.slice() = \" + str.slice(0, 13) + \"<br>str.substring() = \" + str.substring(0, 13); } </script></body> </html>", "e": 5506, "s": 4679, "text": null }, { "code": null, "e": 5514, "s": 5506, "text": "Output:" }, { "code": null, "e": 5545, "s": 5514, "text": "Before clicking on the button:" }, { "code": null, "e": 5575, "s": 5545, "text": "After clicking on the button:" }, { "code": null, "e": 5708, "s": 5575, "text": "Example-2:In this Example, In case of substring() it swaps the arguments when start>stop where the slice() returns the empty string." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | difference between String.slice and String.substring </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"Geeks()\"> click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"> </p> <script> var str = \"This is GeeksForGeeks\"; var up = document.getElementById(\"GFG_UP\"); var down = document.getElementById(\"GFG_DOWN\"); up.innerHTML = \"Str = '\" + str + \"'\"; function Geeks() { down.innerHTML = \"str.slice() = \" + str.slice(13, 0) + \"<br>str.substring() = \" + str.substring(13, 0); } </script></body> </html>", "e": 6534, "s": 5708, "text": null }, { "code": null, "e": 6542, "s": 6534, "text": "Output:" }, { "code": null, "e": 6573, "s": 6542, "text": "Before clicking on the button:" }, { "code": null, "e": 6603, "s": 6573, "text": "After clicking on the button:" }, { "code": null, "e": 6733, "s": 6603, "text": "Example-3:In this Example, In case of substring() negative arguments are treated as 0 where the slice() returns the empty string." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | difference between String.slice and String.substring </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"Geeks()\"> click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"> </p> <script> var str = \"This is GeeksForGeeks\"; var up = document.getElementById(\"GFG_UP\"); var down = document.getElementById(\"GFG_DOWN\"); up.innerHTML = \"Str = '\" + str + \"'\"; function Geeks() { down.innerHTML = \"str.slice() = \" + str.slice(-13, 7) + \"<br>str.substring() = \" + str.substring(-13, 7); } </script></body> </html>", "e": 7560, "s": 6733, "text": null }, { "code": null, "e": 7568, "s": 7560, "text": "Output:" }, { "code": null, "e": 7599, "s": 7568, "text": "Before clicking on the button:" }, { "code": null, "e": 7629, "s": 7599, "text": "After clicking on the button:" }, { "code": null, "e": 7639, "s": 7629, "text": "Syntax -:" }, { "code": null, "e": 7674, "s": 7639, "text": "string_name.slice(index1 , index2)" }, { "code": null, "e": 7685, "s": 7674, "text": "Syntax – :" }, { "code": null, "e": 7714, "s": 7685, "text": "string.substring(start, end)" }, { "code": null, "e": 7728, "s": 7714, "text": "mayank007rawa" }, { "code": null, "e": 7744, "s": 7728, "text": "JavaScript-Misc" }, { "code": null, "e": 7762, "s": 7744, "text": "javascript-string" }, { "code": null, "e": 7773, "s": 7762, "text": "JavaScript" }, { "code": null, "e": 7790, "s": 7773, "text": "Web Technologies" }, { "code": null, "e": 7817, "s": 7790, "text": "Web technologies Questions" } ]
Output of C Programs | Set 12
27 Dec, 2016 Predict the output of below programs. Question 1 int fun(char *str1){ char *str2 = str1; while(*++str1); return (str1-str2);} int main(){ char *str = "geeksforgeeks"; printf("%d", fun(str)); getchar(); return 0;} Output: 13Inside fun(), pointer str2 is initialized as str1 and str1 is moved till ‘\0’ is reached (note ; after while loop). So str1 will be incremented by 13 (assuming that char takes 1 byte). Question 2 void fun(int *p){ static int q = 10; p = &q;} int main(){ int r = 20; int *p = &r; fun(p); printf("%d", *p); getchar(); return 0;} Output: 20Inside fun(), q is a copy of the pointer p. So if we change q to point something else then p remains unaffected. Question 3 void fun(int **p){ static int q = 10; *p = &q;} int main(){ int r = 20; int *p = &r; fun(&p); printf("%d", *p); getchar(); return 0;} Output 10 Note that we are passing address of p to fun(). p in fun() is actually a pointer to p in main() and we are changing value at p in fun(). So p of main is changed to point q of fun(). To understand it better, let us rename p in fun() to p_ref or ptr_to_p void fun(int **ptr_to_p){ static int q = 10; *ptr_to_p = &q; /*Now p of main is pointing to q*/} Also, note that the program won’t cause any 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 weird output because auto variable may not exist in memory after functions return. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. C-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Dec, 2016" }, { "code": null, "e": 92, "s": 54, "text": "Predict the output of below programs." }, { "code": null, "e": 103, "s": 92, "text": "Question 1" }, { "code": "int fun(char *str1){ char *str2 = str1; while(*++str1); return (str1-str2);} int main(){ char *str = \"geeksforgeeks\"; printf(\"%d\", fun(str)); getchar(); return 0;}", "e": 279, "s": 103, "text": null }, { "code": null, "e": 474, "s": 279, "text": "Output: 13Inside fun(), pointer str2 is initialized as str1 and str1 is moved till ‘\\0’ is reached (note ; after while loop). So str1 will be incremented by 13 (assuming that char takes 1 byte)." }, { "code": null, "e": 485, "s": 474, "text": "Question 2" }, { "code": "void fun(int *p){ static int q = 10; p = &q;} int main(){ int r = 20; int *p = &r; fun(p); printf(\"%d\", *p); getchar(); return 0;}", "e": 629, "s": 485, "text": null }, { "code": null, "e": 752, "s": 629, "text": "Output: 20Inside fun(), q is a copy of the pointer p. So if we change q to point something else then p remains unaffected." }, { "code": null, "e": 763, "s": 752, "text": "Question 3" }, { "code": "void fun(int **p){ static int q = 10; *p = &q;} int main(){ int r = 20; int *p = &r; fun(&p); printf(\"%d\", *p); getchar(); return 0;}", "e": 910, "s": 763, "text": null }, { "code": null, "e": 920, "s": 910, "text": "Output 10" }, { "code": null, "e": 1173, "s": 920, "text": "Note that we are passing address of p to fun(). p in fun() is actually a pointer to p in main() and we are changing value at p in fun(). So p of main is changed to point q of fun(). To understand it better, let us rename p in fun() to p_ref or ptr_to_p" }, { "code": "void fun(int **ptr_to_p){ static int q = 10; *ptr_to_p = &q; /*Now p of main is pointing to q*/}", "e": 1273, "s": 1173, "text": null }, { "code": null, "e": 1548, "s": 1273, "text": "Also, note that the program won’t cause any 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 weird output because auto variable may not exist in memory after functions return." }, { "code": null, "e": 1697, "s": 1548, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above." }, { "code": null, "e": 1706, "s": 1697, "text": "C-Output" }, { "code": null, "e": 1721, "s": 1706, "text": "Program Output" } ]
Locating multiple elements in Selenium Python
20 Apr, 2020 Locators Strategies in Selenium Python are methods that are used to locate single or multiple elements from the page and perform operations on the same. Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. After one has installed selenium and checked out – Navigating links using get method, one might want to play more with Selenium Python. After opening page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. This article revolves around Locating multiple elements in Selenium Python. Selenium Python follows different locating strategies for elements. One can locate multiple elements in 7 different ways. Here is a list of locating strategies for Selenium in python – With this strategy, all elements with the name attribute value matching the location will be returned. If no element has a matching name attribute, a NoSuchElementException will be raised. driver.find_elements_by_name("name_of_element") Example –For instance, consider this page source: <html> <body> <form id="loginForm"> <input name="username" type="text" /> <input name="username" type="username" /> <input name="continue" type="submit" value="Login" /> </form> </body><html> Now after you have created a driver, you can grab elements using – elements = driver.find_elements_by_name('username') To check practical Implementation, visit – find_elements_by_name() driver method – Selenium Python With this strategy, all elements with pattern of xpath matching the location will be returned. If no element has a matching element attribute, a NoSuchElementException will be raised. driver.find_elements_by_xpath("xpath") Example –For instance, consider this page source: <html> <body> <form id="loginForm"> <input name="username" type="text" /> <input name="password" type="password" /> <input name="continue" type="submit" value="Login" /> </form> </body><html> Now after you have created a driver, you can grab elements using – login_form = driver.find_elements_by_xpath("/html/body/form[1]") login_form = driver.find_elements_by_xpath("//form[1]") To check Practical Implementation, visit – find_elements_by_xpath() driver method – Selenium Python With this strategy, all elements with the link text value matching the location will be returned. If no element has a matching link text attribute, a NoSuchElementException will be raised. driver.find_elements_by_link_text("Text of Link") Example –For instance, consider this page source: <html> <body> <p>Are you sure you want to do this?</p> <a href="continue.html">Continue</a> <a href="cancel.html">Cancel</a></body><html> Now after you have created a driver, you can grab elements using – login_form = driver.find_elements_by_link_text('Continue') To check practical Implementation, visit – find_elements_by_link_text() driver method – Selenium Python With this strategy, all elements with the partial link text value matching the location will be returned. If no element has a matching partial link text attribute, a NoSuchElementException will be raised. driver.find_elements_by_partial_link_text("Text of Link") Example –For instance, consider this page source: <html> <body> <p>Are you sure you want to do this?</p> <a href="continue.html">Continue</a> <a href="cancel.html">Cancel</a></body><html> Now after you have created a driver, you can grab all elements using – login_form = driver.find_elements_by_partial_link_text('Conti') To check practical implementation, visit – find_elements_by_partial_link_text() driver method – Selenium Python With this strategy, all elements with the given tag name will be returned. If no element has a matching tag name, a NoSuchElementException will be raised. driver.find_elements_by_tag_name("Tag name") Example –For instance, consider this page source: <html> <body> <h1>Welcome</h1> <p>Site content goes here.</p></body><html> Now after you have created a driver, you can grab all elements using – login_form = driver.find_elements_by_tag_name('h1') To check practical Implementation, visit – find_elements_by_tag_name() driver method – Selenium Python With this strategy, the first elements with the matching class attribute name will be returned. If no element has a matching class attribute name, a NoSuchElementException will be raised. driver.find_elements_by_class_name("class_of_element") Example –For instance, consider this page source: <html> <body> <p class="content">Site content goes here.</p></body><html> Now after you have created a driver, you can grab all elements using – content = driver.find_elements_by_class_name('content') To check practical Implementation, visit – find_elements_by_class_name() driver method – Selenium Python With this strategy, all elements with the matching CSS selector will be returned. If no element has a matching CSS selector, a NoSuchElementException will be raised. driver.find_elements_by_css_selector("CSS Selectors") Example –For instance, consider this page source: <html> <body> <p class="content">Site content goes here.</p></body><html> Now after you have created a driver, you can grab all elements using – content = driver.find_elements_by_css_selector('p.content') To check practical implementation, visit – find_elements_by_css_selector() driver method – Selenium Python Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe 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 ? Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Apr, 2020" }, { "code": null, "e": 744, "s": 28, "text": "Locators Strategies in Selenium Python are methods that are used to locate single or multiple elements from the page and perform operations on the same. Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. After one has installed selenium and checked out – Navigating links using get method, one might want to play more with Selenium Python. After opening page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. This article revolves around Locating multiple elements in Selenium Python." }, { "code": null, "e": 929, "s": 744, "text": "Selenium Python follows different locating strategies for elements. One can locate multiple elements in 7 different ways. Here is a list of locating strategies for Selenium in python –" }, { "code": null, "e": 1118, "s": 929, "text": "With this strategy, all elements with the name attribute value matching the location will be returned. If no element has a matching name attribute, a NoSuchElementException will be raised." }, { "code": null, "e": 1167, "s": 1118, "text": "driver.find_elements_by_name(\"name_of_element\")\n" }, { "code": null, "e": 1217, "s": 1167, "text": "Example –For instance, consider this page source:" }, { "code": "<html> <body> <form id=\"loginForm\"> <input name=\"username\" type=\"text\" /> <input name=\"username\" type=\"username\" /> <input name=\"continue\" type=\"submit\" value=\"Login\" /> </form> </body><html>", "e": 1417, "s": 1217, "text": null }, { "code": null, "e": 1484, "s": 1417, "text": "Now after you have created a driver, you can grab elements using –" }, { "code": null, "e": 1537, "s": 1484, "text": "elements = driver.find_elements_by_name('username')\n" }, { "code": null, "e": 1636, "s": 1537, "text": "To check practical Implementation, visit – find_elements_by_name() driver method – Selenium Python" }, { "code": null, "e": 1820, "s": 1636, "text": "With this strategy, all elements with pattern of xpath matching the location will be returned. If no element has a matching element attribute, a NoSuchElementException will be raised." }, { "code": null, "e": 1860, "s": 1820, "text": "driver.find_elements_by_xpath(\"xpath\")\n" }, { "code": null, "e": 1910, "s": 1860, "text": "Example –For instance, consider this page source:" }, { "code": "<html> <body> <form id=\"loginForm\"> <input name=\"username\" type=\"text\" /> <input name=\"password\" type=\"password\" /> <input name=\"continue\" type=\"submit\" value=\"Login\" /> </form> </body><html>", "e": 2110, "s": 1910, "text": null }, { "code": null, "e": 2177, "s": 2110, "text": "Now after you have created a driver, you can grab elements using –" }, { "code": null, "e": 2299, "s": 2177, "text": "login_form = driver.find_elements_by_xpath(\"/html/body/form[1]\")\nlogin_form = driver.find_elements_by_xpath(\"//form[1]\")\n" }, { "code": null, "e": 2399, "s": 2299, "text": "To check Practical Implementation, visit – find_elements_by_xpath() driver method – Selenium Python" }, { "code": null, "e": 2588, "s": 2399, "text": "With this strategy, all elements with the link text value matching the location will be returned. If no element has a matching link text attribute, a NoSuchElementException will be raised." }, { "code": null, "e": 2639, "s": 2588, "text": "driver.find_elements_by_link_text(\"Text of Link\")\n" }, { "code": null, "e": 2689, "s": 2639, "text": "Example –For instance, consider this page source:" }, { "code": "<html> <body> <p>Are you sure you want to do this?</p> <a href=\"continue.html\">Continue</a> <a href=\"cancel.html\">Cancel</a></body><html>", "e": 2830, "s": 2689, "text": null }, { "code": null, "e": 2897, "s": 2830, "text": "Now after you have created a driver, you can grab elements using –" }, { "code": null, "e": 2957, "s": 2897, "text": "login_form = driver.find_elements_by_link_text('Continue')\n" }, { "code": null, "e": 3061, "s": 2957, "text": "To check practical Implementation, visit – find_elements_by_link_text() driver method – Selenium Python" }, { "code": null, "e": 3266, "s": 3061, "text": "With this strategy, all elements with the partial link text value matching the location will be returned. If no element has a matching partial link text attribute, a NoSuchElementException will be raised." }, { "code": null, "e": 3325, "s": 3266, "text": "driver.find_elements_by_partial_link_text(\"Text of Link\")\n" }, { "code": null, "e": 3375, "s": 3325, "text": "Example –For instance, consider this page source:" }, { "code": "<html> <body> <p>Are you sure you want to do this?</p> <a href=\"continue.html\">Continue</a> <a href=\"cancel.html\">Cancel</a></body><html>", "e": 3516, "s": 3375, "text": null }, { "code": null, "e": 3587, "s": 3516, "text": "Now after you have created a driver, you can grab all elements using –" }, { "code": null, "e": 3652, "s": 3587, "text": "login_form = driver.find_elements_by_partial_link_text('Conti')\n" }, { "code": null, "e": 3764, "s": 3652, "text": "To check practical implementation, visit – find_elements_by_partial_link_text() driver method – Selenium Python" }, { "code": null, "e": 3919, "s": 3764, "text": "With this strategy, all elements with the given tag name will be returned. If no element has a matching tag name, a NoSuchElementException will be raised." }, { "code": null, "e": 3965, "s": 3919, "text": "driver.find_elements_by_tag_name(\"Tag name\")\n" }, { "code": null, "e": 4015, "s": 3965, "text": "Example –For instance, consider this page source:" }, { "code": "<html> <body> <h1>Welcome</h1> <p>Site content goes here.</p></body><html>", "e": 4092, "s": 4015, "text": null }, { "code": null, "e": 4163, "s": 4092, "text": "Now after you have created a driver, you can grab all elements using –" }, { "code": null, "e": 4216, "s": 4163, "text": "login_form = driver.find_elements_by_tag_name('h1')\n" }, { "code": null, "e": 4319, "s": 4216, "text": "To check practical Implementation, visit – find_elements_by_tag_name() driver method – Selenium Python" }, { "code": null, "e": 4507, "s": 4319, "text": "With this strategy, the first elements with the matching class attribute name will be returned. If no element has a matching class attribute name, a NoSuchElementException will be raised." }, { "code": null, "e": 4563, "s": 4507, "text": "driver.find_elements_by_class_name(\"class_of_element\")\n" }, { "code": null, "e": 4613, "s": 4563, "text": "Example –For instance, consider this page source:" }, { "code": "<html> <body> <p class=\"content\">Site content goes here.</p></body><html>", "e": 4688, "s": 4613, "text": null }, { "code": null, "e": 4759, "s": 4688, "text": "Now after you have created a driver, you can grab all elements using –" }, { "code": null, "e": 4816, "s": 4759, "text": "content = driver.find_elements_by_class_name('content')\n" }, { "code": null, "e": 4921, "s": 4816, "text": "To check practical Implementation, visit – find_elements_by_class_name() driver method – Selenium Python" }, { "code": null, "e": 5087, "s": 4921, "text": "With this strategy, all elements with the matching CSS selector will be returned. If no element has a matching CSS selector, a NoSuchElementException will be raised." }, { "code": null, "e": 5142, "s": 5087, "text": "driver.find_elements_by_css_selector(\"CSS Selectors\")\n" }, { "code": null, "e": 5192, "s": 5142, "text": "Example –For instance, consider this page source:" }, { "code": "<html> <body> <p class=\"content\">Site content goes here.</p></body><html>", "e": 5267, "s": 5192, "text": null }, { "code": null, "e": 5338, "s": 5267, "text": "Now after you have created a driver, you can grab all elements using –" }, { "code": null, "e": 5399, "s": 5338, "text": "content = driver.find_elements_by_css_selector('p.content')\n" }, { "code": null, "e": 5506, "s": 5399, "text": "To check practical implementation, visit – find_elements_by_css_selector() driver method – Selenium Python" }, { "code": null, "e": 5522, "s": 5506, "text": "Python-selenium" }, { "code": null, "e": 5531, "s": 5522, "text": "selenium" }, { "code": null, "e": 5538, "s": 5531, "text": "Python" }, { "code": null, "e": 5636, "s": 5538, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5664, "s": 5636, "text": "Read JSON file using Python" }, { "code": null, "e": 5714, "s": 5664, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 5736, "s": 5714, "text": "Python map() function" }, { "code": null, "e": 5780, "s": 5736, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 5822, "s": 5780, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5844, "s": 5822, "text": "Enumerate() in Python" }, { "code": null, "e": 5879, "s": 5844, "text": "Read a file line by line in Python" }, { "code": null, "e": 5905, "s": 5879, "text": "Python String | replace()" }, { "code": null, "e": 5937, "s": 5905, "text": "How to Install PIP on Windows ?" } ]
Set Position with seekg() in C++ File Handling
05 Apr, 2022 seekg() is a function in the iostream library that allows you to seek an arbitrary position in a file. It is included in the <fstream> header file and is defined for istream class. It is used in file handling to sets the position of the next character to be extracted from the input stream from a given file. Syntax: There are two syntaxes for seekg() in file handling, istream&seekg(streampos position); or istream&seekg(streamoff offset, ios_base::seekdir dir); Parameters: position: is the new position in the stream buffer. offset: is an integer value of type streamoff representing the offset in the stream’s buffer. It is relative to the dir parameter. dir: It is the seeking direction. It is an object of type ios_base::seekdir that can take any of the following constant values. There are 3 directions we use for offset value: ios_base::beg: offset from the beginning of the stream’s buffer. ios_base::cur: offset from the current position in the stream’s buffer. ios_base::end: offset from the end of the stream’s buffer. Let’s understand through an example, If we take the following input, Input : "Hello World" and seek to 6th position from the beginning of the file myFile.seekg(6, ios::beg); and read the next 5 characters from the file into a buffer, char A[6]; myFile.read(A, 5); then the output will be, Output : World Algorithm for the Above Example: Open a new file for input/output operations, discarding any current in the file (assume a length of zero on opening). Add the characters “Hello World” to the file. Seek to 6 characters from the beginning of the file. Read the next 5 characters from the file into the buffer. End the buffer with a null terminating character. Output the contents read from the file and close it. Program: CPP // CPP Program to demonstrate the// seekg function in file// handling#include <fstream>#include <iostream>using namespace std; // Driver Codeint main(int argc, char** argv){ // Open a new file for input/output operations fstream myFile("test.txt", ios::in | ios::out | ios::trunc); // Add the characters "Hello World" to the file myFile << "Hello World"; // Seek to 6 characters from the beginning of the file myFile.seekg(6, ios::beg); // Read the next 5 characters from the file into a // buffer char A[6]; myFile.read(A, 5); // End the buffer with a null terminating character A[5] = 0; // Output the contents read from the file and close it cout << A << endl; myFile.close();} Output: World Note: If we previously get an end of file on the stream, seekg will not reset it but will return an error in many implementations. Use the clear() method to clear the end of file bit first. This is a relatively common mistake and if seekg() is not performing as expected. This article is contributed by Shivani Baghel. 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. kmcewan25 anshikajain26 simranarora5sos cpp-file-handling CPP-Library C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ Substring in C++ unordered_map in C++ STL Priority Queue in C++ Standard Template Library (STL) Object Oriented Programming in C++ The C++ Standard Template Library (STL) Sorting a vector in C++ 2D Vector In C++ With User Defined Size
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Apr, 2022" }, { "code": null, "e": 362, "s": 52, "text": "seekg() is a function in the iostream library that allows you to seek an arbitrary position in a file. It is included in the <fstream> header file and is defined for istream class. It is used in file handling to sets the position of the next character to be extracted from the input stream from a given file. " }, { "code": null, "e": 424, "s": 362, "text": "Syntax: There are two syntaxes for seekg() in file handling, " }, { "code": null, "e": 459, "s": 424, "text": "istream&seekg(streampos position);" }, { "code": null, "e": 462, "s": 459, "text": "or" }, { "code": null, "e": 518, "s": 462, "text": "istream&seekg(streamoff offset, ios_base::seekdir dir);" }, { "code": null, "e": 530, "s": 518, "text": "Parameters:" }, { "code": null, "e": 582, "s": 530, "text": "position: is the new position in the stream buffer." }, { "code": null, "e": 713, "s": 582, "text": "offset: is an integer value of type streamoff representing the offset in the stream’s buffer. It is relative to the dir parameter." }, { "code": null, "e": 841, "s": 713, "text": "dir: It is the seeking direction. It is an object of type ios_base::seekdir that can take any of the following constant values." }, { "code": null, "e": 889, "s": 841, "text": "There are 3 directions we use for offset value:" }, { "code": null, "e": 954, "s": 889, "text": "ios_base::beg: offset from the beginning of the stream’s buffer." }, { "code": null, "e": 1026, "s": 954, "text": "ios_base::cur: offset from the current position in the stream’s buffer." }, { "code": null, "e": 1085, "s": 1026, "text": "ios_base::end: offset from the end of the stream’s buffer." }, { "code": null, "e": 1122, "s": 1085, "text": "Let’s understand through an example," }, { "code": null, "e": 1154, "s": 1122, "text": "If we take the following input," }, { "code": null, "e": 1176, "s": 1154, "text": "Input : \"Hello World\"" }, { "code": null, "e": 1232, "s": 1176, "text": "and seek to 6th position from the beginning of the file" }, { "code": null, "e": 1260, "s": 1232, "text": " myFile.seekg(6, ios::beg);" }, { "code": null, "e": 1321, "s": 1260, "text": "and read the next 5 characters from the file into a buffer, " }, { "code": null, "e": 1351, "s": 1321, "text": "char A[6];\nmyFile.read(A, 5);" }, { "code": null, "e": 1376, "s": 1351, "text": "then the output will be," }, { "code": null, "e": 1391, "s": 1376, "text": "Output : World" }, { "code": null, "e": 1424, "s": 1391, "text": "Algorithm for the Above Example:" }, { "code": null, "e": 1542, "s": 1424, "text": "Open a new file for input/output operations, discarding any current in the file (assume a length of zero on opening)." }, { "code": null, "e": 1588, "s": 1542, "text": "Add the characters “Hello World” to the file." }, { "code": null, "e": 1641, "s": 1588, "text": "Seek to 6 characters from the beginning of the file." }, { "code": null, "e": 1699, "s": 1641, "text": "Read the next 5 characters from the file into the buffer." }, { "code": null, "e": 1749, "s": 1699, "text": "End the buffer with a null terminating character." }, { "code": null, "e": 1802, "s": 1749, "text": "Output the contents read from the file and close it." }, { "code": null, "e": 1811, "s": 1802, "text": "Program:" }, { "code": null, "e": 1815, "s": 1811, "text": "CPP" }, { "code": "// CPP Program to demonstrate the// seekg function in file// handling#include <fstream>#include <iostream>using namespace std; // Driver Codeint main(int argc, char** argv){ // Open a new file for input/output operations fstream myFile(\"test.txt\", ios::in | ios::out | ios::trunc); // Add the characters \"Hello World\" to the file myFile << \"Hello World\"; // Seek to 6 characters from the beginning of the file myFile.seekg(6, ios::beg); // Read the next 5 characters from the file into a // buffer char A[6]; myFile.read(A, 5); // End the buffer with a null terminating character A[5] = 0; // Output the contents read from the file and close it cout << A << endl; myFile.close();}", "e": 2565, "s": 1815, "text": null }, { "code": null, "e": 2573, "s": 2565, "text": "Output:" }, { "code": null, "e": 2579, "s": 2573, "text": "World" }, { "code": null, "e": 2851, "s": 2579, "text": "Note: If we previously get an end of file on the stream, seekg will not reset it but will return an error in many implementations. Use the clear() method to clear the end of file bit first. This is a relatively common mistake and if seekg() is not performing as expected." }, { "code": null, "e": 3275, "s": 2851, "text": "This article is contributed by Shivani Baghel. 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": 3285, "s": 3275, "text": "kmcewan25" }, { "code": null, "e": 3299, "s": 3285, "text": "anshikajain26" }, { "code": null, "e": 3315, "s": 3299, "text": "simranarora5sos" }, { "code": null, "e": 3333, "s": 3315, "text": "cpp-file-handling" }, { "code": null, "e": 3345, "s": 3333, "text": "CPP-Library" }, { "code": null, "e": 3349, "s": 3345, "text": "C++" }, { "code": null, "e": 3353, "s": 3349, "text": "CPP" }, { "code": null, "e": 3451, "s": 3353, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3478, "s": 3451, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 3521, "s": 3478, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 3555, "s": 3521, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 3572, "s": 3555, "text": "Substring in C++" }, { "code": null, "e": 3597, "s": 3572, "text": "unordered_map in C++ STL" }, { "code": null, "e": 3651, "s": 3597, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 3686, "s": 3651, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 3726, "s": 3686, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 3750, "s": 3726, "text": "Sorting a vector in C++" } ]
Condition To Print “HelloWorld”
21 Feb, 2022 What should be the “condition” so that the following code snippet prints both HelloWorld! if "condition" printf ("Hello"); else printf("World"); Method 1: c #include<stdio.h>int main(){ if(!printf("Hello")) printf("Hello"); else printf("World"); getchar();} Explanation: Printf returns the number of character it has printed successfully. So, following solutions will also workif (printf(“Hello”) < 0) or if (printf(“Hello”) < 1) etc Method 2: Using fork() c #include<stdio.h>#include<unistd.h>int main(){ if(fork()) printf("Hello"); else printf("World"); getchar();} This method is contributed by Aravind Alapati.Please comment if you find more solutions of this. sagar0719kumar c-puzzle C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Feb, 2022" }, { "code": null, "e": 142, "s": 52, "text": "What should be the “condition” so that the following code snippet prints both HelloWorld!" }, { "code": null, "e": 233, "s": 144, "text": " if \"condition\"\n printf (\"Hello\");\n else\n printf(\"World\"); " }, { "code": null, "e": 245, "s": 233, "text": "Method 1: " }, { "code": null, "e": 247, "s": 245, "text": "c" }, { "code": "#include<stdio.h>int main(){ if(!printf(\"Hello\")) printf(\"Hello\"); else printf(\"World\"); getchar();} ", "e": 378, "s": 247, "text": null }, { "code": null, "e": 579, "s": 378, "text": "Explanation: Printf returns the number of character it has printed successfully. So, following solutions will also workif (printf(“Hello”) < 0) or if (printf(“Hello”) < 1) etc Method 2: Using fork() " }, { "code": null, "e": 581, "s": 579, "text": "c" }, { "code": "#include<stdio.h>#include<unistd.h>int main(){ if(fork()) printf(\"Hello\"); else printf(\"World\"); getchar();} ", "e": 720, "s": 581, "text": null }, { "code": null, "e": 818, "s": 720, "text": "This method is contributed by Aravind Alapati.Please comment if you find more solutions of this. " }, { "code": null, "e": 833, "s": 818, "text": "sagar0719kumar" }, { "code": null, "e": 842, "s": 833, "text": "c-puzzle" }, { "code": null, "e": 853, "s": 842, "text": "C Language" }, { "code": null, "e": 857, "s": 853, "text": "C++" }, { "code": null, "e": 861, "s": 857, "text": "CPP" }, { "code": null, "e": 959, "s": 861, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 976, "s": 959, "text": "Substring in C++" }, { "code": null, "e": 998, "s": 976, "text": "Function Pointer in C" }, { "code": null, "e": 1044, "s": 998, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 1089, "s": 1044, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 1114, "s": 1089, "text": "std::string class in C++" }, { "code": null, "e": 1132, "s": 1114, "text": "Vector in C++ STL" }, { "code": null, "e": 1175, "s": 1132, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 1221, "s": 1175, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 1264, "s": 1221, "text": "Set in C++ Standard Template Library (STL)" } ]
Program to format a number with thousands separator in C/C++
31 Oct, 2020 Given an integer N, the task is to print output of the given integer in international place value format and put commas at the appropriate place, from the right. Examples Input: N = 47634Output: 47, 634 Input: N = 1000000Output : 1, 000, 000 Approach: Follow the steps below to solve the problem: Convert the given integer N to its equivalent string.Iterate over the characters of the given string from the right to the left.After traversing every 3 characters, insert a ‘,’ separator. Convert the given integer N to its equivalent string. Iterate over the characters of the given string from the right to the left. After traversing every 3 characters, insert a ‘,’ separator. Below is the implementation of the above approach: C++ // C++ program to implement the// above approach #include <bits/stdc++.h>using namespace std; // Function to put thousands// separators in the given integerstring thousandSeparator(int n){ string ans = ""; // Convert the given integer // to equivalent string string num = to_string(n); // Initialise count int count = 0; // Traverse the string in reverse for (int i = num.size() - 1; i >= 0; i--) { count++; ans.push_back(num[i]); // If three characters // are traversed if (count == 3) { ans.push_back(','); count = 0; } } // Reverse the string to get // the desired output reverse(ans.begin(), ans.end()); // If the given string is // less than 1000 if (ans.size() % 4 == 0) { // Remove ',' ans.erase(ans.begin()); } return ans;} // Driver Codeint main(){ int N = 47634; string s = thousandSeparator(N); cout << s << endl;} 47,634 Time Complexity: O(log10N)Auxiliary Space: O(1) Mathematical School Programming Strings Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Find next greater number with same set of digits Segment Tree | Set 1 (Sum of given range) Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2020" }, { "code": null, "e": 190, "s": 28, "text": "Given an integer N, the task is to print output of the given integer in international place value format and put commas at the appropriate place, from the right." }, { "code": null, "e": 199, "s": 190, "text": "Examples" }, { "code": null, "e": 231, "s": 199, "text": "Input: N = 47634Output: 47, 634" }, { "code": null, "e": 270, "s": 231, "text": "Input: N = 1000000Output : 1, 000, 000" }, { "code": null, "e": 325, "s": 270, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 514, "s": 325, "text": "Convert the given integer N to its equivalent string.Iterate over the characters of the given string from the right to the left.After traversing every 3 characters, insert a ‘,’ separator." }, { "code": null, "e": 568, "s": 514, "text": "Convert the given integer N to its equivalent string." }, { "code": null, "e": 644, "s": 568, "text": "Iterate over the characters of the given string from the right to the left." }, { "code": null, "e": 705, "s": 644, "text": "After traversing every 3 characters, insert a ‘,’ separator." }, { "code": null, "e": 756, "s": 705, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 760, "s": 756, "text": "C++" }, { "code": "// C++ program to implement the// above approach #include <bits/stdc++.h>using namespace std; // Function to put thousands// separators in the given integerstring thousandSeparator(int n){ string ans = \"\"; // Convert the given integer // to equivalent string string num = to_string(n); // Initialise count int count = 0; // Traverse the string in reverse for (int i = num.size() - 1; i >= 0; i--) { count++; ans.push_back(num[i]); // If three characters // are traversed if (count == 3) { ans.push_back(','); count = 0; } } // Reverse the string to get // the desired output reverse(ans.begin(), ans.end()); // If the given string is // less than 1000 if (ans.size() % 4 == 0) { // Remove ',' ans.erase(ans.begin()); } return ans;} // Driver Codeint main(){ int N = 47634; string s = thousandSeparator(N); cout << s << endl;}", "e": 1751, "s": 760, "text": null }, { "code": null, "e": 1759, "s": 1751, "text": "47,634\n" }, { "code": null, "e": 1807, "s": 1759, "text": "Time Complexity: O(log10N)Auxiliary Space: O(1)" }, { "code": null, "e": 1820, "s": 1807, "text": "Mathematical" }, { "code": null, "e": 1839, "s": 1820, "text": "School Programming" }, { "code": null, "e": 1847, "s": 1839, "text": "Strings" }, { "code": null, "e": 1855, "s": 1847, "text": "Strings" }, { "code": null, "e": 1868, "s": 1855, "text": "Mathematical" }, { "code": null, "e": 1966, "s": 1868, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1998, "s": 1966, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 2044, "s": 1998, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 2088, "s": 2044, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 2137, "s": 2088, "text": "Find next greater number with same set of digits" }, { "code": null, "e": 2179, "s": 2137, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 2197, "s": 2179, "text": "Python Dictionary" }, { "code": null, "e": 2222, "s": 2197, "text": "Reverse a string in Java" }, { "code": null, "e": 2238, "s": 2222, "text": "Arrays in C/C++" }, { "code": null, "e": 2261, "s": 2238, "text": "Introduction To PYTHON" } ]
Python – Dictionaries with Unique Value Lists
30 Aug, 2020 Given List of dictionaries with list values, extract unique dictionaries. Input : [{‘Gfg’: [2, 3], ‘is’ : [7, 8], ‘best’ : [10]}, {‘Gfg’: [2, 3], ‘is’ : [7, 8], ‘best’ : [10]}]Output : [{‘Gfg’: [2, 3], ‘is’: [7, 8], ‘best’: [10]}]Explanation : Both are similar dictionaries, and hence 1 is removed. Input : [{‘Gfg’: [2, 3], ‘is’ : [7, 8], ‘best’ : [10]}, {‘Gfg’: [2, 3], ‘is’ : [7, 8], ‘best’ : [10, 11]}]Output : [{‘Gfg’: [2, 3], ‘is’: [7, 8], ‘best’: [10]}, {‘Gfg’: [2, 3], ‘is’: [7, 8], ‘best’: [10, 11]}]Explanation : None duplicate. Method #1 : Using loop This is one of the ways in which this task can be performed. In this, we iterate for each dictionary and memoize it, and prevent it from adding to result. Python3 # Python3 code to demonstrate working of # Unique Value Lists Dictionaries# Using loop # initializing liststest_list = [{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}, {'Gfg': [2, 3], 'is' : [7], 'best' : [10]}, {'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}] # printing original listprint("The original list : " + str(test_list)) # Using loop to iterate through elements# result array to also keep track of already occurred elementsres = []for sub in test_list: if sub not in res: res.append(sub) # printing result print("List after duplicates removal : " + str(res)) The original list : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}, {'Gfg': [2, 3], 'is': [7], 'best': [10]}, {'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}] List after duplicates removal : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}, {'Gfg': [2, 3], 'is': [7], 'best': [10]}] Method #2 : Using list comprehension This is yet another way in which this task can be performed. In this, similar approach is employed as above, just the difference of encapsulating result in list comprehension for one-liner. Python3 # Python3 code to demonstrate working of # Unique Value Lists Dictionaries# Using list comprehension # initializing liststest_list = [{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}, {'Gfg': [2, 3], 'is' : [7], 'best' : [10]}, {'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}] # printing original listprint("The original list : " + str(test_list)) # list comprehension to encapsulate logic in one linerres = [][res.append(val) for val in test_list if val not in res] # printing result print("List after duplicates removal : " + str(res)) The original list : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}, {'Gfg': [2, 3], 'is': [7], 'best': [10]}, {'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}] List after duplicates removal : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}, {'Gfg': [2, 3], 'is': [7], 'best': [10]}] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Aug, 2020" }, { "code": null, "e": 102, "s": 28, "text": "Given List of dictionaries with list values, extract unique dictionaries." }, { "code": null, "e": 327, "s": 102, "text": "Input : [{‘Gfg’: [2, 3], ‘is’ : [7, 8], ‘best’ : [10]}, {‘Gfg’: [2, 3], ‘is’ : [7, 8], ‘best’ : [10]}]Output : [{‘Gfg’: [2, 3], ‘is’: [7, 8], ‘best’: [10]}]Explanation : Both are similar dictionaries, and hence 1 is removed." }, { "code": null, "e": 566, "s": 327, "text": "Input : [{‘Gfg’: [2, 3], ‘is’ : [7, 8], ‘best’ : [10]}, {‘Gfg’: [2, 3], ‘is’ : [7, 8], ‘best’ : [10, 11]}]Output : [{‘Gfg’: [2, 3], ‘is’: [7, 8], ‘best’: [10]}, {‘Gfg’: [2, 3], ‘is’: [7, 8], ‘best’: [10, 11]}]Explanation : None duplicate." }, { "code": null, "e": 589, "s": 566, "text": "Method #1 : Using loop" }, { "code": null, "e": 745, "s": 589, "text": "This is one of the ways in which this task can be performed. In this, we iterate for each dictionary and memoize it, and prevent it from adding to result. " }, { "code": null, "e": 753, "s": 745, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Unique Value Lists Dictionaries# Using loop # initializing liststest_list = [{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}, {'Gfg': [2, 3], 'is' : [7], 'best' : [10]}, {'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}] # printing original listprint(\"The original list : \" + str(test_list)) # Using loop to iterate through elements# result array to also keep track of already occurred elementsres = []for sub in test_list: if sub not in res: res.append(sub) # printing result print(\"List after duplicates removal : \" + str(res))", "e": 1363, "s": 753, "text": null }, { "code": null, "e": 1637, "s": 1363, "text": "The original list : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}, {'Gfg': [2, 3], 'is': [7], 'best': [10]}, {'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}]\nList after duplicates removal : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}, {'Gfg': [2, 3], 'is': [7], 'best': [10]}]\n" }, { "code": null, "e": 1674, "s": 1637, "text": "Method #2 : Using list comprehension" }, { "code": null, "e": 1865, "s": 1674, "text": "This is yet another way in which this task can be performed. In this, similar approach is employed as above, just the difference of encapsulating result in list comprehension for one-liner. " }, { "code": null, "e": 1873, "s": 1865, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Unique Value Lists Dictionaries# Using list comprehension # initializing liststest_list = [{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}, {'Gfg': [2, 3], 'is' : [7], 'best' : [10]}, {'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}] # printing original listprint(\"The original list : \" + str(test_list)) # list comprehension to encapsulate logic in one linerres = [][res.append(val) for val in test_list if val not in res] # printing result print(\"List after duplicates removal : \" + str(res))", "e": 2439, "s": 1873, "text": null }, { "code": null, "e": 2713, "s": 2439, "text": "The original list : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}, {'Gfg': [2, 3], 'is': [7], 'best': [10]}, {'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}]\nList after duplicates removal : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}, {'Gfg': [2, 3], 'is': [7], 'best': [10]}]\n" }, { "code": null, "e": 2734, "s": 2713, "text": "Python list-programs" }, { "code": null, "e": 2741, "s": 2734, "text": "Python" }, { "code": null, "e": 2757, "s": 2741, "text": "Python Programs" }, { "code": null, "e": 2855, "s": 2757, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2873, "s": 2855, "text": "Python Dictionary" }, { "code": null, "e": 2915, "s": 2873, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2941, "s": 2915, "text": "Python String | replace()" }, { "code": null, "e": 2973, "s": 2941, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3002, "s": 2973, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3045, "s": 3002, "text": "Python program to convert a list to string" }, { "code": null, "e": 3067, "s": 3045, "text": "Defaultdict in Python" }, { "code": null, "e": 3106, "s": 3067, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3144, "s": 3106, "text": "Python | Convert a list to dictionary" } ]
Learning Model Building in Scikit-learn : A Python Machine Learning Library
08 Jul, 2022 Pre-requisite: Getting started with machine learning scikit-learn is an open-source Python library that implements a range of machine learning, pre-processing, cross-validation, and visualization algorithms using a unified interface. Important features of scikit-learn: Simple and efficient tools for data mining and data analysis. It features various classification, regression and clustering algorithms including support vector machines, random forests, gradient boosting, k-means, etc. Accessible to everybody and reusable in various contexts. Built on the top of NumPy, SciPy, and matplotlib. Open source, commercially usable – BSD license. In this article, we are going to see how we can easily build a machine learning model using scikit-learn. Installation: Scikit-learn requires: NumPy SciPy as its dependencies. Before installing scikit-learn, ensure that you have NumPy and SciPy installed. Once you have a working installation of NumPy and SciPy, the easiest way to install scikit-learn is using pip: pip install -U scikit-learn Let us get started with the modeling process now. Step 1: Load a dataset A dataset is nothing but a collection of data. A dataset generally has two main components: Features: (also known as predictors, inputs, or attributes) they are simply the variables of our data. They can be more than one and hence represented by a feature matrix (‘X’ is a common notation to represent feature matrix). A list of all the feature names is termed feature names. Response: (also known as the target, label, or output) This is the output variable depending on the feature variables. We generally have a single response column and it is represented by a response vector (‘y’ is a common notation to represent response vector). All the possible values taken by a response vector are termed target names. Loading exemplar dataset: scikit-learn comes loaded with a few example datasets like the iris and digits datasets for classification and the boston house prices dataset for regression. Given below is an example of how one can load an exemplar dataset: Python # load the iris dataset as an example from sklearn.datasets import load_iris iris = load_iris() # store the feature matrix (X) and response vector (y) X = iris.data y = iris.target # store the feature and target names feature_names = iris.feature_names target_names = iris.target_names # printing features and target names of our dataset print("Feature names:", feature_names) print("Target names:", target_names) # X and y are numpy arrays print("\nType of X is:", type(X)) # printing first 5 input rows print("\nFirst 5 rows of X:\n", X[:5]) Output: Feature names: ['sepal length (cm)','sepal width (cm)', 'petal length (cm)','petal width (cm)'] Target names: ['setosa' 'versicolor' 'virginica'] Type of X is: First 5 rows of X: [[ 5.1 3.5 1.4 0.2] [ 4.9 3. 1.4 0.2] [ 4.7 3.2 1.3 0.2] [ 4.6 3.1 1.5 0.2] [ 5. 3.6 1.4 0.2]] Loading external dataset: Now, consider the case when we want to load an external dataset. For this purpose, we can use the pandas library for easily loading and manipulating datasets. To install pandas, use the following pip command: pip install pandas In pandas, important data types are:Series: Series is a one-dimensional labeled array capable of holding any data type. DataFrame: It is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects. It is generally the most commonly used pandas object.Note: The CSV file used in the example below can be downloaded from here: weather.csv Python import pandas as pd # reading csv file data = pd.read_csv('weather.csv') # shape of dataset print("Shape:", data.shape) # column names print("\nFeatures:", data.columns) # storing the feature matrix (X) and response vector (y) X = data[data.columns[:-1]] y = data[data.columns[-1]] # printing first 5 rows of feature matrix print("\nFeature matrix:\n", X.head()) # printing first 5 values of response vector print("\nResponse vector:\n", y.head()) Output: Shape: (14, 5) Features: Index([u'Outlook', u'Temperature', u'Humidity', u'Windy', u'Play'], dtype='object') Feature matrix: Outlook Temperature Humidity Windy 0 overcast hot high False 1 overcast cool normal True 2 overcast mild high True 3 overcast hot normal False 4 rainy mild high False Response vector: 0 yes 1 yes 2 yes 3 yes 4 yes Name: Play, dtype: object Step 2: Splitting the datasetOne important aspect of all machine learning models is to determine their accuracy. Now, in order to determine their accuracy, one can train the model using the given dataset and then predict the response values for the same dataset using that model and hence, find the accuracy of the model. But this method has several flaws in it, like: The goal is to estimate the likely performance of a model on out-of-sample data. Maximizing training accuracy rewards overly complex models that won’t necessarily generalize our model. Unnecessarily complex models may over-fit the training data. A better option is to split our data into two parts: the first one for training our machine learning model, and the second one for testing our model. To summarize: Split the dataset into two pieces: a training set and a testing set. Train the model on the training set. Test the model on the testing set, and evaluate how well our model did. Advantages of train/test split: The model can be trained and tested on different data than the one used for training. Response values are known for the test dataset, hence predictions can be evaluated Testing accuracy is a better estimate than training accuracy of out-of-sample performance. Consider the example below: Python # load the iris dataset as an examplefrom sklearn.datasets import load_irisiris = load_iris() # store the feature matrix (X) and response vector (y)X = iris.datay = iris.target # splitting X and y into training and testing setsfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1) # printing the shapes of the new X objectsprint(X_train.shape)print(X_test.shape) # printing the shapes of the new y objectsprint(y_train.shape)print(y_test.shape) Output: (90L, 4L) (60L, 4L) (90L,) (60L,) The train_test_split function takes several arguments which are explained below: X, y: These are the feature matrix and response vector which need to be split. test_size: It is the ratio of test data to the given data. For example, setting test_size = 0.4 for 150 rows of X produces test data of 150 x 0.4 = 60 rows. random_state: If you use random_state = some_number, then you can guarantee that your split will be always the same. This is useful if you want reproducible results, for example in testing for consistency in the documentation (so that everybody can see the same numbers). Step 3: Training the model Now, it’s time to train some prediction models using our dataset. Scikit-learn provides a wide range of machine learning algorithms that have a unified/consistent interface for fitting, predicting accuracy, etc.The example given below uses KNN (K nearest neighbors) classifier. Note: We will not go into the details of how the algorithm works as we are interested in understanding its implementation only. Now, consider the example below: Python # load the iris dataset as an examplefrom sklearn.datasets import load_irisiris = load_iris() # store the feature matrix (X) and response vector (y)X = iris.datay = iris.target # splitting X and y into training and testing setsfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1) # training the model on training setfrom sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors=3)knn.fit(X_train, y_train) # making predictions on the testing sety_pred = knn.predict(X_test) # comparing actual response values (y_test) with predicted response values (y_pred)from sklearn import metricsprint("kNN model accuracy:", metrics.accuracy_score(y_test, y_pred)) # making prediction for out of sample datasample = [[3, 5, 4, 2], [2, 3, 5, 4]]preds = knn.predict(sample)pred_species = [iris.target_names[p] for p in preds]print("Predictions:", pred_species) # saving the modelfrom sklearn.externals import joblibjoblib.dump(knn, 'iris_knn.pkl') Output: kNN model accuracy: 0.983333333333 Predictions: ['versicolor', 'virginica'] Important points to note from the above code: We create a knn classifier object using: knn = KNeighborsClassifier(n_neighbors=3) The classifier is trained using X_train data. The process is termed fitting. We pass the feature matrix and the corresponding response vector. knn.fit(X_train, y_train) Now, we need to test our classifier on the X_test data. knn.predict method is used for this purpose. It returns the predicted response vector, y_pred. y_pred = knn.predict(X_test) Now, we are interested in finding the accuracy of our model by comparing y_test and y_pred. This is done using the metrics module’s method accuracy_score: print(metrics.accuracy_score(y_test, y_pred)) Consider the case when you want your model to make predictions out of sample data. Then, the sample input can simply be passed in the same way as we pass any feature matrix. sample = [[3, 5, 4, 2], [2, 3, 5, 4]] preds = knn.predict(sample) If you are not interested in training your classifier again and again and using the pre-trained classifier, one can save their classifier using joblib. All you need to do is: joblib.dump(knn, 'iris_knn.pkl') In case you want to load an already saved classifier, use the following method: knn = joblib.load('iris_knn.pkl') As we approach the end of this article, here are some benefits of using scikit-learn over some other machine learning libraries(like R libraries): Consistent interface to machine learning models Provides many tuning parameters but with sensible defaults Exceptional documentation Rich set of functionality for companion tasks. Active community for development and support. References: http://scikit-learn.org/stable/documentation.html https://github.com/justmarkham/scikit-learn-videos This article is contributed by Nikhil Kumar. 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. ayushgangwar ArthTyagi punamsingh628700 Advanced Computer Subject Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial Docker - COPY Instruction How to Run a Python Script using Docker? ML | Monte Carlo Tree Search (MCTS) Copying Files to and from Docker Containers Agents in Artificial Intelligence Search Algorithms in AI Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Support Vector Machine Algorithm
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 286, "s": 52, "text": "Pre-requisite: Getting started with machine learning scikit-learn is an open-source Python library that implements a range of machine learning, pre-processing, cross-validation, and visualization algorithms using a unified interface." }, { "code": null, "e": 323, "s": 286, "text": "Important features of scikit-learn: " }, { "code": null, "e": 542, "s": 323, "text": "Simple and efficient tools for data mining and data analysis. It features various classification, regression and clustering algorithms including support vector machines, random forests, gradient boosting, k-means, etc." }, { "code": null, "e": 600, "s": 542, "text": "Accessible to everybody and reusable in various contexts." }, { "code": null, "e": 650, "s": 600, "text": "Built on the top of NumPy, SciPy, and matplotlib." }, { "code": null, "e": 698, "s": 650, "text": "Open source, commercially usable – BSD license." }, { "code": null, "e": 805, "s": 698, "text": "In this article, we are going to see how we can easily build a machine learning model using scikit-learn. " }, { "code": null, "e": 819, "s": 805, "text": "Installation:" }, { "code": null, "e": 844, "s": 819, "text": "Scikit-learn requires: " }, { "code": null, "e": 850, "s": 844, "text": "NumPy" }, { "code": null, "e": 877, "s": 850, "text": "SciPy as its dependencies." }, { "code": null, "e": 1069, "s": 877, "text": "Before installing scikit-learn, ensure that you have NumPy and SciPy installed. Once you have a working installation of NumPy and SciPy, the easiest way to install scikit-learn is using pip: " }, { "code": null, "e": 1097, "s": 1069, "text": "pip install -U scikit-learn" }, { "code": null, "e": 1147, "s": 1097, "text": "Let us get started with the modeling process now." }, { "code": null, "e": 1170, "s": 1147, "text": "Step 1: Load a dataset" }, { "code": null, "e": 1263, "s": 1170, "text": "A dataset is nothing but a collection of data. A dataset generally has two main components: " }, { "code": null, "e": 1547, "s": 1263, "text": "Features: (also known as predictors, inputs, or attributes) they are simply the variables of our data. They can be more than one and hence represented by a feature matrix (‘X’ is a common notation to represent feature matrix). A list of all the feature names is termed feature names." }, { "code": null, "e": 1885, "s": 1547, "text": "Response: (also known as the target, label, or output) This is the output variable depending on the feature variables. We generally have a single response column and it is represented by a response vector (‘y’ is a common notation to represent response vector). All the possible values taken by a response vector are termed target names." }, { "code": null, "e": 2071, "s": 1885, "text": "Loading exemplar dataset: scikit-learn comes loaded with a few example datasets like the iris and digits datasets for classification and the boston house prices dataset for regression. " }, { "code": null, "e": 2139, "s": 2071, "text": "Given below is an example of how one can load an exemplar dataset: " }, { "code": null, "e": 2146, "s": 2139, "text": "Python" }, { "code": "# load the iris dataset as an example from sklearn.datasets import load_iris iris = load_iris() # store the feature matrix (X) and response vector (y) X = iris.data y = iris.target # store the feature and target names feature_names = iris.feature_names target_names = iris.target_names # printing features and target names of our dataset print(\"Feature names:\", feature_names) print(\"Target names:\", target_names) # X and y are numpy arrays print(\"\\nType of X is:\", type(X)) # printing first 5 input rows print(\"\\nFirst 5 rows of X:\\n\", X[:5])", "e": 2710, "s": 2146, "text": null }, { "code": null, "e": 2719, "s": 2710, "text": "Output: " }, { "code": null, "e": 3034, "s": 2719, "text": "Feature names: ['sepal length (cm)','sepal width (cm)',\n 'petal length (cm)','petal width (cm)']\nTarget names: ['setosa' 'versicolor' 'virginica']\n\nType of X is: \n\nFirst 5 rows of X:\n [[ 5.1 3.5 1.4 0.2]\n [ 4.9 3. 1.4 0.2]\n [ 4.7 3.2 1.3 0.2]\n [ 4.6 3.1 1.5 0.2]\n [ 5. 3.6 1.4 0.2]]" }, { "code": null, "e": 3219, "s": 3034, "text": "Loading external dataset: Now, consider the case when we want to load an external dataset. For this purpose, we can use the pandas library for easily loading and manipulating datasets." }, { "code": null, "e": 3271, "s": 3219, "text": "To install pandas, use the following pip command: " }, { "code": null, "e": 3290, "s": 3271, "text": "pip install pandas" }, { "code": null, "e": 3410, "s": 3290, "text": "In pandas, important data types are:Series: Series is a one-dimensional labeled array capable of holding any data type." }, { "code": null, "e": 3732, "s": 3410, "text": "DataFrame: It is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects. It is generally the most commonly used pandas object.Note: The CSV file used in the example below can be downloaded from here: weather.csv" }, { "code": null, "e": 3739, "s": 3732, "text": "Python" }, { "code": "import pandas as pd # reading csv file data = pd.read_csv('weather.csv') # shape of dataset print(\"Shape:\", data.shape) # column names print(\"\\nFeatures:\", data.columns) # storing the feature matrix (X) and response vector (y) X = data[data.columns[:-1]] y = data[data.columns[-1]] # printing first 5 rows of feature matrix print(\"\\nFeature matrix:\\n\", X.head()) # printing first 5 values of response vector print(\"\\nResponse vector:\\n\", y.head())", "e": 4211, "s": 3739, "text": null }, { "code": null, "e": 4220, "s": 4211, "text": "Output: " }, { "code": null, "e": 4694, "s": 4220, "text": "Shape: (14, 5)\n\nFeatures: Index([u'Outlook', u'Temperature', u'Humidity', \n u'Windy', u'Play'], dtype='object')\n\nFeature matrix:\n Outlook Temperature Humidity Windy\n0 overcast hot high False\n1 overcast cool normal True\n2 overcast mild high True\n3 overcast hot normal False\n4 rainy mild high False\n\nResponse vector:\n0 yes\n1 yes\n2 yes\n3 yes\n4 yes\nName: Play, dtype: object" }, { "code": null, "e": 5064, "s": 4694, "text": "Step 2: Splitting the datasetOne important aspect of all machine learning models is to determine their accuracy. Now, in order to determine their accuracy, one can train the model using the given dataset and then predict the response values for the same dataset using that model and hence, find the accuracy of the model. But this method has several flaws in it, like: " }, { "code": null, "e": 5145, "s": 5064, "text": "The goal is to estimate the likely performance of a model on out-of-sample data." }, { "code": null, "e": 5249, "s": 5145, "text": "Maximizing training accuracy rewards overly complex models that won’t necessarily generalize our model." }, { "code": null, "e": 5310, "s": 5249, "text": "Unnecessarily complex models may over-fit the training data." }, { "code": null, "e": 5461, "s": 5310, "text": "A better option is to split our data into two parts: the first one for training our machine learning model, and the second one for testing our model. " }, { "code": null, "e": 5477, "s": 5461, "text": "To summarize: " }, { "code": null, "e": 5546, "s": 5477, "text": "Split the dataset into two pieces: a training set and a testing set." }, { "code": null, "e": 5583, "s": 5546, "text": "Train the model on the training set." }, { "code": null, "e": 5655, "s": 5583, "text": "Test the model on the testing set, and evaluate how well our model did." }, { "code": null, "e": 5689, "s": 5655, "text": "Advantages of train/test split: " }, { "code": null, "e": 5775, "s": 5689, "text": "The model can be trained and tested on different data than the one used for training." }, { "code": null, "e": 5858, "s": 5775, "text": "Response values are known for the test dataset, hence predictions can be evaluated" }, { "code": null, "e": 5949, "s": 5858, "text": "Testing accuracy is a better estimate than training accuracy of out-of-sample performance." }, { "code": null, "e": 5978, "s": 5949, "text": "Consider the example below: " }, { "code": null, "e": 5985, "s": 5978, "text": "Python" }, { "code": "# load the iris dataset as an examplefrom sklearn.datasets import load_irisiris = load_iris() # store the feature matrix (X) and response vector (y)X = iris.datay = iris.target # splitting X and y into training and testing setsfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1) # printing the shapes of the new X objectsprint(X_train.shape)print(X_test.shape) # printing the shapes of the new y objectsprint(y_train.shape)print(y_test.shape)", "e": 6521, "s": 5985, "text": null }, { "code": null, "e": 6530, "s": 6521, "text": "Output: " }, { "code": null, "e": 6564, "s": 6530, "text": "(90L, 4L)\n(60L, 4L)\n(90L,)\n(60L,)" }, { "code": null, "e": 6647, "s": 6564, "text": "The train_test_split function takes several arguments which are explained below: " }, { "code": null, "e": 6726, "s": 6647, "text": "X, y: These are the feature matrix and response vector which need to be split." }, { "code": null, "e": 6883, "s": 6726, "text": "test_size: It is the ratio of test data to the given data. For example, setting test_size = 0.4 for 150 rows of X produces test data of 150 x 0.4 = 60 rows." }, { "code": null, "e": 7155, "s": 6883, "text": "random_state: If you use random_state = some_number, then you can guarantee that your split will be always the same. This is useful if you want reproducible results, for example in testing for consistency in the documentation (so that everybody can see the same numbers)." }, { "code": null, "e": 7182, "s": 7155, "text": "Step 3: Training the model" }, { "code": null, "e": 7460, "s": 7182, "text": "Now, it’s time to train some prediction models using our dataset. Scikit-learn provides a wide range of machine learning algorithms that have a unified/consistent interface for fitting, predicting accuracy, etc.The example given below uses KNN (K nearest neighbors) classifier." }, { "code": null, "e": 7589, "s": 7460, "text": "Note: We will not go into the details of how the algorithm works as we are interested in understanding its implementation only. " }, { "code": null, "e": 7623, "s": 7589, "text": "Now, consider the example below: " }, { "code": null, "e": 7630, "s": 7623, "text": "Python" }, { "code": "# load the iris dataset as an examplefrom sklearn.datasets import load_irisiris = load_iris() # store the feature matrix (X) and response vector (y)X = iris.datay = iris.target # splitting X and y into training and testing setsfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1) # training the model on training setfrom sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors=3)knn.fit(X_train, y_train) # making predictions on the testing sety_pred = knn.predict(X_test) # comparing actual response values (y_test) with predicted response values (y_pred)from sklearn import metricsprint(\"kNN model accuracy:\", metrics.accuracy_score(y_test, y_pred)) # making prediction for out of sample datasample = [[3, 5, 4, 2], [2, 3, 5, 4]]preds = knn.predict(sample)pred_species = [iris.target_names[p] for p in preds]print(\"Predictions:\", pred_species) # saving the modelfrom sklearn.externals import joblibjoblib.dump(knn, 'iris_knn.pkl')", "e": 8686, "s": 7630, "text": null }, { "code": null, "e": 8695, "s": 8686, "text": "Output: " }, { "code": null, "e": 8771, "s": 8695, "text": "kNN model accuracy: 0.983333333333\nPredictions: ['versicolor', 'virginica']" }, { "code": null, "e": 8819, "s": 8771, "text": "Important points to note from the above code: " }, { "code": null, "e": 8861, "s": 8819, "text": "We create a knn classifier object using: " }, { "code": null, "e": 8904, "s": 8861, "text": " knn = KNeighborsClassifier(n_neighbors=3)" }, { "code": null, "e": 9048, "s": 8904, "text": "The classifier is trained using X_train data. The process is termed fitting. We pass the feature matrix and the corresponding response vector. " }, { "code": null, "e": 9075, "s": 9048, "text": " knn.fit(X_train, y_train)" }, { "code": null, "e": 9227, "s": 9075, "text": "Now, we need to test our classifier on the X_test data. knn.predict method is used for this purpose. It returns the predicted response vector, y_pred. " }, { "code": null, "e": 9257, "s": 9227, "text": " y_pred = knn.predict(X_test)" }, { "code": null, "e": 9413, "s": 9257, "text": "Now, we are interested in finding the accuracy of our model by comparing y_test and y_pred. This is done using the metrics module’s method accuracy_score: " }, { "code": null, "e": 9459, "s": 9413, "text": "print(metrics.accuracy_score(y_test, y_pred))" }, { "code": null, "e": 9634, "s": 9459, "text": "Consider the case when you want your model to make predictions out of sample data. Then, the sample input can simply be passed in the same way as we pass any feature matrix. " }, { "code": null, "e": 9700, "s": 9634, "text": "sample = [[3, 5, 4, 2], [2, 3, 5, 4]]\npreds = knn.predict(sample)" }, { "code": null, "e": 9876, "s": 9700, "text": "If you are not interested in training your classifier again and again and using the pre-trained classifier, one can save their classifier using joblib. All you need to do is: " }, { "code": null, "e": 9909, "s": 9876, "text": "joblib.dump(knn, 'iris_knn.pkl')" }, { "code": null, "e": 9990, "s": 9909, "text": "In case you want to load an already saved classifier, use the following method: " }, { "code": null, "e": 10025, "s": 9990, "text": "knn = joblib.load('iris_knn.pkl') " }, { "code": null, "e": 10174, "s": 10025, "text": "As we approach the end of this article, here are some benefits of using scikit-learn over some other machine learning libraries(like R libraries): " }, { "code": null, "e": 10222, "s": 10174, "text": "Consistent interface to machine learning models" }, { "code": null, "e": 10281, "s": 10222, "text": "Provides many tuning parameters but with sensible defaults" }, { "code": null, "e": 10307, "s": 10281, "text": "Exceptional documentation" }, { "code": null, "e": 10354, "s": 10307, "text": "Rich set of functionality for companion tasks." }, { "code": null, "e": 10400, "s": 10354, "text": "Active community for development and support." }, { "code": null, "e": 10414, "s": 10400, "text": "References: " }, { "code": null, "e": 10464, "s": 10414, "text": "http://scikit-learn.org/stable/documentation.html" }, { "code": null, "e": 10515, "s": 10464, "text": "https://github.com/justmarkham/scikit-learn-videos" }, { "code": null, "e": 10936, "s": 10515, "text": "This article is contributed by Nikhil Kumar. 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": 10949, "s": 10936, "text": "ayushgangwar" }, { "code": null, "e": 10959, "s": 10949, "text": "ArthTyagi" }, { "code": null, "e": 10976, "s": 10959, "text": "punamsingh628700" }, { "code": null, "e": 11002, "s": 10976, "text": "Advanced Computer Subject" }, { "code": null, "e": 11019, "s": 11002, "text": "Machine Learning" }, { "code": null, "e": 11026, "s": 11019, "text": "Python" }, { "code": null, "e": 11043, "s": 11026, "text": "Machine Learning" }, { "code": null, "e": 11141, "s": 11043, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11164, "s": 11141, "text": "System Design Tutorial" }, { "code": null, "e": 11190, "s": 11164, "text": "Docker - COPY Instruction" }, { "code": null, "e": 11231, "s": 11190, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 11267, "s": 11231, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 11311, "s": 11267, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 11345, "s": 11311, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 11369, "s": 11345, "text": "Search Algorithms in AI" }, { "code": null, "e": 11410, "s": 11369, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 11446, "s": 11410, "text": "ML | Monte Carlo Tree Search (MCTS)" } ]
Measure execution time of a function in C++
14 Feb, 2022 We can find out the time taken by different parts of a program by using the std::chrono library introduced in C++ 11. We have discussed at How to measure time taken by a program in C. The functions described there are supported in C++ too but they are C specific. For clean and robust C++ programs we should strive to use C++ specific language constructs only.std::chrono has two distinct objects–timepoint and duration. A timepoint as the name suggests represents a point in time whereas a duration represents an interval or span of time. The C++ library allows us to subtract two timepoints to get the interval of time passed in between. Using provided methods we can also convert this duration to appropriate units.The std::chrono provides us with three clocks with varying accuracy. The high_resolution_clock is the most accurate and hence it is used to measure execution time.Step 1: Get the timepoint before the function is called CPP #include <chrono>using namespace std::chrono; // Use auto keyword to avoid typing long// type definitions to get the timepoint// at this instant use function now()auto start = high_resolution_clock::now(); Step 2: Get the timepoint after the function is called CPP #include <chrono>using namespace std::chrono; // After function callauto stop = high_resolution_clock::now(); Step 3: Get the difference in timepoints and cast it to required units CPP // Subtract stop and start timepoints and// cast it to required unit. Predefined units// are nanoseconds, microseconds, milliseconds,// seconds, minutes, hours. Use duration_cast()// function.auto duration = duration_cast<microseconds>(stop - start); // To get the value of duration use the count()// member function on the duration objectcout << duration.count() << endl; A complete C++ program demonstrating the procedure is given below. We fill up a vector with some random numbers and measure the time taken by sort() function to sort this vector. CPP // C++ program to find out execution time of// of functions#include <algorithm>#include <chrono>#include <iostream>#include<vector>using namespace std;using namespace std::chrono; // For demonstration purpose, we will fill up// a vector with random integers and then sort// them using sort function. We fill record// and print the time required by sort functionint main(){ vector<int> values(10000); // Generate Random values auto f = []() -> int { return rand() % 10000; }; // Fill up the vector generate(values.begin(), values.end(), f); // Get starting timepoint auto start = high_resolution_clock::now(); // Call the function, here sort() sort(values.begin(), values.end()); // Get ending timepoint auto stop = high_resolution_clock::now(); // Get duration. Substart timepoints to // get duration. To cast it to proper unit // use duration cast method auto duration = duration_cast<microseconds>(stop - start); cout << "Time taken by function: " << duration.count() << " microseconds" << endl; return 0;} Output: (Machine Dependent) Time taken by function: 3062 microseconds References https://www.geeksforgeeks.org/chrono-in-c/ intenserave bugsanderrors sohammalviya65 varshagumber28 CPP-Library cpp-puzzle C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Inheritance in C++ Priority Queue in C++ Standard Template Library (STL) Substring in C++ Object Oriented Programming in C++ C++ Classes and Objects Sorting a vector in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Feb, 2022" }, { "code": null, "e": 992, "s": 54, "text": "We can find out the time taken by different parts of a program by using the std::chrono library introduced in C++ 11. We have discussed at How to measure time taken by a program in C. The functions described there are supported in C++ too but they are C specific. For clean and robust C++ programs we should strive to use C++ specific language constructs only.std::chrono has two distinct objects–timepoint and duration. A timepoint as the name suggests represents a point in time whereas a duration represents an interval or span of time. The C++ library allows us to subtract two timepoints to get the interval of time passed in between. Using provided methods we can also convert this duration to appropriate units.The std::chrono provides us with three clocks with varying accuracy. The high_resolution_clock is the most accurate and hence it is used to measure execution time.Step 1: Get the timepoint before the function is called " }, { "code": null, "e": 996, "s": 992, "text": "CPP" }, { "code": "#include <chrono>using namespace std::chrono; // Use auto keyword to avoid typing long// type definitions to get the timepoint// at this instant use function now()auto start = high_resolution_clock::now();", "e": 1202, "s": 996, "text": null }, { "code": null, "e": 1259, "s": 1202, "text": "Step 2: Get the timepoint after the function is called " }, { "code": null, "e": 1263, "s": 1259, "text": "CPP" }, { "code": "#include <chrono>using namespace std::chrono; // After function callauto stop = high_resolution_clock::now();", "e": 1373, "s": 1263, "text": null }, { "code": null, "e": 1446, "s": 1373, "text": "Step 3: Get the difference in timepoints and cast it to required units " }, { "code": null, "e": 1450, "s": 1446, "text": "CPP" }, { "code": "// Subtract stop and start timepoints and// cast it to required unit. Predefined units// are nanoseconds, microseconds, milliseconds,// seconds, minutes, hours. Use duration_cast()// function.auto duration = duration_cast<microseconds>(stop - start); // To get the value of duration use the count()// member function on the duration objectcout << duration.count() << endl;", "e": 1823, "s": 1450, "text": null }, { "code": null, "e": 2003, "s": 1823, "text": "A complete C++ program demonstrating the procedure is given below. We fill up a vector with some random numbers and measure the time taken by sort() function to sort this vector. " }, { "code": null, "e": 2007, "s": 2003, "text": "CPP" }, { "code": "// C++ program to find out execution time of// of functions#include <algorithm>#include <chrono>#include <iostream>#include<vector>using namespace std;using namespace std::chrono; // For demonstration purpose, we will fill up// a vector with random integers and then sort// them using sort function. We fill record// and print the time required by sort functionint main(){ vector<int> values(10000); // Generate Random values auto f = []() -> int { return rand() % 10000; }; // Fill up the vector generate(values.begin(), values.end(), f); // Get starting timepoint auto start = high_resolution_clock::now(); // Call the function, here sort() sort(values.begin(), values.end()); // Get ending timepoint auto stop = high_resolution_clock::now(); // Get duration. Substart timepoints to // get duration. To cast it to proper unit // use duration cast method auto duration = duration_cast<microseconds>(stop - start); cout << \"Time taken by function: \" << duration.count() << \" microseconds\" << endl; return 0;}", "e": 3084, "s": 2007, "text": null }, { "code": null, "e": 3114, "s": 3084, "text": "Output: (Machine Dependent) " }, { "code": null, "e": 3156, "s": 3114, "text": "Time taken by function: 3062 microseconds" }, { "code": null, "e": 3211, "s": 3156, "text": "References https://www.geeksforgeeks.org/chrono-in-c/ " }, { "code": null, "e": 3223, "s": 3211, "text": "intenserave" }, { "code": null, "e": 3237, "s": 3223, "text": "bugsanderrors" }, { "code": null, "e": 3252, "s": 3237, "text": "sohammalviya65" }, { "code": null, "e": 3267, "s": 3252, "text": "varshagumber28" }, { "code": null, "e": 3279, "s": 3267, "text": "CPP-Library" }, { "code": null, "e": 3290, "s": 3279, "text": "cpp-puzzle" }, { "code": null, "e": 3294, "s": 3290, "text": "C++" }, { "code": null, "e": 3298, "s": 3294, "text": "CPP" }, { "code": null, "e": 3396, "s": 3298, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3423, "s": 3396, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 3466, "s": 3423, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 3500, "s": 3466, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 3525, "s": 3500, "text": "unordered_map in C++ STL" }, { "code": null, "e": 3544, "s": 3525, "text": "Inheritance in C++" }, { "code": null, "e": 3598, "s": 3544, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 3615, "s": 3598, "text": "Substring in C++" }, { "code": null, "e": 3650, "s": 3615, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 3674, "s": 3650, "text": "C++ Classes and Objects" } ]
Playing with Destructors in C++
29 May, 2017 Predict the output of the below code snippet. #include <iostream>using namespace std; int i; class A{public: ~A() { i=10; }}; int foo(){ i=3; A ob; return i;} int main(){ cout << "i = " << foo() << endl; return 0;} Output of the above program is “i = 3”.Why the output is i= 3 and not 10?While returning from a function, destructor is the last method to be executed. The destructor for the object “ob” is called after the value of i is copied to the return value of the function. So, before destructor could change the value of i to 10, the current value of i gets copied & hence the output is i = 3. How to make the program to output “i = 10” ?Following are two ways of returning updated value: 1) Return by Reference:Since reference gives the l-value of the variable,by using return by reference the program will output “i = 10”. #include <iostream>using namespace std; int i; class A{public: ~A() { i = 10; }}; int& foo(){ i = 3; A ob; return i;} int main(){ cout << "i = " << foo() << endl; return 0;} The function foo() returns the l-value of the variable i. So, the address of i will be copied in the return value. Since, the references are automatically dereferened. It will output “i = 10”. 2. Create the object ob in a block scope #include <iostream>using namespace std; int i; class A{public: ~A() { i = 10; }}; int foo(){ i = 3; { A ob; } return i;} int main(){ cout << "i = " << foo() << endl; return 0;} Since the object ob is created in the block scope, the destructor of the object will be called after the block ends, thereby changing the value of i to 10. Finally 10 will copied to the return value. This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above cpp-destructor C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n29 May, 2017" }, { "code": null, "e": 100, "s": 54, "text": "Predict the output of the below code snippet." }, { "code": "#include <iostream>using namespace std; int i; class A{public: ~A() { i=10; }}; int foo(){ i=3; A ob; return i;} int main(){ cout << \"i = \" << foo() << endl; return 0;}", "e": 304, "s": 100, "text": null }, { "code": null, "e": 690, "s": 304, "text": "Output of the above program is “i = 3”.Why the output is i= 3 and not 10?While returning from a function, destructor is the last method to be executed. The destructor for the object “ob” is called after the value of i is copied to the return value of the function. So, before destructor could change the value of i to 10, the current value of i gets copied & hence the output is i = 3." }, { "code": null, "e": 785, "s": 690, "text": "How to make the program to output “i = 10” ?Following are two ways of returning updated value:" }, { "code": null, "e": 921, "s": 785, "text": "1) Return by Reference:Since reference gives the l-value of the variable,by using return by reference the program will output “i = 10”." }, { "code": "#include <iostream>using namespace std; int i; class A{public: ~A() { i = 10; }}; int& foo(){ i = 3; A ob; return i;} int main(){ cout << \"i = \" << foo() << endl; return 0;}", "e": 1130, "s": 921, "text": null }, { "code": null, "e": 1323, "s": 1130, "text": "The function foo() returns the l-value of the variable i. So, the address of i will be copied in the return value. Since, the references are automatically dereferened. It will output “i = 10”." }, { "code": null, "e": 1364, "s": 1323, "text": "2. Create the object ob in a block scope" }, { "code": "#include <iostream>using namespace std; int i; class A{public: ~A() { i = 10; }}; int foo(){ i = 3; { A ob; } return i;} int main(){ cout << \"i = \" << foo() << endl; return 0;}", "e": 1586, "s": 1364, "text": null }, { "code": null, "e": 1786, "s": 1586, "text": "Since the object ob is created in the block scope, the destructor of the object will be called after the block ends, thereby changing the value of i to 10. Finally 10 will copied to the return value." }, { "code": null, "e": 1990, "s": 1786, "text": "This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 2005, "s": 1990, "text": "cpp-destructor" }, { "code": null, "e": 2016, "s": 2005, "text": "C Language" }, { "code": null, "e": 2020, "s": 2016, "text": "C++" }, { "code": null, "e": 2024, "s": 2020, "text": "CPP" }, { "code": null, "e": 2122, "s": 2024, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2139, "s": 2122, "text": "Substring in C++" }, { "code": null, "e": 2161, "s": 2139, "text": "Function Pointer in C" }, { "code": null, "e": 2196, "s": 2161, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 2242, "s": 2196, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 2287, "s": 2242, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 2305, "s": 2287, "text": "Vector in C++ STL" }, { "code": null, "e": 2348, "s": 2305, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 2394, "s": 2348, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 2437, "s": 2394, "text": "Set in C++ Standard Template Library (STL)" } ]
Python | Pandas Series.set_axis()
03 Sep, 2021 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.set_axis() function is used to assign desired index to given axis. Indexes for column or row labels can be changed by assigning a list-like or Index. Syntax: Series.set_axis(labels, axis=0, inplace=None)Parameter : labels : The values for the new index. axis : The axis to update. The value 0 identifies the rows, and 1 identifies the columns. inplace : Whether to return a new %(klass)s instance.Returns : renamed : series Example #1: Use Series.set_axis() function to reset the axis of the given Series object. Python3 # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.set_axis() function to reset the index of the given series object Python3 # Create the Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # reset the indexsr.set_axis(didx, inplace = True) # Print the seriesprint(sr) Output : As we can see in the output, the Series.set_axis() function has successfully reset the index of the given Series object. Example #2: Use Series.set_axis() function to reset the axis of the given Series object. Python3 # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([100, 25, 32, 118, 24, 65]) # Print the seriesprint(sr) Output : Now we will use Series.set_axis() function to reset the index of the given series object Python3 # Assign the new indexsr.set_axis(['A', 'B', 'C', 'D', 'E', 'F'], inplace = True) # print the seriesprint(sr) Output : As we can see in the output, the Series.set_axis() function has successfully reset the index of the given Series object. anikakapoor Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Sep, 2021" }, { "code": null, "e": 285, "s": 28, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 449, "s": 285, "text": "Pandas Series.set_axis() function is used to assign desired index to given axis. Indexes for column or row labels can be changed by assigning a list-like or Index." }, { "code": null, "e": 724, "s": 449, "text": "Syntax: Series.set_axis(labels, axis=0, inplace=None)Parameter : labels : The values for the new index. axis : The axis to update. The value 0 identifies the rows, and 1 identifies the columns. inplace : Whether to return a new %(klass)s instance.Returns : renamed : series " }, { "code": null, "e": 814, "s": 724, "text": "Example #1: Use Series.set_axis() function to reset the axis of the given Series object. " }, { "code": null, "e": 822, "s": 814, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 1114, "s": 822, "text": null }, { "code": null, "e": 1124, "s": 1114, "text": "Output : " }, { "code": null, "e": 1214, "s": 1124, "text": "Now we will use Series.set_axis() function to reset the index of the given series object " }, { "code": null, "e": 1222, "s": 1214, "text": "Python3" }, { "code": "# Create the Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # reset the indexsr.set_axis(didx, inplace = True) # Print the seriesprint(sr)", "e": 1437, "s": 1222, "text": null }, { "code": null, "e": 1447, "s": 1437, "text": "Output : " }, { "code": null, "e": 1568, "s": 1447, "text": "As we can see in the output, the Series.set_axis() function has successfully reset the index of the given Series object." }, { "code": null, "e": 1658, "s": 1568, "text": "Example #2: Use Series.set_axis() function to reset the axis of the given Series object. " }, { "code": null, "e": 1666, "s": 1658, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([100, 25, 32, 118, 24, 65]) # Print the seriesprint(sr)", "e": 1802, "s": 1666, "text": null }, { "code": null, "e": 1812, "s": 1802, "text": "Output : " }, { "code": null, "e": 1902, "s": 1812, "text": "Now we will use Series.set_axis() function to reset the index of the given series object " }, { "code": null, "e": 1910, "s": 1902, "text": "Python3" }, { "code": "# Assign the new indexsr.set_axis(['A', 'B', 'C', 'D', 'E', 'F'], inplace = True) # print the seriesprint(sr)", "e": 2020, "s": 1910, "text": null }, { "code": null, "e": 2030, "s": 2020, "text": "Output : " }, { "code": null, "e": 2152, "s": 2030, "text": "As we can see in the output, the Series.set_axis() function has successfully reset the index of the given Series object. " }, { "code": null, "e": 2164, "s": 2152, "text": "anikakapoor" }, { "code": null, "e": 2185, "s": 2164, "text": "Python pandas-series" }, { "code": null, "e": 2214, "s": 2185, "text": "Python pandas-series-methods" }, { "code": null, "e": 2228, "s": 2214, "text": "Python-pandas" }, { "code": null, "e": 2235, "s": 2228, "text": "Python" } ]