title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Program to make Indian Flag in Python | Python’s libraries to draw graphs has very extensive features which can not only give us charts but also give us flexibility to draw other diagrams like flags. In that sense those modules have an artistic touch. In this article we will see how to draw the Indian flag using the libraries numpy and matplotlib.
We create three rectangles of same width and draw them with appropriate colours and borders.
We create three rectangles of same width and draw them with appropriate colours and borders.
Use pyplot function to draw the circle of the Ashok Chakra at the center of the middle rectangle.
Use pyplot function to draw the circle of the Ashok Chakra at the center of the middle rectangle.
Use numpy and matplotlib to draw the 24 lines inside the Ashok Chakra.
Use numpy and matplotlib to draw the 24 lines inside the Ashok Chakra.
In all the above drawing we mention the colours, borders, radius and line lengths to match the requirement of the final size of the flag we need.
In all the above drawing we mention the colours, borders, radius and line lengths to match the requirement of the final size of the flag we need.
We implement the above approach using the following program.
import numpy as np
import matplotlib.pyplot as py
import matplotlib.patches as patch
#Plotting the tri colours in national flag
a = patch.Rectangle((0,1), width=12, height=2, facecolor='green', edgecolor='grey')
b = patch.Rectangle((0,3), width=12, height=2, facecolor='white', edgecolor='grey')
c = patch.Rectangle((0,5), width=12, height=2, facecolor='#FF9933', edgecolor='grey')
m,n = py.subplots()
n.add_patch(a)
n.add_patch(b)
n.add_patch(c)
#AshokChakra Circle
radius=0.8
py.plot(6,4, marker = 'o', markerfacecolor = '#000088ff', markersize = 9.5)
chakra = py.Circle((6, 4), radius, color='#000088ff', fill=False, linewidth=7)
n.add_artist(chakra)
#24 spokes in AshokChakra
for i in range(0,24):
p = 6 + radius/2 * np.cos(np.pi*i/12 + np.pi/48)
q = 6 + radius/2 * np.cos(np.pi*i/12 - np.pi/48)
r = 4 + radius/2 * np.sin(np.pi*i/12 + np.pi/48)
s = 4 + radius/2 * np.sin(np.pi*i/12 - np.pi/48)
t = 6 + radius * np.cos(np.pi*i/12)
u = 4 + radius * np.sin(np.pi*i/12)
n.add_patch(patch.Polygon([[6,4], [p,r], [t,u],[q,s]], fill=True, closed=True, color='#000088ff'))
py.axis('equal')
py.show()
Running the above code gives us the following result − | [
{
"code": null,
"e": 1372,
"s": 1062,
"text": "Python’s libraries to draw graphs has very extensive features which can not only give us charts but also give us flexibility to draw other diagrams like flags. In that sense those modules have an artistic touch. In this article we will see how to draw the Indian flag using the libraries numpy and matplotlib."
},
{
"code": null,
"e": 1465,
"s": 1372,
"text": "We create three rectangles of same width and draw them with appropriate colours and borders."
},
{
"code": null,
"e": 1558,
"s": 1465,
"text": "We create three rectangles of same width and draw them with appropriate colours and borders."
},
{
"code": null,
"e": 1656,
"s": 1558,
"text": "Use pyplot function to draw the circle of the Ashok Chakra at the center of the middle rectangle."
},
{
"code": null,
"e": 1754,
"s": 1656,
"text": "Use pyplot function to draw the circle of the Ashok Chakra at the center of the middle rectangle."
},
{
"code": null,
"e": 1825,
"s": 1754,
"text": "Use numpy and matplotlib to draw the 24 lines inside the Ashok Chakra."
},
{
"code": null,
"e": 1896,
"s": 1825,
"text": "Use numpy and matplotlib to draw the 24 lines inside the Ashok Chakra."
},
{
"code": null,
"e": 2042,
"s": 1896,
"text": "In all the above drawing we mention the colours, borders, radius and line lengths to match the requirement of the final size of the flag we need."
},
{
"code": null,
"e": 2188,
"s": 2042,
"text": "In all the above drawing we mention the colours, borders, radius and line lengths to match the requirement of the final size of the flag we need."
},
{
"code": null,
"e": 2249,
"s": 2188,
"text": "We implement the above approach using the following program."
},
{
"code": null,
"e": 3366,
"s": 2249,
"text": "import numpy as np\nimport matplotlib.pyplot as py\nimport matplotlib.patches as patch\n#Plotting the tri colours in national flag\na = patch.Rectangle((0,1), width=12, height=2, facecolor='green', edgecolor='grey')\nb = patch.Rectangle((0,3), width=12, height=2, facecolor='white', edgecolor='grey')\nc = patch.Rectangle((0,5), width=12, height=2, facecolor='#FF9933', edgecolor='grey')\nm,n = py.subplots()\nn.add_patch(a)\nn.add_patch(b)\nn.add_patch(c)\n#AshokChakra Circle\nradius=0.8\npy.plot(6,4, marker = 'o', markerfacecolor = '#000088ff', markersize = 9.5)\nchakra = py.Circle((6, 4), radius, color='#000088ff', fill=False, linewidth=7)\nn.add_artist(chakra)\n#24 spokes in AshokChakra\nfor i in range(0,24):\n p = 6 + radius/2 * np.cos(np.pi*i/12 + np.pi/48)\n q = 6 + radius/2 * np.cos(np.pi*i/12 - np.pi/48)\n r = 4 + radius/2 * np.sin(np.pi*i/12 + np.pi/48)\n s = 4 + radius/2 * np.sin(np.pi*i/12 - np.pi/48)\n t = 6 + radius * np.cos(np.pi*i/12)\n u = 4 + radius * np.sin(np.pi*i/12)\n n.add_patch(patch.Polygon([[6,4], [p,r], [t,u],[q,s]], fill=True, closed=True, color='#000088ff'))\npy.axis('equal')\npy.show()"
},
{
"code": null,
"e": 3421,
"s": 3366,
"text": "Running the above code gives us the following result −"
}
] |
Find Common Words in Article with Python Module Newspaper and NLTK | by Khuyen Tran | Towards Data Science | You want to extract essential information from an interesting article, but find the article is too long to read with your limited amount of time. Before you dive into the whole article and end up disappointed with the irrelevant content, you should look at the summary and keywords beforehand.
newpaper3k and nltk are the two effective tools that could be used for scraping and summarizing news articles. Let’s analyze the interesting article that I came across today on Medium: It Took Me 2 Years To Get 1000 Followers — Life Lessons I’ve Learned Throughout The Journey using these 2 tools.
pip install newspaper3kfrom newspaper import Article url = 'https://mystudentvoices.com/it-took-me-2-years-to-get-1000-followers-life-lessons-ive-learned-throughout-the-journey-9bc44f2959f0'article = Article(url)article.download()
Find the publish date
article.publish_date
Extract the top image and take a quick look at the image
image_url = article.top_imagefrom IPython.display import Imagefrom IPython.core.display import HTML Image(url=image_url)
Output:
Extract author’s name
article.authors
Output:
['William Cho']
Extract article keywords:
article.keywords
Output:
['soon', 'ive', 'work', 'journey', '1000', 'took', 'followers', 'started', 'truth', 'life', 'writing', 'wasnt', 'lessons', 'doing', 'read', 'maybe', 'learned', 'youre']
Summarize the article
article.summary
Output:
'But I’ve only been writing on Medium for a total of maybe 4.5 months.\nI started writing passionately, and you could tell from my writing that I thought I was enlightened and speaking from authority.\nI’ve noticed that it comes in moments where I put in effort to improve myself — working out, writing, and reading.\nYou’re just doing it to put yourself on a higher ground than your friends, to judge them from a higher platform and deem everything you’re doing more virtuous than what they’re doing.\nI would sidestep and avoid the truth — the truth that would hurt but ultimately set me free.'
With the summary, we could quickly grasp the key takeaways of the article:
To become a better writer, he constantly improved his writing skills by writing, reading, and working out.
His motivation was once from external sources such as friends.
There was struggling in his journey. But by evaluating his approach, he sets himself free.
Let see if we could extract more insights from the article using NLTK
Start with extracting the text from the newspaper
text = article.text
pip install nltk
Requirement already satisfied: nltk in ./opt/anaconda3/lib/python3.7/site-packages (3.4.5)
Requirement already satisfied: six in ./opt/anaconda3/lib/python3.7/site-packages (from nltk) (1.12.0)
Note: you may need to restart the kernel to use updated packages.
import nltk
nltk.download()
showing info https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/index.xml
True
Remove punctuation
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'\w+')
text = tokenizer.tokenize(text)
text = ' '.join(word for word in text)
Tokenize words
from nltk.tokenize import word_tokenize
tokenized_word=word_tokenize(text)
Lowercase
tokenized_word = [word.lower() for word in tokenized_word]
Remove stopwords
from nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
print(stop_words)
{'t', 'under', 'will', "should've", 'such', 'has', 'other', 'do', 'shan', 'was', 'his', "wouldn't", 'he', 'if', 'ours', 'did', 'which', 'my', 'had', 'after', 'through', 'off', 'the', 'most', 'o', 'aren', 'when', 'into', 'being', 'her', 'each', 'this', 'been', 'about', 'until', 'won', 'what', 'be', 'ourselves', 'doesn', 'they', 'hers', 'am', "it's", 'i', 'down', 'y', 'have', 'who', 'their', 'any', 'with', 'both', 'because', 'from', 'before', 'or', 'hasn', 'haven', 'doing', 'few', 'don', "shouldn't", 'for', 'ain', 'by', 'having', 'some', 'our', 'm', 'no', 'weren', 'yourself', 've', 'there', 'were', "you'll", 's', 'should', "won't", 'over', 'against', 'to', "wasn't", "aren't", 'on', 'him', 'are', "mightn't", 'as', "hadn't", 'how', 'you', 'it', "shan't", 'hadn', 'and', 'than', 'that', "couldn't", 'where', 'then', 'its', 'whom', 'below', 'here', "hasn't", 'all', "didn't", "isn't", 'wasn', 'an', 'yourselves', 'again', "don't", 'why', 'theirs', 'up', 'couldn', 'just', 'can', "doesn't", 'so', 'own', 'd', 'wouldn', 'we', 'she', "mustn't", 'these', 'between', 'once', 'didn', "you've", "haven't", "that'll", 'but', 'needn', 'itself', "you'd", 'me', 'those', 'very', 'isn', 'himself', 'during', "she's", 'does', 'nor', 'them', 'not', 'mustn', 'now', 'same', 'your', 'll', 'yours', 'ma', 'myself', 'only', 'in', 'a', 'while', 'above', 'out', 're', 'shouldn', 'mightn', 'more', "needn't", 'at', "weren't", 'is', "you're", 'themselves', 'of', 'herself', 'too', 'further'}
filtered_word = []
for word in tokenized_word:
if word not in stop_words:
filtered_word.append(word)
Stemming the word
from nltk.stem import PorterStemmer
ps = PorterStemmer()
stemmed_words = []
for w in filtered_word:
stemmed_words.append(ps.stem(w))
#See how stemming works
for word in ['thinking', 'felt', 'asked','challenging','devoted']:
print(ps.stem(word))
think
felt
ask
challeng
devot
Try with lemmatization and compare it with stemming
from nltk.stem.wordnet import WordNetLemmatizer
lem = WordNetLemmatizer()
lem_words = []
for w in filtered_word:
lem_words.append(lem.lemmatize(w,'v'))
for word in ['thinking', 'felt', 'asked','challenging','devoted']:
print(lem.lemmatize(word,'v'))
think
felt
ask
challenge
devote
from nltk.probability import FreqDist
fdist = FreqDist(lem_words)
most_common = fdist.most_common(20)
most_common
[('write', 26),
('read', 11),
('maybe', 8),
('start', 8),
('one', 7),
('work', 7),
('know', 6),
('soon', 6),
('time', 6),
('think', 6),
('doubt', 6),
('would', 6),
('medium', 5),
('make', 5),
('truth', 5),
('day', 4),
('everyday', 4),
('keep', 4),
('could', 4),
('fail', 4)]
pip install matplotlib
Requirement already satisfied: matplotlib in ./opt/anaconda3/lib/python3.7/site-packages (3.1.1)
Requirement already satisfied: cycler>=0.10 in ./opt/anaconda3/lib/python3.7/site-packages (from matplotlib) (0.10.0)
Requirement already satisfied: kiwisolver>=1.0.1 in ./opt/anaconda3/lib/python3.7/site-packages (from matplotlib) (1.1.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in ./opt/anaconda3/lib/python3.7/site-packages (from matplotlib) (2.4.2)
Requirement already satisfied: python-dateutil>=2.1 in ./opt/anaconda3/lib/python3.7/site-packages (from matplotlib) (2.8.0)
Requirement already satisfied: numpy>=1.11 in ./opt/anaconda3/lib/python3.7/site-packages (from matplotlib) (1.17.2)
Requirement already satisfied: six in ./opt/anaconda3/lib/python3.7/site-packages (from cycler>=0.10->matplotlib) (1.12.0)
Requirement already satisfied: setuptools in ./opt/anaconda3/lib/python3.7/site-packages (from kiwisolver>=1.0.1->matplotlib) (41.4.0)
Note: you may need to restart the kernel to use updated packages.
import matplotlib.pyplot as plt
plt.figure(figsize=(20,5))
plt.plot([word[0] for word in most_common], [word[1] for word in most_common])
plt.xlabel('Words')
plt.ylabel('Frequency')
Text(0, 0.5, 'Frequency')
By looking at the plot of the most frequent words, we have a better idea of what the article about.
Let’s utilize another tool called WordClouds to create a more interesting visualization of our article
From this list of words, I could guess the general idea of the article: Becoming a better writer takes effort. You have to consistently write and read every day to improve your skills. There may be doubts and fear, but things will eventually improve if you trust the journey and keep your eyes on the bigger vision. Now, I could dive into reading this article since I know it will give me practical lessons for improving my writing skills.
newspaper3k andnltk are the great combination for extracting the essential information from an online article. You could also utilize this tool to grasp the general ideas of the article to decide whether the article is worthy of reading or to analyze several articles at once.
Feel free to fork and play with the code for this article in this Github repo.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
medium.com
[1]https://care.pressreader.com/hc/en-us/articles/203210155-Advanced-Keyword-Search
[2] William Cho, It Took Me 2 Years To Get 1000 Followers — Life Lessons I’ve Learned Throughout The Journey (2018), My Student Voices | [
{
"code": null,
"e": 465,
"s": 171,
"text": "You want to extract essential information from an interesting article, but find the article is too long to read with your limited amount of time. Before you dive into the whole article and end up disappointed with the irrelevant content, you should look at the summary and keywords beforehand."
},
{
"code": null,
"e": 763,
"s": 465,
"text": "newpaper3k and nltk are the two effective tools that could be used for scraping and summarizing news articles. Let’s analyze the interesting article that I came across today on Medium: It Took Me 2 Years To Get 1000 Followers — Life Lessons I’ve Learned Throughout The Journey using these 2 tools."
},
{
"code": null,
"e": 994,
"s": 763,
"text": "pip install newspaper3kfrom newspaper import Article url = 'https://mystudentvoices.com/it-took-me-2-years-to-get-1000-followers-life-lessons-ive-learned-throughout-the-journey-9bc44f2959f0'article = Article(url)article.download()"
},
{
"code": null,
"e": 1016,
"s": 994,
"text": "Find the publish date"
},
{
"code": null,
"e": 1037,
"s": 1016,
"text": "article.publish_date"
},
{
"code": null,
"e": 1094,
"s": 1037,
"text": "Extract the top image and take a quick look at the image"
},
{
"code": null,
"e": 1215,
"s": 1094,
"text": "image_url = article.top_imagefrom IPython.display import Imagefrom IPython.core.display import HTML Image(url=image_url)"
},
{
"code": null,
"e": 1223,
"s": 1215,
"text": "Output:"
},
{
"code": null,
"e": 1245,
"s": 1223,
"text": "Extract author’s name"
},
{
"code": null,
"e": 1261,
"s": 1245,
"text": "article.authors"
},
{
"code": null,
"e": 1269,
"s": 1261,
"text": "Output:"
},
{
"code": null,
"e": 1285,
"s": 1269,
"text": "['William Cho']"
},
{
"code": null,
"e": 1311,
"s": 1285,
"text": "Extract article keywords:"
},
{
"code": null,
"e": 1328,
"s": 1311,
"text": "article.keywords"
},
{
"code": null,
"e": 1336,
"s": 1328,
"text": "Output:"
},
{
"code": null,
"e": 1505,
"s": 1336,
"text": "['soon', 'ive', 'work', 'journey', '1000', 'took', 'followers', 'started', 'truth', 'life', 'writing', 'wasnt', 'lessons', 'doing', 'read', 'maybe', 'learned', 'youre']"
},
{
"code": null,
"e": 1527,
"s": 1505,
"text": "Summarize the article"
},
{
"code": null,
"e": 1543,
"s": 1527,
"text": "article.summary"
},
{
"code": null,
"e": 1551,
"s": 1543,
"text": "Output:"
},
{
"code": null,
"e": 2148,
"s": 1551,
"text": "'But I’ve only been writing on Medium for a total of maybe 4.5 months.\\nI started writing passionately, and you could tell from my writing that I thought I was enlightened and speaking from authority.\\nI’ve noticed that it comes in moments where I put in effort to improve myself — working out, writing, and reading.\\nYou’re just doing it to put yourself on a higher ground than your friends, to judge them from a higher platform and deem everything you’re doing more virtuous than what they’re doing.\\nI would sidestep and avoid the truth — the truth that would hurt but ultimately set me free.'"
},
{
"code": null,
"e": 2223,
"s": 2148,
"text": "With the summary, we could quickly grasp the key takeaways of the article:"
},
{
"code": null,
"e": 2330,
"s": 2223,
"text": "To become a better writer, he constantly improved his writing skills by writing, reading, and working out."
},
{
"code": null,
"e": 2393,
"s": 2330,
"text": "His motivation was once from external sources such as friends."
},
{
"code": null,
"e": 2484,
"s": 2393,
"text": "There was struggling in his journey. But by evaluating his approach, he sets himself free."
},
{
"code": null,
"e": 2554,
"s": 2484,
"text": "Let see if we could extract more insights from the article using NLTK"
},
{
"code": null,
"e": 2604,
"s": 2554,
"text": "Start with extracting the text from the newspaper"
},
{
"code": null,
"e": 2624,
"s": 2604,
"text": "text = article.text"
},
{
"code": null,
"e": 2642,
"s": 2624,
"text": "pip install nltk\n"
},
{
"code": null,
"e": 2903,
"s": 2642,
"text": "Requirement already satisfied: nltk in ./opt/anaconda3/lib/python3.7/site-packages (3.4.5)\nRequirement already satisfied: six in ./opt/anaconda3/lib/python3.7/site-packages (from nltk) (1.12.0)\nNote: you may need to restart the kernel to use updated packages.\n"
},
{
"code": null,
"e": 2916,
"s": 2903,
"text": "import nltk\n"
},
{
"code": null,
"e": 2933,
"s": 2916,
"text": "nltk.download()\n"
},
{
"code": null,
"e": 3015,
"s": 2933,
"text": "showing info https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/index.xml\n"
},
{
"code": null,
"e": 3020,
"s": 3015,
"text": "True"
},
{
"code": null,
"e": 3039,
"s": 3020,
"text": "Remove punctuation"
},
{
"code": null,
"e": 3191,
"s": 3039,
"text": "from nltk.tokenize import RegexpTokenizer\n\ntokenizer = RegexpTokenizer(r'\\w+')\ntext = tokenizer.tokenize(text)\n\ntext = ' '.join(word for word in text)\n"
},
{
"code": null,
"e": 3206,
"s": 3191,
"text": "Tokenize words"
},
{
"code": null,
"e": 3282,
"s": 3206,
"text": "from nltk.tokenize import word_tokenize\ntokenized_word=word_tokenize(text)\n"
},
{
"code": null,
"e": 3292,
"s": 3282,
"text": "Lowercase"
},
{
"code": null,
"e": 3352,
"s": 3292,
"text": "tokenized_word = [word.lower() for word in tokenized_word]\n"
},
{
"code": null,
"e": 3369,
"s": 3352,
"text": "Remove stopwords"
},
{
"code": null,
"e": 3467,
"s": 3369,
"text": "from nltk.corpus import stopwords\nstop_words = set(stopwords.words('english'))\nprint(stop_words)\n"
},
{
"code": null,
"e": 4942,
"s": 3467,
"text": "{'t', 'under', 'will', \"should've\", 'such', 'has', 'other', 'do', 'shan', 'was', 'his', \"wouldn't\", 'he', 'if', 'ours', 'did', 'which', 'my', 'had', 'after', 'through', 'off', 'the', 'most', 'o', 'aren', 'when', 'into', 'being', 'her', 'each', 'this', 'been', 'about', 'until', 'won', 'what', 'be', 'ourselves', 'doesn', 'they', 'hers', 'am', \"it's\", 'i', 'down', 'y', 'have', 'who', 'their', 'any', 'with', 'both', 'because', 'from', 'before', 'or', 'hasn', 'haven', 'doing', 'few', 'don', \"shouldn't\", 'for', 'ain', 'by', 'having', 'some', 'our', 'm', 'no', 'weren', 'yourself', 've', 'there', 'were', \"you'll\", 's', 'should', \"won't\", 'over', 'against', 'to', \"wasn't\", \"aren't\", 'on', 'him', 'are', \"mightn't\", 'as', \"hadn't\", 'how', 'you', 'it', \"shan't\", 'hadn', 'and', 'than', 'that', \"couldn't\", 'where', 'then', 'its', 'whom', 'below', 'here', \"hasn't\", 'all', \"didn't\", \"isn't\", 'wasn', 'an', 'yourselves', 'again', \"don't\", 'why', 'theirs', 'up', 'couldn', 'just', 'can', \"doesn't\", 'so', 'own', 'd', 'wouldn', 'we', 'she', \"mustn't\", 'these', 'between', 'once', 'didn', \"you've\", \"haven't\", \"that'll\", 'but', 'needn', 'itself', \"you'd\", 'me', 'those', 'very', 'isn', 'himself', 'during', \"she's\", 'does', 'nor', 'them', 'not', 'mustn', 'now', 'same', 'your', 'll', 'yours', 'ma', 'myself', 'only', 'in', 'a', 'while', 'above', 'out', 're', 'shouldn', 'mightn', 'more', \"needn't\", 'at', \"weren't\", 'is', \"you're\", 'themselves', 'of', 'herself', 'too', 'further'}\n"
},
{
"code": null,
"e": 5055,
"s": 4942,
"text": "filtered_word = []\nfor word in tokenized_word:\n if word not in stop_words:\n filtered_word.append(word)\n \n"
},
{
"code": null,
"e": 5073,
"s": 5055,
"text": "Stemming the word"
},
{
"code": null,
"e": 5328,
"s": 5073,
"text": "from nltk.stem import PorterStemmer\n\nps = PorterStemmer()\n\nstemmed_words = []\nfor w in filtered_word:\n stemmed_words.append(ps.stem(w))\n\n#See how stemming works\nfor word in ['thinking', 'felt', 'asked','challenging','devoted']:\n print(ps.stem(word))\n"
},
{
"code": null,
"e": 5359,
"s": 5328,
"text": "think\nfelt\nask\nchalleng\ndevot\n"
},
{
"code": null,
"e": 5411,
"s": 5359,
"text": "Try with lemmatization and compare it with stemming"
},
{
"code": null,
"e": 5486,
"s": 5411,
"text": "from nltk.stem.wordnet import WordNetLemmatizer\nlem = WordNetLemmatizer()\n"
},
{
"code": null,
"e": 5570,
"s": 5486,
"text": "lem_words = []\nfor w in filtered_word:\n lem_words.append(lem.lemmatize(w,'v'))\n \n"
},
{
"code": null,
"e": 5673,
"s": 5570,
"text": "for word in ['thinking', 'felt', 'asked','challenging','devoted']:\n print(lem.lemmatize(word,'v'))\n"
},
{
"code": null,
"e": 5706,
"s": 5673,
"text": "think\nfelt\nask\nchallenge\ndevote\n"
},
{
"code": null,
"e": 5773,
"s": 5706,
"text": "from nltk.probability import FreqDist\nfdist = FreqDist(lem_words)\n"
},
{
"code": null,
"e": 5822,
"s": 5773,
"text": "most_common = fdist.most_common(20)\nmost_common\n"
},
{
"code": null,
"e": 6116,
"s": 5822,
"text": "[('write', 26),\n ('read', 11),\n ('maybe', 8),\n ('start', 8),\n ('one', 7),\n ('work', 7),\n ('know', 6),\n ('soon', 6),\n ('time', 6),\n ('think', 6),\n ('doubt', 6),\n ('would', 6),\n ('medium', 5),\n ('make', 5),\n ('truth', 5),\n ('day', 4),\n ('everyday', 4),\n ('keep', 4),\n ('could', 4),\n ('fail', 4)]"
},
{
"code": null,
"e": 6140,
"s": 6116,
"text": "pip install matplotlib\n"
},
{
"code": null,
"e": 7189,
"s": 6140,
"text": "Requirement already satisfied: matplotlib in ./opt/anaconda3/lib/python3.7/site-packages (3.1.1)\nRequirement already satisfied: cycler>=0.10 in ./opt/anaconda3/lib/python3.7/site-packages (from matplotlib) (0.10.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in ./opt/anaconda3/lib/python3.7/site-packages (from matplotlib) (1.1.0)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in ./opt/anaconda3/lib/python3.7/site-packages (from matplotlib) (2.4.2)\nRequirement already satisfied: python-dateutil>=2.1 in ./opt/anaconda3/lib/python3.7/site-packages (from matplotlib) (2.8.0)\nRequirement already satisfied: numpy>=1.11 in ./opt/anaconda3/lib/python3.7/site-packages (from matplotlib) (1.17.2)\nRequirement already satisfied: six in ./opt/anaconda3/lib/python3.7/site-packages (from cycler>=0.10->matplotlib) (1.12.0)\nRequirement already satisfied: setuptools in ./opt/anaconda3/lib/python3.7/site-packages (from kiwisolver>=1.0.1->matplotlib) (41.4.0)\nNote: you may need to restart the kernel to use updated packages.\n"
},
{
"code": null,
"e": 7222,
"s": 7189,
"text": "import matplotlib.pyplot as plt\n"
},
{
"code": null,
"e": 7373,
"s": 7222,
"text": "plt.figure(figsize=(20,5))\nplt.plot([word[0] for word in most_common], [word[1] for word in most_common])\nplt.xlabel('Words')\nplt.ylabel('Frequency')\n"
},
{
"code": null,
"e": 7399,
"s": 7373,
"text": "Text(0, 0.5, 'Frequency')"
},
{
"code": null,
"e": 7502,
"s": 7402,
"text": "By looking at the plot of the most frequent words, we have a better idea of what the article about."
},
{
"code": null,
"e": 7605,
"s": 7502,
"text": "Let’s utilize another tool called WordClouds to create a more interesting visualization of our article"
},
{
"code": null,
"e": 8045,
"s": 7605,
"text": "From this list of words, I could guess the general idea of the article: Becoming a better writer takes effort. You have to consistently write and read every day to improve your skills. There may be doubts and fear, but things will eventually improve if you trust the journey and keep your eyes on the bigger vision. Now, I could dive into reading this article since I know it will give me practical lessons for improving my writing skills."
},
{
"code": null,
"e": 8322,
"s": 8045,
"text": "newspaper3k andnltk are the great combination for extracting the essential information from an online article. You could also utilize this tool to grasp the general ideas of the article to decide whether the article is worthy of reading or to analyze several articles at once."
},
{
"code": null,
"e": 8401,
"s": 8322,
"text": "Feel free to fork and play with the code for this article in this Github repo."
},
{
"code": null,
"e": 8561,
"s": 8401,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
},
{
"code": null,
"e": 8737,
"s": 8561,
"text": "Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:"
},
{
"code": null,
"e": 8760,
"s": 8737,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8783,
"s": 8760,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8806,
"s": 8783,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8817,
"s": 8806,
"text": "medium.com"
},
{
"code": null,
"e": 8901,
"s": 8817,
"text": "[1]https://care.pressreader.com/hc/en-us/articles/203210155-Advanced-Keyword-Search"
}
] |
How can I create a MySQL stored procedure that returns multiple values from a MySQL table? | We can create a stored procedure with both IN and OUT parameters to get multiple values from a MySQL table. To make it understand we are taking an example of a table named ‘student_info’ having the following data −
mysql> Select * from student_info;
+------+---------+------------+------------+
| id | Name | Address | Subject |
+------+---------+------------+------------+
| 101 | YashPal | Amritsar | History |
| 105 | Gaurav | Jaipur | Literature |
| 110 | Rahul | Chandigarh | History |
| 125 | Raman | Bangalore | Computers |
+------+---------+------------+------------+
4 rows in set (0.01 sec)
Now, by creating the procedure named ‘select_studentinfo’ as follow, we can select the values from ‘student_info’ table by providing the value of ‘id’ −
mysql> DELIMITER // ;
mysql> Create Procedure Select_studentinfo ( IN p_id INT, OUT p_name varchar(20),OUT p_address varchar(20), OUT p_subject varchar(20))
-> BEGIN
-> SELECT name, address, subject INTO p_name, p_address, p_subject
-> FROM student_info
-> WHERE id = p_id;
-> END //
Query OK, 0 rows affected (0.03 sec)
In the query above, along with 1 IN parameters, it is taking 4 OUT parameters also. Now, invoke the procedure with the values we want to provide as condition as follows −
mysql> DELIMITER ; //
mysql> CALL Select_studentinfo(110, @p_name, @p_address, @p_subject);
Query OK, 1 row affected (0.06 sec)
mysql> Select @p_name AS Name,@p_Address AS Address, @p_subject AS Subject;
+--------+------------+-----------+
| Name | Address | Subject |
+--------+------------+-----------+
| Rahul | Chandigarh | History |
+--------+------------+-----------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1277,
"s": 1062,
"text": "We can create a stored procedure with both IN and OUT parameters to get multiple values from a MySQL table. To make it understand we are taking an example of a table named ‘student_info’ having the following data −"
},
{
"code": null,
"e": 1697,
"s": 1277,
"text": "mysql> Select * from student_info;\n+------+---------+------------+------------+\n| id | Name | Address | Subject |\n+------+---------+------------+------------+\n| 101 | YashPal | Amritsar | History |\n| 105 | Gaurav | Jaipur | Literature |\n| 110 | Rahul | Chandigarh | History |\n| 125 | Raman | Bangalore | Computers |\n+------+---------+------------+------------+\n4 rows in set (0.01 sec)"
},
{
"code": null,
"e": 1850,
"s": 1697,
"text": "Now, by creating the procedure named ‘select_studentinfo’ as follow, we can select the values from ‘student_info’ table by providing the value of ‘id’ −"
},
{
"code": null,
"e": 2191,
"s": 1850,
"text": "mysql> DELIMITER // ;\nmysql> Create Procedure Select_studentinfo ( IN p_id INT, OUT p_name varchar(20),OUT p_address varchar(20), OUT p_subject varchar(20))\n -> BEGIN\n -> SELECT name, address, subject INTO p_name, p_address, p_subject\n -> FROM student_info\n -> WHERE id = p_id;\n -> END //\nQuery OK, 0 rows affected (0.03 sec)"
},
{
"code": null,
"e": 2362,
"s": 2191,
"text": "In the query above, along with 1 IN parameters, it is taking 4 OUT parameters also. Now, invoke the procedure with the values we want to provide as condition as follows −"
},
{
"code": null,
"e": 2771,
"s": 2362,
"text": "mysql> DELIMITER ; //\nmysql> CALL Select_studentinfo(110, @p_name, @p_address, @p_subject);\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> Select @p_name AS Name,@p_Address AS Address, @p_subject AS Subject;\n+--------+------------+-----------+\n| Name | Address | Subject |\n+--------+------------+-----------+\n| Rahul | Chandigarh | History |\n+--------+------------+-----------+\n1 row in set (0.00 sec)"
}
] |
How to read volley json array in android? | This example demonstrate about How to read volley json array in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:textSize="30sp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
In the above code, we have taken text view to show json array.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
TextView textView;
RequestQueue queue;
String URL = "http://www.mocky.io/v2/597c41390f0000d002f4dbd1";
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
textView.setText(response.toString());
try {
JSONObject object=new JSONObject(response);
JSONArray array=object.getJSONArray("users");
for(int i=0;i<array.length();i++) {
JSONObject object1=array.getJSONObject(i);
textView.setText(object1.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
});
queue.add(request);
}
}
Step 4 − Add the following code to AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 5 − Add the following code to build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.volley:volley:1.1.0'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "This example demonstrate about How to read volley json array in android."
},
{
"code": null,
"e": 1264,
"s": 1135,
"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": 1329,
"s": 1264,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1863,
"s": 1329,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:gravity=\"center\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"30sp\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1926,
"s": 1863,
"text": "In the above code, we have taken text view to show json array."
},
{
"code": null,
"e": 1983,
"s": 1926,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3900,
"s": 1983,
"text": "package com.example.myapplication;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport com.android.volley.Request;\nimport com.android.volley.RequestQueue;\nimport com.android.volley.Response;\nimport com.android.volley.VolleyError;\nimport com.android.volley.toolbox.StringRequest;\nimport com.android.volley.toolbox.Volley;\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n RequestQueue queue;\n String URL = \"http://www.mocky.io/v2/597c41390f0000d002f4dbd1\";\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n queue = Volley.newRequestQueue(this);\n StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {\n @Override\n public void onResponse(String response) {\n textView.setText(response.toString());\n try {\n JSONObject object=new JSONObject(response);\n JSONArray array=object.getJSONArray(\"users\");\n for(int i=0;i<array.length();i++) {\n JSONObject object1=array.getJSONObject(i);\n textView.setText(object1.toString());\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.d(\"error\",error.toString());\n }\n });\n queue.add(request);\n }\n}"
},
{
"code": null,
"e": 3955,
"s": 3900,
"text": "Step 4 − Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 4780,
"s": 3955,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.myapplication\">\n <uses-permission android:name=\"android.permission.INTERNET\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <action android:name=\"android.net.conn.CONNECTIVITY_CHANGE\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4828,
"s": 4780,
"text": "Step 5 − Add the following code to build.gradle"
},
{
"code": null,
"e": 5763,
"s": 4828,
"text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.myapplication\"\n minSdkVersion 15\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\nimplementation fileTree(dir: 'libs', include: ['*.jar'])\nimplementation 'com.android.volley:volley:1.1.0'\nimplementation 'com.android.support:appcompat-v7:28.0.0'\nimplementation 'com.android.support.constraint:constraint-layout:1.1.3'\ntestImplementation 'junit:junit:4.12'\nandroidTestImplementation 'com.android.support.test:runner:1.0.2'\nandroidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}"
},
{
"code": null,
"e": 6110,
"s": 5763,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 6150,
"s": 6110,
"text": "Click here to download the project code"
}
] |
Python MongoDB - Introduction | Pymongo is a python distribution which provides tools to work with MongoDB, it is the most preferred way to communicate with MongoDB database from python.
To install pymongo first of all make sure you have installed python3 (along with PIP) and MongoDB properly. Then execute the following command.
C:\WINDOWS\system32>pip install pymongo
Collecting pymongo
Using cached https://files.pythonhosted.org/packages/cb/a6/b0ae3781b0ad75825e00e29dc5489b53512625e02328d73556e1ecdf12f8/pymongo-3.9.0-cp37-cp37m-win32.whl
Installing collected packages: pymongo
Successfully installed pymongo-3.9.0
Once you have installed pymongo, open a new text document, paste the following line in it and, save it as test.py.
import pymongo
If you have installed pymongo properly, if you execute the test.py as shown below, you should not get any issues.
D:\Python_MongoDB>test.py
D:\Python_MongoDB>
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": 3360,
"s": 3205,
"text": "Pymongo is a python distribution which provides tools to work with MongoDB, it is the most preferred way to communicate with MongoDB database from python."
},
{
"code": null,
"e": 3504,
"s": 3360,
"text": "To install pymongo first of all make sure you have installed python3 (along with PIP) and MongoDB properly. Then execute the following command."
},
{
"code": null,
"e": 3795,
"s": 3504,
"text": "C:\\WINDOWS\\system32>pip install pymongo\nCollecting pymongo\nUsing cached https://files.pythonhosted.org/packages/cb/a6/b0ae3781b0ad75825e00e29dc5489b53512625e02328d73556e1ecdf12f8/pymongo-3.9.0-cp37-cp37m-win32.whl\nInstalling collected packages: pymongo\nSuccessfully installed pymongo-3.9.0\n"
},
{
"code": null,
"e": 3910,
"s": 3795,
"text": "Once you have installed pymongo, open a new text document, paste the following line in it and, save it as test.py."
},
{
"code": null,
"e": 3926,
"s": 3910,
"text": "import pymongo\n"
},
{
"code": null,
"e": 4040,
"s": 3926,
"text": "If you have installed pymongo properly, if you execute the test.py as shown below, you should not get any issues."
},
{
"code": null,
"e": 4086,
"s": 4040,
"text": "D:\\Python_MongoDB>test.py\nD:\\Python_MongoDB>\n"
},
{
"code": null,
"e": 4123,
"s": 4086,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4139,
"s": 4123,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4172,
"s": 4139,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4191,
"s": 4172,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4226,
"s": 4191,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4248,
"s": 4226,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4282,
"s": 4248,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4310,
"s": 4282,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4345,
"s": 4310,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4359,
"s": 4345,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4392,
"s": 4359,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4409,
"s": 4392,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4416,
"s": 4409,
"text": " Print"
},
{
"code": null,
"e": 4427,
"s": 4416,
"text": " Add Notes"
}
] |
C program to print environment variables | Here, we will create a c program to print environment variables.
Environment variable is a global variable that can affect the way the running process will behave on the system.
//Program to print environment variables
Live Demo
#include <stdio.h>
int main(int argc, char *argv[], char * envp[]){
int i;
for (i = 0; envp[i] != NULL; i++)
printf("\n%s", envp[i]);
getchar();
return 0;
}
ALLUSERSPROFILE=C:\ProgramData
CommonProgramFiles=C:\Program Files\Common Files
HOMEDRIVE=C:
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_IDENTIFIER=x86 Family 6 Model 42 Stepping 7, GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=2a07
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
PUBLIC=C:\Users\Public
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\Windows
WATCOM=C:\watcom
windir=C:\Windows | [
{
"code": null,
"e": 1127,
"s": 1062,
"text": "Here, we will create a c program to print environment variables."
},
{
"code": null,
"e": 1240,
"s": 1127,
"text": "Environment variable is a global variable that can affect the way the running process will behave on the system."
},
{
"code": null,
"e": 1281,
"s": 1240,
"text": "//Program to print environment variables"
},
{
"code": null,
"e": 1292,
"s": 1281,
"text": " Live Demo"
},
{
"code": null,
"e": 1464,
"s": 1292,
"text": "#include <stdio.h>\nint main(int argc, char *argv[], char * envp[]){\n int i;\n for (i = 0; envp[i] != NULL; i++)\n printf(\"\\n%s\", envp[i]);\n getchar();\n return 0;\n}"
},
{
"code": null,
"e": 1965,
"s": 1464,
"text": "ALLUSERSPROFILE=C:\\ProgramData\nCommonProgramFiles=C:\\Program Files\\Common Files\nHOMEDRIVE=C:\nNUMBER_OF_PROCESSORS=2\nOS=Windows_NT\nPATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC\nPROCESSOR_ARCHITECTURE=x86\nPROCESSOR_IDENTIFIER=x86 Family 6 Model 42 Stepping 7, GenuineIntel\nPROCESSOR_LEVEL=6\nPROCESSOR_REVISION=2a07\nProgramData=C:\\ProgramData\nProgramFiles=C:\\Program Files\nPUBLIC=C:\\Users\\Public\nSESSIONNAME=Console\nSystemDrive=C:\nSystemRoot=C:\\Windows\nWATCOM=C:\\watcom\nwindir=C:\\Windows"
}
] |
Java program to split and join a string | To split and join a string in Java, use the split() and join() method as in the below example −
public class Demo{
public static void main(String args[]){
String my_str = "This_is_a_sample";
String[] split_str = my_str.split("_", 4);
System.out.println("The split string is:");
for (String every_Str : split_str)
System.out.println(every_Str);
String joined_str = String.join("_", "This", "is", "a", "sample");
System.out.println("The joined string is:");
System.out.println(joined_str);
}
}
The split string is:
This
is
a
sample
The joined string is:
This_is_a_sample
A class named Demo contains the main function. Here a String object is defined and it is split based on the ‘_’ value upto the last word. A ‘for’ loop is iterated over and the string is split based on the ‘_’ value. Again, the string is joined using the ‘join’ function. Relevant messages are displayed on the console. | [
{
"code": null,
"e": 1158,
"s": 1062,
"text": "To split and join a string in Java, use the split() and join() method as in the below example −"
},
{
"code": null,
"e": 1608,
"s": 1158,
"text": "public class Demo{\n public static void main(String args[]){\n String my_str = \"This_is_a_sample\";\n String[] split_str = my_str.split(\"_\", 4);\n System.out.println(\"The split string is:\");\n for (String every_Str : split_str)\n System.out.println(every_Str);\n String joined_str = String.join(\"_\", \"This\", \"is\", \"a\", \"sample\");\n System.out.println(\"The joined string is:\");\n System.out.println(joined_str);\n }\n}"
},
{
"code": null,
"e": 1685,
"s": 1608,
"text": "The split string is:\nThis\nis\na\nsample\nThe joined string is:\nThis_is_a_sample"
},
{
"code": null,
"e": 2004,
"s": 1685,
"text": "A class named Demo contains the main function. Here a String object is defined and it is split based on the ‘_’ value upto the last word. A ‘for’ loop is iterated over and the string is split based on the ‘_’ value. Again, the string is joined using the ‘join’ function. Relevant messages are displayed on the console."
}
] |
PHP - Function eregi_replace() | string eregi_replace (string pattern, string replacement, string originalstring);
The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern in string is not case sensitive.
After the replacement has occurred, the modified string will be returned.
After the replacement has occurred, the modified string will be returned.
If no matches are found, the string will remain unchanged.
If no matches are found, the string will remain unchanged.
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$copy_date = "Copyright 2000";
$copy_date = eregi_replace("([a-z]+)", "&Copy;", $copy_date);
print $copy_date;
?>
This will produce the following result −
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2840,
"s": 2757,
"text": "string eregi_replace (string pattern, string replacement, string originalstring);\n"
},
{
"code": null,
"e": 2975,
"s": 2840,
"text": "The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern in string is not case sensitive."
},
{
"code": null,
"e": 3049,
"s": 2975,
"text": "After the replacement has occurred, the modified string will be returned."
},
{
"code": null,
"e": 3123,
"s": 3049,
"text": "After the replacement has occurred, the modified string will be returned."
},
{
"code": null,
"e": 3182,
"s": 3123,
"text": "If no matches are found, the string will remain unchanged."
},
{
"code": null,
"e": 3241,
"s": 3182,
"text": "If no matches are found, the string will remain unchanged."
},
{
"code": null,
"e": 3333,
"s": 3241,
"text": "Following is the piece of code, copy and paste this code into a file and verify the result."
},
{
"code": null,
"e": 3466,
"s": 3333,
"text": "<?php\n $copy_date = \"Copyright 2000\";\n $copy_date = eregi_replace(\"([a-z]+)\", \"&Copy;\", $copy_date);\n \n print $copy_date;\n?>"
},
{
"code": null,
"e": 3507,
"s": 3466,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3540,
"s": 3507,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 3556,
"s": 3540,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3589,
"s": 3556,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3600,
"s": 3589,
"text": " Syed Raza"
},
{
"code": null,
"e": 3635,
"s": 3600,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3652,
"s": 3635,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3685,
"s": 3652,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3700,
"s": 3685,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 3735,
"s": 3700,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 3747,
"s": 3735,
"text": " Azaz Patel"
},
{
"code": null,
"e": 3782,
"s": 3747,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3810,
"s": 3782,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 3817,
"s": 3810,
"text": " Print"
},
{
"code": null,
"e": 3828,
"s": 3817,
"text": " Add Notes"
}
] |
Find average of a list in python? | Python provides sum function for calculating n number of element. Here we use this function and then calculate average.
Step 1: input “size of the list”
Step 2: input “Element”
Step 3: using sum function calculate summation of all numbers.
Step 4: calculate average.
# Average of a list
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the number ::")
for i in range(int(n)):
k=int(input(""))
A.append(int(k))
sm=sum(A)
avg=sm/n
print("SUM = ",sm)
print("AVERAGE = ",avg)
Enter the size of the List ::5
Enter the number::
10
20
30
40
50
SUM = 150
AVERAGE = 30.0 | [
{
"code": null,
"e": 1182,
"s": 1062,
"text": "Python provides sum function for calculating n number of element. Here we use this function and then calculate average."
},
{
"code": null,
"e": 1330,
"s": 1182,
"text": "Step 1: input “size of the list”\nStep 2: input “Element”\nStep 3: using sum function calculate summation of all numbers.\nStep 4: calculate average.\n"
},
{
"code": null,
"e": 1560,
"s": 1330,
"text": "# Average of a list\nA=list()\nn=int(input(\"Enter the size of the List ::\"))\nprint(\"Enter the number ::\")\nfor i in range(int(n)):\n k=int(input(\"\"))\n A.append(int(k))\nsm=sum(A)\navg=sm/n\nprint(\"SUM = \",sm)\nprint(\"AVERAGE = \",avg)"
},
{
"code": null,
"e": 1651,
"s": 1560,
"text": "Enter the size of the List ::5\nEnter the number::\n10\n20\n30\n40\n50\nSUM = 150\nAVERAGE = 30.0\n"
}
] |
XGBoost: A Complete Guide to Fine-Tune and Optimize your Model | by David Martins | Towards Data Science | Initially started as a research project in 2014, XGBoost has quickly become one of the most popular Machine Learning algorithms of the past few years.
Many consider it as one of the best algorithms and, due to its great performance for regression and classification problems, would recommend it as a first choice in many situations. XGBoost has become famous for winning tons of Kaggle competitions, is now used in many industry-application, and is even implemented within machine-learning platforms, such as BigQuery ML.
If you’re reading this article on XGBoost hyperparameters optimization, you’re probably familiar with the algorithm. But to better understand what we want to tune, let's have a recap!
XGBoost (eXtreme Gradient Boosting) is not only an algorithm. It’s an entire open-source library, designed as an optimized implementation of the Gradient Boosting framework. It focuses on speed, flexibility, and model performances. Its strength doesn’t only come from the algorithm, but also from all the underlying system optimization (parallelization, caching, hardware optimization, etc...).
In most cases, data scientist uses XGBoost with a“Tree Base learner”, which means that your XGBoost model is based on Decision Trees. But even though they are way less popular, you can also use XGboost with other base learners, such as linear model or Dart. As this is by far the most common situation, we’ll focus on Trees for the rest of this article.
At that point, you probably have even more questions. What is a Decision Tree? What is Boosting? What the difference with Gradient Boosting?Don’t worry, we’ll recap it all!
Decision tree is one of the simplest ML algorithms.
It is a way to implement an algorithm that only contains conditional statements.
XGBoost uses a type of decision tree called CART: Classification and Decision Tree.
Classification Trees: the target variable is categorical and the tree is used to identify the “class” within which a target variable would likely fall.
Regression Trees: the target variable is continuous and the tree is used to predict its value.
CART leaves don’t simply contain final decision values, but also real-valued scores for each leaf, no matter if they are used for classification or regression.
Boosting is just a method that uses the principle of ensemble learning, but in sequential order.
If you’re not familiar with ensemble learning, it’s a process that combines decisions from multiple underlying models, and uses a voting technique to determine the final prediction.
Random forests and Bagging are two famous ensemble learning methods.
Boosting is a type of ensemble learning that uses the previous model's result as an input to the next one. Instead of training models separately, boosting trains models sequentially, each new model being trained to correct the errors of the previous ones. At each iteration (round), the outcomes predicted correctly are given a lower weight, and the ones wrongly predicted a higher weight. It then uses a weighted average to produce a final outcome.
Finally, Gradient Boosting is a boosting method where errors are minimized using a gradient descent algorithm. Simply put, Gradient descent is an iterative optimization algorithm used to minimize a loss function.
The loss function quantifies how far off our prediction is from the actual result for a given data point. The better the predictions, the lower will be the output of your loss function.
When we construct our model, the goal is to minimize the loss function across all of the data points. For example, Mean squared error (MSE) is the most commonly used loss function for regression.
Contrary to classic Boosting, Gradient boosting not only weight higher wrongly predicted outcomes, but also adjust those weights based on a gradient — given by the direction in the loss function where the loss “decreases the fastest”. If you want to learn more about Gradient Boosting, you can check out this video.
And as we said in the intro, XGBoost is an optimized implementation of this Gradient Boosting method!
There are 2 common ways of using XGBoost:
Learning API: It is the basic, low-level way of using XGBoost. Simple and powerful, it includes a built-in cross-validation method.
import xgboost as xgb X, y = #Import your datadmatrix = xgb.DMatrix(data=x, label=y) #Learning API uses a dmatrixparams = {'objective':'reg:squarederror'}cv_results = xgb.cv(dtrain=dmatrix, params=params, nfold=10, metrics={'rmse'})print('RMSE: %.2f' % cv_results['test-rmse-mean'].min())
Scikit-Learn API: It is a Scikit-Learn wrapper interface for XGBoost. It allows using XGBoost in a scikit-learn compatible way, the same way you would use any native scikit-learn model.
import xgboost as xgbX, y = # Import your dataxtrain, xtest, ytrain, ytest = train_test_split(X, y, test_size=0.2)xgbr = xgb.XGBRegressor(objective='reg:squarederror')xgbr.fit(xtrain, ytrain) ypred = xgbr.predict(xtest)mse = mean_squared_error(ytest, ypred)print("RMSE: %.2f" % (mse**(1/2.0)))
Note that when using the Learning API you can input and access an evaluation metric, whereas when using the Scikit-learn API you have to calculate it.
XGBoost is a great choice in multiple situations, including regression and classification problems. Based on the problem and how you want your model to learn, you’ll choose a different objective function.
The most commonly used are:
reg:squarederror: for linear regression
reg:logistic: for logistic regression
binary:logistic: for logistic regression — with output of the probabilities
How would an untuned model perform compared to a tuned model? Is it worth the effort? Before going deeper into XGBoost model tuning, let’s highlight the reasons why you have to tune your model.
As a demo, we will use the well-known Boston house prices dataset from sklearn, and try to predict the prices of houses.
Here how would perform our model without hyperparameter tuning:
import xgboost as xgbfrom sklearn.datasets import load_bostonfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error boston = load_boston()X, y = boston.data, boston.targetdmatrix = xgb.DMatrix(data=x, label=y)params={'objective':'reg:squarederror'}cv_results = xgb.cv(dtrain=dmatrix, params=params, nfold=10, metrics={'rmse'}, as_pandas=True, seed=20)print('RMSE: %.2f' % cv_results['test-rmse-mean'].min())## Result : RMSE: 3.38
Without any tuning, we’ve got a RMSE of 3.38. Which isn’t bad, but let’s see how it would perform with just a few tuned hyperparameters:
import xgboost as xgbfrom sklearn.datasets import load_bostonfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error boston = load_boston()X, y = boston.data, boston.targetdmatrix = xgb.DMatrix(data=x, label=y)params={ 'objective':'reg:squarederror', 'max_depth': 6, 'colsample_bylevel':0.5, 'learning_rate':0.01, 'random_state':20}cv_results = xgb.cv(dtrain=dmatrix, params=params, nfold=10, metrics={'rmse'}, as_pandas=True, seed=20, num_boost_round=1000)print('RMSE: %.2f' % cv_results['test-rmse-mean'].min())## Result : RMSE: 2.69
With just a little bit of tuning, we’ve now got a RMSE of 2.69. It’s a 20% improvement! And we could probably improve even more. Let’s see how!
A hyperparameter is a type of parameter, external to the model, set before the learning process begins. It’s tunable and can directly affect how well a model performs.
To find out the best hyperparameters for your model, you may use rules of thumb, or specific methods that we’ll review in this article.
Before that, note that there are several parameters you can tune when working with XGBoost. You can find the complete list here, or the aliases used in the Scikit-Learn API.
For Tree base learners, the most common parameters are:
max_depth: The maximum depth per tree. A deeper tree might increase the performance, but also the complexity and chances to overfit.The value must be an integer greater than 0. Default is 6.
learning_rate: The learning rate determines the step size at each iteration while your model optimizes toward its objective. A low learning rate makes computation slower, and requires more rounds to achieve the same reduction in residual error as a model with a high learning rate. But it optimizes the chances to reach the best optimum.The value must be between 0 and 1. Default is 0.3.
n_estimators: The number of trees in our ensemble. Equivalent to the number of boosting rounds.The value must be an integer greater than 0. Default is 100.NB: In the standard library, this is referred as num_boost_round.
colsample_bytree: Represents the fraction of columns to be randomly sampled for each tree. It might improve overfitting.The value must be between 0 and 1. Default is 1.
subsample: Represents the fraction of observations to be sampled for each tree. A lower values prevent overfitting but might lead to under-fitting.The value must be between 0 and 1. Default is 1.
Regularization parameters:
alpha (reg_alpha): L1 regularization on the weights (Lasso Regression). When working with a large number of features, it might improve speed performances. It can be any integer. Default is 0.
lambda (reg_lambda): L2 regularization on the weights (Ridge Regression). It might help to reduce overfitting. It can be any integer. Default is 1.
gamma: Gamma is a pseudo-regularisation parameter (Lagrangian multiplier), and depends on the other parameters. The higher Gamma is, the higher the regularization. It can be any integer. Default is 0.
A first approach would be to start with reasonable parameters and to play along. If you understood the meanings of each hyperparameter above, you should be able to intuitively set some values.
Let’s start with reasonable values. It would usually be:
max_depth: 3–10n_estimators: 100 (lots of observations) to 1000 (few observations)learning_rate: 0.01–0.3colsample_bytree: 0.5–1subsample: 0.6–1
Then, you can focus on optimizing max_depth and n_estimators.
You can then play along with the learning_rate, and increase it to speed up the model without decreasing the performances. If it becomes faster without losing in performances, you can increase the number of estimators to try to increase the performances.
Finally, you can work with your regularization parameters, usually starting with alpha and lambda. For gamma, 0 would mean no regularization, 1–5 are commonly used values, whereas 10+ would be considered as very high.
A second approach to find the best hyperparameters is through Optimization Algorithm. Since XGBoost is available in a Scikit-learn compatible way, you can work with Scikit-learn’s hyperparameter optimizer functions!
The two most common are Grid Search and Random Search.
A Grid Search is an exhaustive search over every combination of specified parameter values. If you specify 2 possible values for max_depth and 3 for n_estimators, Grid Search will iterate over 6 possible combinations:
max_depth: [3,6],n_estimators:[100, 200, 300]
Would result in the following possibilities:max_depth: 3, n_estimators: 100max_depth: 3, n_estimators: 200max_depth: 3, n_estimators: 300max_depth: 6, n_estimators: 100max_depth: 6, n_estimators: 200max_depth: 6, n_estimators: 300
Let’s use GridSearchCV() from Scikit-learn to tune our XGBoost model!
In the following examples, we’ll use a processed version of the Life Expectancy dataset available on Kaggle.
import pandas as pdimport xgboost as xgbfrom sklearn.model_selection import GridSearchCVdata = pd.read_csv("life_expectancy_clean.csv")X, y = data[data.columns.tolist()[:-1]], data[data.columns.tolist()[-1]]params = { 'max_depth': [3,6,10], 'learning_rate': [0.01, 0.05, 0.1], 'n_estimators': [100, 500, 1000], 'colsample_bytree': [0.3, 0.7]}xgbr = xgb.XGBRegressor(seed = 20)clf = GridSearchCV(estimator=xgbr, param_grid=params, scoring='neg_mean_squared_error', verbose=1)clf.fit(X, y)print("Best parameters:", clf.best_params_)print("Lowest RMSE: ", (-clf.best_score_)**(1/2.0))
estimator: GridSearchCV is part of sklearn.model_selection, and works with any scikit-learn compatible estimator. We use xgb.XGBRegressor(), from XGBoost’s Scikit-learn API.
param_grid: GridSearchCV takes a list of parameters to test in input. As we said, a Grid Search will test out every combination.
scoring: It’s the metric(s) that will be used to evaluate the performance of the cross-validated model. In this case, neg_mean_squared_error is used in replacement for mean_squared_error. GridSearchCV is simply using a negative version of MSE for technical reasons — so it makes the function generalizable to other metrics where we aim for the higher score instead of the lower.
verbose: Controls the verbosity. The higher, the more messages.
More parameters as available, as you can find out in the documentation.
Finally, the lowest RMSE based on the negative value of clf.best_score_And the best parameters with clf.best_params_
Best parameters: {'colsample_bytree': 0.7, 'learning_rate': 0.05, 'max_depth': 6, 'n_estimators': 500}
A Random Search uses a large (possibly infinite) range of hyperparameters values, and randomly iterates a specified number of times over combinations of those values. Contrary to a Grid Search which iterates over every possible combination, with a Random Search you specify the number of iterations.
If you input 10 possible values for max_depth, 200 possible values for n_estimators, and choose to do 10 iterations:
max_depth: np.arrange(1,10,1),n_estimators: np.arrange(100,400,2)
Example of random possibilities with 10 iterations:1: max_depth: 1, n_estimators: 1102: max_depth: 3, n_estimators: 2223: max_depth: 3, n_estimators: 3064: max_depth: 4, n_estimators: 1025: max_depth: 1, n_estimators: 3986: max_depth: 6, n_estimators: 2907: max_depth: 9, n_estimators: 1028: max_depth: 6, n_estimators: 3109: max_depth: 3, n_estimators: 34410: max_depth: 6, n_estimators: 202
Now, let’s use RandomSearchCV() from Scikit-learn to tune our model!
import pandas as pdimport numpy as npimport xgboost as xgbfrom sklearn.model_selection import RandomizedSearchCVdata = pd.read_csv("life_expectancy_clean.csv")X, y = data[data.columns.tolist()[:-1]], data[data.columns.tolist()[-1]]params = { 'max_depth': [3, 5, 6, 10, 15, 20], 'learning_rate': [0.01, 0.1, 0.2, 0.3], 'subsample': np.arange(0.5, 1.0, 0.1), 'colsample_bytree': np.arange(0.4, 1.0, 0.1), 'colsample_bylevel': np.arange(0.4, 1.0, 0.1), 'n_estimators': [100, 500, 1000]}xgbr = xgb.XGBRegressor(seed = 20)clf = RandomizedSearchCV(estimator=xgbr, param_distributions=params, scoring='neg_mean_squared_error', n_iter=25, verbose=1)clf.fit(X, y)print("Best parameters:", clf.best_params_)print("Lowest RMSE: ", (-clf.best_score_)**(1/2.0))
Most RandomizedSearchCV’s parameters are similar to GridSearchCV’s.
n_iter: It’s the number of parameter combinations that are sampled.The higher, the more combinations you’ll be testing. It trades off runtime and quality of the solution.
As for GridSearchCV, we print the best parameters with clf.best_params_And the lowest RMSE based on the negative value of clf.best_score_
In this article, we explained how XGBoost operates to better understand how to tune its hyperparameters. As we’ve seen, tuning usually results in a big improvement in model performances.
Using our intuition to tune our model might sometimes be enough. It is also worth trying Optimization Algorithms like GridSearch and RandomSearch.But most of the time, you’ll get an even better result with a mix of Algorithms and adjustments through testing and intuition! | [
{
"code": null,
"e": 323,
"s": 172,
"text": "Initially started as a research project in 2014, XGBoost has quickly become one of the most popular Machine Learning algorithms of the past few years."
},
{
"code": null,
"e": 694,
"s": 323,
"text": "Many consider it as one of the best algorithms and, due to its great performance for regression and classification problems, would recommend it as a first choice in many situations. XGBoost has become famous for winning tons of Kaggle competitions, is now used in many industry-application, and is even implemented within machine-learning platforms, such as BigQuery ML."
},
{
"code": null,
"e": 878,
"s": 694,
"text": "If you’re reading this article on XGBoost hyperparameters optimization, you’re probably familiar with the algorithm. But to better understand what we want to tune, let's have a recap!"
},
{
"code": null,
"e": 1273,
"s": 878,
"text": "XGBoost (eXtreme Gradient Boosting) is not only an algorithm. It’s an entire open-source library, designed as an optimized implementation of the Gradient Boosting framework. It focuses on speed, flexibility, and model performances. Its strength doesn’t only come from the algorithm, but also from all the underlying system optimization (parallelization, caching, hardware optimization, etc...)."
},
{
"code": null,
"e": 1627,
"s": 1273,
"text": "In most cases, data scientist uses XGBoost with a“Tree Base learner”, which means that your XGBoost model is based on Decision Trees. But even though they are way less popular, you can also use XGboost with other base learners, such as linear model or Dart. As this is by far the most common situation, we’ll focus on Trees for the rest of this article."
},
{
"code": null,
"e": 1800,
"s": 1627,
"text": "At that point, you probably have even more questions. What is a Decision Tree? What is Boosting? What the difference with Gradient Boosting?Don’t worry, we’ll recap it all!"
},
{
"code": null,
"e": 1852,
"s": 1800,
"text": "Decision tree is one of the simplest ML algorithms."
},
{
"code": null,
"e": 1933,
"s": 1852,
"text": "It is a way to implement an algorithm that only contains conditional statements."
},
{
"code": null,
"e": 2017,
"s": 1933,
"text": "XGBoost uses a type of decision tree called CART: Classification and Decision Tree."
},
{
"code": null,
"e": 2169,
"s": 2017,
"text": "Classification Trees: the target variable is categorical and the tree is used to identify the “class” within which a target variable would likely fall."
},
{
"code": null,
"e": 2264,
"s": 2169,
"text": "Regression Trees: the target variable is continuous and the tree is used to predict its value."
},
{
"code": null,
"e": 2424,
"s": 2264,
"text": "CART leaves don’t simply contain final decision values, but also real-valued scores for each leaf, no matter if they are used for classification or regression."
},
{
"code": null,
"e": 2521,
"s": 2424,
"text": "Boosting is just a method that uses the principle of ensemble learning, but in sequential order."
},
{
"code": null,
"e": 2703,
"s": 2521,
"text": "If you’re not familiar with ensemble learning, it’s a process that combines decisions from multiple underlying models, and uses a voting technique to determine the final prediction."
},
{
"code": null,
"e": 2772,
"s": 2703,
"text": "Random forests and Bagging are two famous ensemble learning methods."
},
{
"code": null,
"e": 3222,
"s": 2772,
"text": "Boosting is a type of ensemble learning that uses the previous model's result as an input to the next one. Instead of training models separately, boosting trains models sequentially, each new model being trained to correct the errors of the previous ones. At each iteration (round), the outcomes predicted correctly are given a lower weight, and the ones wrongly predicted a higher weight. It then uses a weighted average to produce a final outcome."
},
{
"code": null,
"e": 3435,
"s": 3222,
"text": "Finally, Gradient Boosting is a boosting method where errors are minimized using a gradient descent algorithm. Simply put, Gradient descent is an iterative optimization algorithm used to minimize a loss function."
},
{
"code": null,
"e": 3621,
"s": 3435,
"text": "The loss function quantifies how far off our prediction is from the actual result for a given data point. The better the predictions, the lower will be the output of your loss function."
},
{
"code": null,
"e": 3817,
"s": 3621,
"text": "When we construct our model, the goal is to minimize the loss function across all of the data points. For example, Mean squared error (MSE) is the most commonly used loss function for regression."
},
{
"code": null,
"e": 4133,
"s": 3817,
"text": "Contrary to classic Boosting, Gradient boosting not only weight higher wrongly predicted outcomes, but also adjust those weights based on a gradient — given by the direction in the loss function where the loss “decreases the fastest”. If you want to learn more about Gradient Boosting, you can check out this video."
},
{
"code": null,
"e": 4235,
"s": 4133,
"text": "And as we said in the intro, XGBoost is an optimized implementation of this Gradient Boosting method!"
},
{
"code": null,
"e": 4277,
"s": 4235,
"text": "There are 2 common ways of using XGBoost:"
},
{
"code": null,
"e": 4409,
"s": 4277,
"text": "Learning API: It is the basic, low-level way of using XGBoost. Simple and powerful, it includes a built-in cross-validation method."
},
{
"code": null,
"e": 4758,
"s": 4409,
"text": "import xgboost as xgb X, y = #Import your datadmatrix = xgb.DMatrix(data=x, label=y) #Learning API uses a dmatrixparams = {'objective':'reg:squarederror'}cv_results = xgb.cv(dtrain=dmatrix, params=params, nfold=10, metrics={'rmse'})print('RMSE: %.2f' % cv_results['test-rmse-mean'].min())"
},
{
"code": null,
"e": 4944,
"s": 4758,
"text": "Scikit-Learn API: It is a Scikit-Learn wrapper interface for XGBoost. It allows using XGBoost in a scikit-learn compatible way, the same way you would use any native scikit-learn model."
},
{
"code": null,
"e": 5238,
"s": 4944,
"text": "import xgboost as xgbX, y = # Import your dataxtrain, xtest, ytrain, ytest = train_test_split(X, y, test_size=0.2)xgbr = xgb.XGBRegressor(objective='reg:squarederror')xgbr.fit(xtrain, ytrain) ypred = xgbr.predict(xtest)mse = mean_squared_error(ytest, ypred)print(\"RMSE: %.2f\" % (mse**(1/2.0)))"
},
{
"code": null,
"e": 5389,
"s": 5238,
"text": "Note that when using the Learning API you can input and access an evaluation metric, whereas when using the Scikit-learn API you have to calculate it."
},
{
"code": null,
"e": 5594,
"s": 5389,
"text": "XGBoost is a great choice in multiple situations, including regression and classification problems. Based on the problem and how you want your model to learn, you’ll choose a different objective function."
},
{
"code": null,
"e": 5622,
"s": 5594,
"text": "The most commonly used are:"
},
{
"code": null,
"e": 5662,
"s": 5622,
"text": "reg:squarederror: for linear regression"
},
{
"code": null,
"e": 5700,
"s": 5662,
"text": "reg:logistic: for logistic regression"
},
{
"code": null,
"e": 5776,
"s": 5700,
"text": "binary:logistic: for logistic regression — with output of the probabilities"
},
{
"code": null,
"e": 5970,
"s": 5776,
"text": "How would an untuned model perform compared to a tuned model? Is it worth the effort? Before going deeper into XGBoost model tuning, let’s highlight the reasons why you have to tune your model."
},
{
"code": null,
"e": 6091,
"s": 5970,
"text": "As a demo, we will use the well-known Boston house prices dataset from sklearn, and try to predict the prices of houses."
},
{
"code": null,
"e": 6155,
"s": 6091,
"text": "Here how would perform our model without hyperparameter tuning:"
},
{
"code": null,
"e": 6629,
"s": 6155,
"text": "import xgboost as xgbfrom sklearn.datasets import load_bostonfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error boston = load_boston()X, y = boston.data, boston.targetdmatrix = xgb.DMatrix(data=x, label=y)params={'objective':'reg:squarederror'}cv_results = xgb.cv(dtrain=dmatrix, params=params, nfold=10, metrics={'rmse'}, as_pandas=True, seed=20)print('RMSE: %.2f' % cv_results['test-rmse-mean'].min())## Result : RMSE: 3.38"
},
{
"code": null,
"e": 6766,
"s": 6629,
"text": "Without any tuning, we’ve got a RMSE of 3.38. Which isn’t bad, but let’s see how it would perform with just a few tuned hyperparameters:"
},
{
"code": null,
"e": 7378,
"s": 6766,
"text": "import xgboost as xgbfrom sklearn.datasets import load_bostonfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error boston = load_boston()X, y = boston.data, boston.targetdmatrix = xgb.DMatrix(data=x, label=y)params={ 'objective':'reg:squarederror', 'max_depth': 6, 'colsample_bylevel':0.5, 'learning_rate':0.01, 'random_state':20}cv_results = xgb.cv(dtrain=dmatrix, params=params, nfold=10, metrics={'rmse'}, as_pandas=True, seed=20, num_boost_round=1000)print('RMSE: %.2f' % cv_results['test-rmse-mean'].min())## Result : RMSE: 2.69"
},
{
"code": null,
"e": 7522,
"s": 7378,
"text": "With just a little bit of tuning, we’ve now got a RMSE of 2.69. It’s a 20% improvement! And we could probably improve even more. Let’s see how!"
},
{
"code": null,
"e": 7690,
"s": 7522,
"text": "A hyperparameter is a type of parameter, external to the model, set before the learning process begins. It’s tunable and can directly affect how well a model performs."
},
{
"code": null,
"e": 7826,
"s": 7690,
"text": "To find out the best hyperparameters for your model, you may use rules of thumb, or specific methods that we’ll review in this article."
},
{
"code": null,
"e": 8000,
"s": 7826,
"text": "Before that, note that there are several parameters you can tune when working with XGBoost. You can find the complete list here, or the aliases used in the Scikit-Learn API."
},
{
"code": null,
"e": 8056,
"s": 8000,
"text": "For Tree base learners, the most common parameters are:"
},
{
"code": null,
"e": 8247,
"s": 8056,
"text": "max_depth: The maximum depth per tree. A deeper tree might increase the performance, but also the complexity and chances to overfit.The value must be an integer greater than 0. Default is 6."
},
{
"code": null,
"e": 8635,
"s": 8247,
"text": "learning_rate: The learning rate determines the step size at each iteration while your model optimizes toward its objective. A low learning rate makes computation slower, and requires more rounds to achieve the same reduction in residual error as a model with a high learning rate. But it optimizes the chances to reach the best optimum.The value must be between 0 and 1. Default is 0.3."
},
{
"code": null,
"e": 8856,
"s": 8635,
"text": "n_estimators: The number of trees in our ensemble. Equivalent to the number of boosting rounds.The value must be an integer greater than 0. Default is 100.NB: In the standard library, this is referred as num_boost_round."
},
{
"code": null,
"e": 9025,
"s": 8856,
"text": "colsample_bytree: Represents the fraction of columns to be randomly sampled for each tree. It might improve overfitting.The value must be between 0 and 1. Default is 1."
},
{
"code": null,
"e": 9221,
"s": 9025,
"text": "subsample: Represents the fraction of observations to be sampled for each tree. A lower values prevent overfitting but might lead to under-fitting.The value must be between 0 and 1. Default is 1."
},
{
"code": null,
"e": 9248,
"s": 9221,
"text": "Regularization parameters:"
},
{
"code": null,
"e": 9440,
"s": 9248,
"text": "alpha (reg_alpha): L1 regularization on the weights (Lasso Regression). When working with a large number of features, it might improve speed performances. It can be any integer. Default is 0."
},
{
"code": null,
"e": 9588,
"s": 9440,
"text": "lambda (reg_lambda): L2 regularization on the weights (Ridge Regression). It might help to reduce overfitting. It can be any integer. Default is 1."
},
{
"code": null,
"e": 9789,
"s": 9588,
"text": "gamma: Gamma is a pseudo-regularisation parameter (Lagrangian multiplier), and depends on the other parameters. The higher Gamma is, the higher the regularization. It can be any integer. Default is 0."
},
{
"code": null,
"e": 9982,
"s": 9789,
"text": "A first approach would be to start with reasonable parameters and to play along. If you understood the meanings of each hyperparameter above, you should be able to intuitively set some values."
},
{
"code": null,
"e": 10039,
"s": 9982,
"text": "Let’s start with reasonable values. It would usually be:"
},
{
"code": null,
"e": 10184,
"s": 10039,
"text": "max_depth: 3–10n_estimators: 100 (lots of observations) to 1000 (few observations)learning_rate: 0.01–0.3colsample_bytree: 0.5–1subsample: 0.6–1"
},
{
"code": null,
"e": 10246,
"s": 10184,
"text": "Then, you can focus on optimizing max_depth and n_estimators."
},
{
"code": null,
"e": 10501,
"s": 10246,
"text": "You can then play along with the learning_rate, and increase it to speed up the model without decreasing the performances. If it becomes faster without losing in performances, you can increase the number of estimators to try to increase the performances."
},
{
"code": null,
"e": 10719,
"s": 10501,
"text": "Finally, you can work with your regularization parameters, usually starting with alpha and lambda. For gamma, 0 would mean no regularization, 1–5 are commonly used values, whereas 10+ would be considered as very high."
},
{
"code": null,
"e": 10935,
"s": 10719,
"text": "A second approach to find the best hyperparameters is through Optimization Algorithm. Since XGBoost is available in a Scikit-learn compatible way, you can work with Scikit-learn’s hyperparameter optimizer functions!"
},
{
"code": null,
"e": 10990,
"s": 10935,
"text": "The two most common are Grid Search and Random Search."
},
{
"code": null,
"e": 11208,
"s": 10990,
"text": "A Grid Search is an exhaustive search over every combination of specified parameter values. If you specify 2 possible values for max_depth and 3 for n_estimators, Grid Search will iterate over 6 possible combinations:"
},
{
"code": null,
"e": 11254,
"s": 11208,
"text": "max_depth: [3,6],n_estimators:[100, 200, 300]"
},
{
"code": null,
"e": 11485,
"s": 11254,
"text": "Would result in the following possibilities:max_depth: 3, n_estimators: 100max_depth: 3, n_estimators: 200max_depth: 3, n_estimators: 300max_depth: 6, n_estimators: 100max_depth: 6, n_estimators: 200max_depth: 6, n_estimators: 300"
},
{
"code": null,
"e": 11555,
"s": 11485,
"text": "Let’s use GridSearchCV() from Scikit-learn to tune our XGBoost model!"
},
{
"code": null,
"e": 11664,
"s": 11555,
"text": "In the following examples, we’ll use a processed version of the Life Expectancy dataset available on Kaggle."
},
{
"code": null,
"e": 12338,
"s": 11664,
"text": "import pandas as pdimport xgboost as xgbfrom sklearn.model_selection import GridSearchCVdata = pd.read_csv(\"life_expectancy_clean.csv\")X, y = data[data.columns.tolist()[:-1]], data[data.columns.tolist()[-1]]params = { 'max_depth': [3,6,10], 'learning_rate': [0.01, 0.05, 0.1], 'n_estimators': [100, 500, 1000], 'colsample_bytree': [0.3, 0.7]}xgbr = xgb.XGBRegressor(seed = 20)clf = GridSearchCV(estimator=xgbr, param_grid=params, scoring='neg_mean_squared_error', verbose=1)clf.fit(X, y)print(\"Best parameters:\", clf.best_params_)print(\"Lowest RMSE: \", (-clf.best_score_)**(1/2.0))"
},
{
"code": null,
"e": 12512,
"s": 12338,
"text": "estimator: GridSearchCV is part of sklearn.model_selection, and works with any scikit-learn compatible estimator. We use xgb.XGBRegressor(), from XGBoost’s Scikit-learn API."
},
{
"code": null,
"e": 12641,
"s": 12512,
"text": "param_grid: GridSearchCV takes a list of parameters to test in input. As we said, a Grid Search will test out every combination."
},
{
"code": null,
"e": 13020,
"s": 12641,
"text": "scoring: It’s the metric(s) that will be used to evaluate the performance of the cross-validated model. In this case, neg_mean_squared_error is used in replacement for mean_squared_error. GridSearchCV is simply using a negative version of MSE for technical reasons — so it makes the function generalizable to other metrics where we aim for the higher score instead of the lower."
},
{
"code": null,
"e": 13084,
"s": 13020,
"text": "verbose: Controls the verbosity. The higher, the more messages."
},
{
"code": null,
"e": 13156,
"s": 13084,
"text": "More parameters as available, as you can find out in the documentation."
},
{
"code": null,
"e": 13273,
"s": 13156,
"text": "Finally, the lowest RMSE based on the negative value of clf.best_score_And the best parameters with clf.best_params_"
},
{
"code": null,
"e": 13376,
"s": 13273,
"text": "Best parameters: {'colsample_bytree': 0.7, 'learning_rate': 0.05, 'max_depth': 6, 'n_estimators': 500}"
},
{
"code": null,
"e": 13676,
"s": 13376,
"text": "A Random Search uses a large (possibly infinite) range of hyperparameters values, and randomly iterates a specified number of times over combinations of those values. Contrary to a Grid Search which iterates over every possible combination, with a Random Search you specify the number of iterations."
},
{
"code": null,
"e": 13793,
"s": 13676,
"text": "If you input 10 possible values for max_depth, 200 possible values for n_estimators, and choose to do 10 iterations:"
},
{
"code": null,
"e": 13859,
"s": 13793,
"text": "max_depth: np.arrange(1,10,1),n_estimators: np.arrange(100,400,2)"
},
{
"code": null,
"e": 14252,
"s": 13859,
"text": "Example of random possibilities with 10 iterations:1: max_depth: 1, n_estimators: 1102: max_depth: 3, n_estimators: 2223: max_depth: 3, n_estimators: 3064: max_depth: 4, n_estimators: 1025: max_depth: 1, n_estimators: 3986: max_depth: 6, n_estimators: 2907: max_depth: 9, n_estimators: 1028: max_depth: 6, n_estimators: 3109: max_depth: 3, n_estimators: 34410: max_depth: 6, n_estimators: 202"
},
{
"code": null,
"e": 14321,
"s": 14252,
"text": "Now, let’s use RandomSearchCV() from Scikit-learn to tune our model!"
},
{
"code": null,
"e": 15222,
"s": 14321,
"text": "import pandas as pdimport numpy as npimport xgboost as xgbfrom sklearn.model_selection import RandomizedSearchCVdata = pd.read_csv(\"life_expectancy_clean.csv\")X, y = data[data.columns.tolist()[:-1]], data[data.columns.tolist()[-1]]params = { 'max_depth': [3, 5, 6, 10, 15, 20], 'learning_rate': [0.01, 0.1, 0.2, 0.3], 'subsample': np.arange(0.5, 1.0, 0.1), 'colsample_bytree': np.arange(0.4, 1.0, 0.1), 'colsample_bylevel': np.arange(0.4, 1.0, 0.1), 'n_estimators': [100, 500, 1000]}xgbr = xgb.XGBRegressor(seed = 20)clf = RandomizedSearchCV(estimator=xgbr, param_distributions=params, scoring='neg_mean_squared_error', n_iter=25, verbose=1)clf.fit(X, y)print(\"Best parameters:\", clf.best_params_)print(\"Lowest RMSE: \", (-clf.best_score_)**(1/2.0))"
},
{
"code": null,
"e": 15290,
"s": 15222,
"text": "Most RandomizedSearchCV’s parameters are similar to GridSearchCV’s."
},
{
"code": null,
"e": 15461,
"s": 15290,
"text": "n_iter: It’s the number of parameter combinations that are sampled.The higher, the more combinations you’ll be testing. It trades off runtime and quality of the solution."
},
{
"code": null,
"e": 15599,
"s": 15461,
"text": "As for GridSearchCV, we print the best parameters with clf.best_params_And the lowest RMSE based on the negative value of clf.best_score_"
},
{
"code": null,
"e": 15786,
"s": 15599,
"text": "In this article, we explained how XGBoost operates to better understand how to tune its hyperparameters. As we’ve seen, tuning usually results in a big improvement in model performances."
}
] |
Solidity - Conversions | Solidity allows implicit as well as explicit conversion. Solidity compiler allows implicit conversion between two data types provided no implicit conversion is possible and there is no loss of information. For example uint8 is convertible to uint16 but int8 is convertible to uint256 as int8 can contain negative value not allowed in uint256.
We can explicitly convert a data type to another using constructor syntax.
int8 y = -3;
uint x = uint(y);
//Now x = 0xfffff..fd == two complement representation of -3 in 256 bit format.
Conversion to smaller type costs higher order bits.
uint32 a = 0x12345678;
uint16 b = uint16(a); // b = 0x5678
Conversion to higher type adds padding bits to the left.
uint16 a = 0x1234;
uint32 b = uint32(a); // b = 0x00001234
Conversion to smaller byte costs higher order data.
bytes2 a = 0x1234;
bytes1 b = bytes1(a); // b = 0x12
Conversion to larger byte add padding bits to the right.
bytes2 a = 0x1234;
bytes4 b = bytes4(a); // b = 0x12340000
Conversion between fixed size bytes and int is only possible when both are of same size.
bytes2 a = 0x1234;
uint32 b = uint16(a); // b = 0x00001234
uint32 c = uint32(bytes4(a)); // c = 0x12340000
uint8 d = uint8(uint16(a)); // d = 0x34
uint8 e = uint8(bytes1(a)); // e = 0x12
Hexadecimal numbers can be assigned to any integer type if no truncation is needed.
uint8 a = 12; // no error
uint32 b = 1234; // no error
uint16 c = 0x123456; // error, as truncation required to 0x3456
38 Lectures
4.5 hours
Abhilash Nelson
62 Lectures
8.5 hours
Frahaan Hussain
31 Lectures
3.5 hours
Swapnil Kole
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2898,
"s": 2555,
"text": "Solidity allows implicit as well as explicit conversion. Solidity compiler allows implicit conversion between two data types provided no implicit conversion is possible and there is no loss of information. For example uint8 is convertible to uint16 but int8 is convertible to uint256 as int8 can contain negative value not allowed in uint256."
},
{
"code": null,
"e": 2973,
"s": 2898,
"text": "We can explicitly convert a data type to another using constructor syntax."
},
{
"code": null,
"e": 3084,
"s": 2973,
"text": "int8 y = -3;\nuint x = uint(y);\n//Now x = 0xfffff..fd == two complement representation of -3 in 256 bit format."
},
{
"code": null,
"e": 3136,
"s": 3084,
"text": "Conversion to smaller type costs higher order bits."
},
{
"code": null,
"e": 3195,
"s": 3136,
"text": "uint32 a = 0x12345678;\nuint16 b = uint16(a); // b = 0x5678"
},
{
"code": null,
"e": 3252,
"s": 3195,
"text": "Conversion to higher type adds padding bits to the left."
},
{
"code": null,
"e": 3312,
"s": 3252,
"text": "uint16 a = 0x1234;\nuint32 b = uint32(a); // b = 0x00001234 "
},
{
"code": null,
"e": 3364,
"s": 3312,
"text": "Conversion to smaller byte costs higher order data."
},
{
"code": null,
"e": 3417,
"s": 3364,
"text": "bytes2 a = 0x1234;\nbytes1 b = bytes1(a); // b = 0x12"
},
{
"code": null,
"e": 3474,
"s": 3417,
"text": "Conversion to larger byte add padding bits to the right."
},
{
"code": null,
"e": 3533,
"s": 3474,
"text": "bytes2 a = 0x1234;\nbytes4 b = bytes4(a); // b = 0x12340000"
},
{
"code": null,
"e": 3622,
"s": 3533,
"text": "Conversion between fixed size bytes and int is only possible when both are of same size."
},
{
"code": null,
"e": 3809,
"s": 3622,
"text": "bytes2 a = 0x1234;\nuint32 b = uint16(a); // b = 0x00001234\nuint32 c = uint32(bytes4(a)); // c = 0x12340000\nuint8 d = uint8(uint16(a)); // d = 0x34\nuint8 e = uint8(bytes1(a)); // e = 0x12"
},
{
"code": null,
"e": 3893,
"s": 3809,
"text": "Hexadecimal numbers can be assigned to any integer type if no truncation is needed."
},
{
"code": null,
"e": 4012,
"s": 3893,
"text": "uint8 a = 12; // no error\nuint32 b = 1234; // no error\nuint16 c = 0x123456; // error, as truncation required to 0x3456"
},
{
"code": null,
"e": 4047,
"s": 4012,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4064,
"s": 4047,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4099,
"s": 4064,
"text": "\n 62 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4116,
"s": 4099,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4151,
"s": 4116,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4165,
"s": 4151,
"text": " Swapnil Kole"
},
{
"code": null,
"e": 4172,
"s": 4165,
"text": " Print"
},
{
"code": null,
"e": 4183,
"s": 4172,
"text": " Add Notes"
}
] |
PyGTK - DrawingArea Class | The DrawingArea widget presents a blank canvas containing a gtk.gdk.Window on which objects such as line, rectangle, arc, etc. can be drawn.
PyGTK uses Cairo library for such drawing operations. Cairo is a popular 2D vector graphics library. It is written in C., although, it has bindings in most Languages such as C++, Java, Python, PHP etc. Cairo library can be used to draw on standard output devices in various operating systems. It can also be used to create PDF, SVG and post-script files.
In order to perform different drawing operations, we must fetch the device on text of the target output object. In this case, since the drawing is appearing on gtk.DrawingArea widget, the device context of gdk.Window contained inside it is obtained. This class has a cairo-create() method which returns the device context.
area = gtk.DrawingArea()
dc = area.window.cairo_create()
The DrawingArea widget can be connected to the callbacks based on the following signals emitted by it −
The Mouse and Keyboard events can also be used to invoke callbacks by add_events() method of the gtk.Widget class.
Of particular interest is the expose-event signal which is emitted when the DrawingArea canvas first comes up. The different methods for drawing 2D objects, that are defined in the Cairo library are called from this callback connected to the expose-event signal. These methods draw corresponding objects on the Cairo device context.
The following are the available drawing methods −
dc.rectangle(x,y,w,h) − This draws a rectangle at the specified top left coordinate and having givwn width and height.
dc.rectangle(x,y,w,h) − This draws a rectangle at the specified top left coordinate and having givwn width and height.
dc.arc(x,y,r,a1,a2) − This draws a circular arc with given radius and two angles.
dc.arc(x,y,r,a1,a2) − This draws a circular arc with given radius and two angles.
dc.line(x1, y1, x2, y2) − This draws a line between two pairs of coordinates.
dc.line(x1, y1, x2, y2) − This draws a line between two pairs of coordinates.
dc.line_to(x,y) − This draws a line from the current position to (x,y)
dc.line_to(x,y) − This draws a line from the current position to (x,y)
dc.show_text(str) − draws string at current cursor position
dc.show_text(str) − draws string at current cursor position
dc.stroke() − draws outline
dc.stroke() − draws outline
dc.fill() − fills shape with current color
dc.fill() − fills shape with current color
dc.set_color_rgb(r,g,b) − sets color to outline and fill with r, g and b values between 0.0 to 1.0
dc.set_color_rgb(r,g,b) − sets color to outline and fill with r, g and b values between 0.0 to 1.0
The following script draws different shapes and test using Cairo methods.
import gtk
import math
class PyApp(gtk.Window):
def __init__(self):
super(PyApp, self).__init__()
self.set_title("Basic shapes using Cairo")
self.set_size_request(400, 250)
self.set_position(gtk.WIN_POS_CENTER)
self.connect("destroy", gtk.main_quit)
darea = gtk.DrawingArea()
darea.connect("expose-event", self.expose)
self.add(darea)
self.show_all()
def expose(self, widget, event):
cr = widget.window.cairo_create()
cr.set_line_width(2)
cr.set_source_rgb(0,0,1)
cr.rectangle(10,10,100,100)
cr.stroke()
cr.set_source_rgb(1,0,0)
cr.rectangle(10,125,100,100)
cr.stroke()
cr.set_source_rgb(0,1,0)
cr.rectangle(125,10,100,100)
cr.fill()
cr.set_source_rgb(0.5,0.6,0.7)
cr.rectangle(125,125,100,100)
cr.fill()
cr.arc(300, 50, 50,0, 2*math.pi)
cr.set_source_rgb(0.2,0.2,0.2)
cr.fill()
cr.arc(300, 200, 50, math.pi,0)
cr.set_source_rgb(0.1,0.1,0.1)
cr.stroke()
cr.move_to(50,240)
cr.show_text("Hello PyGTK")
cr.move_to(150,240)
cr.line_to(400,240)
cr.stroke()
PyApp()
gtk.main()
The above script will generate the following output −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2875,
"s": 2734,
"text": "The DrawingArea widget presents a blank canvas containing a gtk.gdk.Window on which objects such as line, rectangle, arc, etc. can be drawn."
},
{
"code": null,
"e": 3230,
"s": 2875,
"text": "PyGTK uses Cairo library for such drawing operations. Cairo is a popular 2D vector graphics library. It is written in C., although, it has bindings in most Languages such as C++, Java, Python, PHP etc. Cairo library can be used to draw on standard output devices in various operating systems. It can also be used to create PDF, SVG and post-script files."
},
{
"code": null,
"e": 3553,
"s": 3230,
"text": "In order to perform different drawing operations, we must fetch the device on text of the target output object. In this case, since the drawing is appearing on gtk.DrawingArea widget, the device context of gdk.Window contained inside it is obtained. This class has a cairo-create() method which returns the device context."
},
{
"code": null,
"e": 3611,
"s": 3553,
"text": "area = gtk.DrawingArea()\ndc = area.window.cairo_create()\n"
},
{
"code": null,
"e": 3715,
"s": 3611,
"text": "The DrawingArea widget can be connected to the callbacks based on the following signals emitted by it −"
},
{
"code": null,
"e": 3830,
"s": 3715,
"text": "The Mouse and Keyboard events can also be used to invoke callbacks by add_events() method of the gtk.Widget class."
},
{
"code": null,
"e": 4163,
"s": 3830,
"text": "Of particular interest is the expose-event signal which is emitted when the DrawingArea canvas first comes up. The different methods for drawing 2D objects, that are defined in the Cairo library are called from this callback connected to the expose-event signal. These methods draw corresponding objects on the Cairo device context."
},
{
"code": null,
"e": 4213,
"s": 4163,
"text": "The following are the available drawing methods −"
},
{
"code": null,
"e": 4332,
"s": 4213,
"text": "dc.rectangle(x,y,w,h) − This draws a rectangle at the specified top left coordinate and having givwn width and height."
},
{
"code": null,
"e": 4451,
"s": 4332,
"text": "dc.rectangle(x,y,w,h) − This draws a rectangle at the specified top left coordinate and having givwn width and height."
},
{
"code": null,
"e": 4533,
"s": 4451,
"text": "dc.arc(x,y,r,a1,a2) − This draws a circular arc with given radius and two angles."
},
{
"code": null,
"e": 4615,
"s": 4533,
"text": "dc.arc(x,y,r,a1,a2) − This draws a circular arc with given radius and two angles."
},
{
"code": null,
"e": 4693,
"s": 4615,
"text": "dc.line(x1, y1, x2, y2) − This draws a line between two pairs of coordinates."
},
{
"code": null,
"e": 4771,
"s": 4693,
"text": "dc.line(x1, y1, x2, y2) − This draws a line between two pairs of coordinates."
},
{
"code": null,
"e": 4842,
"s": 4771,
"text": "dc.line_to(x,y) − This draws a line from the current position to (x,y)"
},
{
"code": null,
"e": 4913,
"s": 4842,
"text": "dc.line_to(x,y) − This draws a line from the current position to (x,y)"
},
{
"code": null,
"e": 4973,
"s": 4913,
"text": "dc.show_text(str) − draws string at current cursor position"
},
{
"code": null,
"e": 5033,
"s": 4973,
"text": "dc.show_text(str) − draws string at current cursor position"
},
{
"code": null,
"e": 5061,
"s": 5033,
"text": "dc.stroke() − draws outline"
},
{
"code": null,
"e": 5089,
"s": 5061,
"text": "dc.stroke() − draws outline"
},
{
"code": null,
"e": 5132,
"s": 5089,
"text": "dc.fill() − fills shape with current color"
},
{
"code": null,
"e": 5175,
"s": 5132,
"text": "dc.fill() − fills shape with current color"
},
{
"code": null,
"e": 5274,
"s": 5175,
"text": "dc.set_color_rgb(r,g,b) − sets color to outline and fill with r, g and b values between 0.0 to 1.0"
},
{
"code": null,
"e": 5373,
"s": 5274,
"text": "dc.set_color_rgb(r,g,b) − sets color to outline and fill with r, g and b values between 0.0 to 1.0"
},
{
"code": null,
"e": 5447,
"s": 5373,
"text": "The following script draws different shapes and test using Cairo methods."
},
{
"code": null,
"e": 6677,
"s": 5447,
"text": "import gtk\nimport math\n\nclass PyApp(gtk.Window):\n \n def __init__(self):\n super(PyApp, self).__init__()\n \n\t self.set_title(\"Basic shapes using Cairo\")\n self.set_size_request(400, 250)\n self.set_position(gtk.WIN_POS_CENTER)\n \n\t self.connect(\"destroy\", gtk.main_quit)\n\t\t\n darea = gtk.DrawingArea()\n darea.connect(\"expose-event\", self.expose)\n\t\t\n self.add(darea)\n self.show_all()\n\t\t\n def expose(self, widget, event):\n cr = widget.window.cairo_create()\n\t\t\n cr.set_line_width(2)\n cr.set_source_rgb(0,0,1)\n cr.rectangle(10,10,100,100)\n cr.stroke()\n\t\t\n cr.set_source_rgb(1,0,0)\n cr.rectangle(10,125,100,100)\n cr.stroke()\n\t\t\n cr.set_source_rgb(0,1,0)\n cr.rectangle(125,10,100,100)\n cr.fill()\n\t\t\n cr.set_source_rgb(0.5,0.6,0.7)\n cr.rectangle(125,125,100,100)\n cr.fill()\n\t\t\n cr.arc(300, 50, 50,0, 2*math.pi)\n cr.set_source_rgb(0.2,0.2,0.2)\n cr.fill()\n\t\t\n cr.arc(300, 200, 50, math.pi,0)\n cr.set_source_rgb(0.1,0.1,0.1)\n cr.stroke()\n\t\t\n cr.move_to(50,240)\n cr.show_text(\"Hello PyGTK\")\n cr.move_to(150,240)\n cr.line_to(400,240)\n cr.stroke()\n\nPyApp()\ngtk.main() "
},
{
"code": null,
"e": 6731,
"s": 6677,
"text": "The above script will generate the following output −"
},
{
"code": null,
"e": 6738,
"s": 6731,
"text": " Print"
},
{
"code": null,
"e": 6749,
"s": 6738,
"text": " Add Notes"
}
] |
Guava - Objects Class | Objects class provides helper functions applicable to all objects such as equals, hashCode, etc.
Following is the declaration for com.google.common.base.Objects class −
@GwtCompatible
public final class Objects
extends Object
static boolean equal(Object a, Object b)
Determines whether two possibly-null objects are equal.
static <T> T firstNonNull(T first, T second)
Deprecated. Use MoreObjects.firstNonNull(T, T) instead. This method is scheduled for removal in June 2016.
static int hashCode(Object... objects)
Generates a hash code for multiple values.
static Objects.ToStringHelper toStringHelper(Class<?> clazz)
Deprecated. Use MoreObjects.toStringHelper(Class) instead. This method is scheduled for removal in June 2016
static Objects.ToStringHelper toStringHelper(Object self)
Deprecated. Use MoreObjects.toStringHelper(Object) instead. This method is scheduled for removal in June 2016.
static Objects.ToStringHelper toStringHelper(String className)
Deprecated. Use MoreObjects.toStringHelper(String) instead. This method is scheduled for removal in June 2016.
This class inherits methods from the following class −
java.lang.Object
Create the following java program using any editor of your choice in say C:/> Guava.
import com.google.common.base.Objects;
public class GuavaTester {
public static void main(String args[]) {
Student s1 = new Student("Mahesh", "Parashar", 1, "VI");
Student s2 = new Student("Suresh", null, 3, null);
System.out.println(s1.equals(s2));
System.out.println(s1.hashCode());
System.out.println(
Objects.toStringHelper(s1)
.add("Name",s1.getFirstName()+" " + s1.getLastName())
.add("Class", s1.getClassName())
.add("Roll No", s1.getRollNo())
.toString());
}
}
class Student {
private String firstName;
private String lastName;
private int rollNo;
private String className;
public Student(String firstName, String lastName, int rollNo, String className) {
this.firstName = firstName;
this.lastName = lastName;
this.rollNo = rollNo;
this.className = className;
}
@Override
public boolean equals(Object object) {
if(!(object instanceof Student) || object == null) {
return false;
}
Student student = (Student)object;
// no need to handle null here
// Objects.equal("test", "test") == true
// Objects.equal("test", null) == false
// Objects.equal(null, "test") == false
// Objects.equal(null, null) == true
return Objects.equal(firstName, student.firstName) // first name can be null
&& Objects.equal(lastName, student.lastName) // last name can be null
&& Objects.equal(rollNo, student.rollNo)
&& Objects.equal(className, student.className); // class name can be null
}
@Override
public int hashCode() {
//no need to compute hashCode by self
return Objects.hashCode(className,rollNo);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
Compile the class using javac compiler as follows −
C:\Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:\Guava>java GuavaTester
See the result.
false
85871
Student{Name=Mahesh Parashar, Class=VI, Roll No=1}
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1982,
"s": 1885,
"text": "Objects class provides helper functions applicable to all objects such as equals, hashCode, etc."
},
{
"code": null,
"e": 2054,
"s": 1982,
"text": "Following is the declaration for com.google.common.base.Objects class −"
},
{
"code": null,
"e": 2114,
"s": 2054,
"text": "@GwtCompatible\npublic final class Objects\n extends Object"
},
{
"code": null,
"e": 2155,
"s": 2114,
"text": "static boolean\tequal(Object a, Object b)"
},
{
"code": null,
"e": 2211,
"s": 2155,
"text": "Determines whether two possibly-null objects are equal."
},
{
"code": null,
"e": 2256,
"s": 2211,
"text": "static <T> T\tfirstNonNull(T first, T second)"
},
{
"code": null,
"e": 2363,
"s": 2256,
"text": "Deprecated. Use MoreObjects.firstNonNull(T, T) instead. This method is scheduled for removal in June 2016."
},
{
"code": null,
"e": 2402,
"s": 2363,
"text": "static int hashCode(Object... objects)"
},
{
"code": null,
"e": 2445,
"s": 2402,
"text": "Generates a hash code for multiple values."
},
{
"code": null,
"e": 2506,
"s": 2445,
"text": "static Objects.ToStringHelper\ttoStringHelper(Class<?> clazz)"
},
{
"code": null,
"e": 2615,
"s": 2506,
"text": "Deprecated. Use MoreObjects.toStringHelper(Class) instead. This method is scheduled for removal in June 2016"
},
{
"code": null,
"e": 2673,
"s": 2615,
"text": "static Objects.ToStringHelper\ttoStringHelper(Object self)"
},
{
"code": null,
"e": 2784,
"s": 2673,
"text": "Deprecated. Use MoreObjects.toStringHelper(Object) instead. This method is scheduled for removal in June 2016."
},
{
"code": null,
"e": 2847,
"s": 2784,
"text": "static Objects.ToStringHelper\ttoStringHelper(String className)"
},
{
"code": null,
"e": 2958,
"s": 2847,
"text": "Deprecated. Use MoreObjects.toStringHelper(String) instead. This method is scheduled for removal in June 2016."
},
{
"code": null,
"e": 3013,
"s": 2958,
"text": "This class inherits methods from the following class −"
},
{
"code": null,
"e": 3030,
"s": 3013,
"text": "java.lang.Object"
},
{
"code": null,
"e": 3115,
"s": 3030,
"text": "Create the following java program using any editor of your choice in say C:/> Guava."
},
{
"code": null,
"e": 5480,
"s": 3115,
"text": "import com.google.common.base.Objects;\n\npublic class GuavaTester {\n public static void main(String args[]) {\n Student s1 = new Student(\"Mahesh\", \"Parashar\", 1, \"VI\");\t\n Student s2 = new Student(\"Suresh\", null, 3, null);\t\n\t \n System.out.println(s1.equals(s2));\n System.out.println(s1.hashCode());\t\n System.out.println(\n Objects.toStringHelper(s1)\n .add(\"Name\",s1.getFirstName()+\" \" + s1.getLastName())\n .add(\"Class\", s1.getClassName())\n .add(\"Roll No\", s1.getRollNo())\n .toString());\n }\n}\n\nclass Student {\n private String firstName;\n private String lastName;\n private int rollNo;\n private String className;\n\n public Student(String firstName, String lastName, int rollNo, String className) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.rollNo = rollNo;\n this.className = className;\t\t\n }\n\n @Override\n public boolean equals(Object object) {\n if(!(object instanceof Student) || object == null) {\n return false;\n }\n Student student = (Student)object;\n // no need to handle null here\t\t\n // Objects.equal(\"test\", \"test\") == true\n // Objects.equal(\"test\", null) == false\n // Objects.equal(null, \"test\") == false\n // Objects.equal(null, null) == true\t\t\n return Objects.equal(firstName, student.firstName) // first name can be null\n && Objects.equal(lastName, student.lastName) // last name can be null\n && Objects.equal(rollNo, student.rollNo)\t\n && Objects.equal(className, student.className); // class name can be null\n }\n\n @Override\n public int hashCode() {\n //no need to compute hashCode by self\n return Objects.hashCode(className,rollNo);\n }\n \n public String getFirstName() {\n return firstName;\n }\n \n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n \n public String getLastName() {\n return lastName;\n }\n \n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n \n public int getRollNo() {\n return rollNo;\n }\n \n public void setRollNo(int rollNo) {\n this.rollNo = rollNo;\n }\n \n public String getClassName() {\n return className;\n }\n \n public void setClassName(String className) {\n this.className = className;\n }\n}"
},
{
"code": null,
"e": 5532,
"s": 5480,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 5565,
"s": 5532,
"text": "C:\\Guava>javac GuavaTester.java\n"
},
{
"code": null,
"e": 5608,
"s": 5565,
"text": "Now run the GuavaTester to see the result."
},
{
"code": null,
"e": 5635,
"s": 5608,
"text": "C:\\Guava>java GuavaTester\n"
},
{
"code": null,
"e": 5651,
"s": 5635,
"text": "See the result."
},
{
"code": null,
"e": 5715,
"s": 5651,
"text": "false\n85871\nStudent{Name=Mahesh Parashar, Class=VI, Roll No=1}\n"
},
{
"code": null,
"e": 5722,
"s": 5715,
"text": " Print"
},
{
"code": null,
"e": 5733,
"s": 5722,
"text": " Add Notes"
}
] |
NLP Text Preprocessing and Cleaning Pipeline in Python | by Emily Elia | Towards Data Science | Through language we express the human experience. Language is how we communicate, express sentiment, listen, think and converse. Over the past decade, tremendous progress has been made in natural language processing(NLP) where computers can classify, generate, and respond to language like a human can. These models and algorithms have started to give computers the tools to understand the human experience. The most important reason that these areas have grown is because of the exponential increase in data that can be feature engineered and then fed into models.
The data scientists, PhDs, machine leaning engineers, and data engineers who have been on the front lines of the advancements in natural language processing spend most of their time cleaning and exploring datasets.
Models will produce state of the art results if they are fed state of the art data; models will produce garbage if they are fed garbage, therefore data cleaning is one of the most important parts of the entire machine learning process. It does not matter if you are training a state of the art transformer like BERT or old-school word2vec. The quality of data that you feed the model will determine the quality of the results that you get.
Feature engineering and data cleaning are not tedious and pointless tasks — they are important filtering mechanisms that work the same way the human brain does when it processes a language. When humans are young they learn how to separate noises from a language and then find meaning in that language through the most important words and phrases in that language. This process is similar to text preprocessing. Text preprocessing breaks down a corpus into smaller parts then extracts the most important information from those parts which a model will then derive meaning from.
#tldr show me the code!
The first step of any machine learning pipeline is to load the data! For good measure we will also take a peek at the data to make sure everything loaded correctly and collect a few basic stats like the number of words, the number of lines, and the number of characters. This will give us a good idea of what we are working with for the next steps in the pipeline. I am using the Reuters dataset that can be found here.
data_folder = Path("/Users/emilyelia/Downloads/reuters/reuters/reuters/training")file_to_open = data_folder / "104"f = open(file_to_open)print(f.read())num_lines =0num_words =0num_chars =0with open(file_to_open, 'r') as f: for line in f: words = line.split()num_lines += 1 num_words += len(words) num_chars += len(line)print ("numbers of words", num_words)print("number of lines", num_lines)print("number of chars", num_chars)
Tokenization is the next preprocessing step. It takes the text corpus and it splits it into “tokens” (words, sentences, etc.).
This process is not as simple as using some kind of separator. There are a lot of different situations where separators don’t work such as abbreviations with dots like “Dr.” or periods “.” at the end of sentences. A more complex model is needed to properly tokenize, but don’t worry because tokenization is a built-in feature in commonly used NLP libraries such as nltk.
from nltk.tokenize import sent_tokenize, word_tokenizef = open(file_to_open)#use built in tokenize to seperate each indiviual wordnltk_words = word_tokenize(f.read())print(f"Tokenized words: {nltk_words}")
Cleaning is the process of removing all unnecessary content from the corpus. The unnecessary content includes stop words and punctuation since they do not add any value or meaning to the overall corpus.
Punctuation removal is an important step since punctuation does not provide any additional value or insight into the overall corpus and the vectorization of the corpus. Removing punctuation is best done after the tokenization step because doing so before might cause some unforeseen results.
Stop words are the most common words in the language that you are using. There are between 50–100 stop words depending on the library that you are using and they are words that don’t add meaning like “the”, “an”, and “it”. Removing these words will not change the meaning of the corpus that you are working with and it will lead to better results because the remaining words will be the most important to determining the meaning of the corpus.
print(nltk_words)punctuation = list(string.punctuation)stopWords = set(stopwords.words('english'))filter = []for w in nltk_words: if w.lower()not in stopWords and w not in punctuation: filter.append(w)
Normalization is the process of returning to a standard form or state. In terms of text preprocessing, it means taking numbers, abbreviations, and special characters, and converting them to text. This process uses the same associations that our brains do when processing special characters, misspellings, and abbreviations by taking them and assigning them to the words that we say, read, or think in the language of our choice. I am using the library normalise that can be found here.
The most common features to normalize are dates, numbers, abbreviations, currency, percents, and misspellings. In normalise you have to list the abbreviations that you want to spell out and then call the normalise function to perform the rest of the normalizations.
from normalise import normaliseabbr = { "lb": "pounds", "USDA": "United States Department of Agriculture", "cts": "cents", "U.S.": "United States"}normalise(text, user_abbrevs=abbr)nt =normalise(filter, user_abbrevs=abbr)display( ' '.join(nt))
These normalizations ensure that the model will be able to understand all of the text that is has to process because the numbers, special characters, misspellings, and abbreviations will have the same representation as everything else in the corpus.
Check out the entire project here! | [
{
"code": null,
"e": 737,
"s": 171,
"text": "Through language we express the human experience. Language is how we communicate, express sentiment, listen, think and converse. Over the past decade, tremendous progress has been made in natural language processing(NLP) where computers can classify, generate, and respond to language like a human can. These models and algorithms have started to give computers the tools to understand the human experience. The most important reason that these areas have grown is because of the exponential increase in data that can be feature engineered and then fed into models."
},
{
"code": null,
"e": 952,
"s": 737,
"text": "The data scientists, PhDs, machine leaning engineers, and data engineers who have been on the front lines of the advancements in natural language processing spend most of their time cleaning and exploring datasets."
},
{
"code": null,
"e": 1392,
"s": 952,
"text": "Models will produce state of the art results if they are fed state of the art data; models will produce garbage if they are fed garbage, therefore data cleaning is one of the most important parts of the entire machine learning process. It does not matter if you are training a state of the art transformer like BERT or old-school word2vec. The quality of data that you feed the model will determine the quality of the results that you get."
},
{
"code": null,
"e": 1969,
"s": 1392,
"text": "Feature engineering and data cleaning are not tedious and pointless tasks — they are important filtering mechanisms that work the same way the human brain does when it processes a language. When humans are young they learn how to separate noises from a language and then find meaning in that language through the most important words and phrases in that language. This process is similar to text preprocessing. Text preprocessing breaks down a corpus into smaller parts then extracts the most important information from those parts which a model will then derive meaning from."
},
{
"code": null,
"e": 1993,
"s": 1969,
"text": "#tldr show me the code!"
},
{
"code": null,
"e": 2413,
"s": 1993,
"text": "The first step of any machine learning pipeline is to load the data! For good measure we will also take a peek at the data to make sure everything loaded correctly and collect a few basic stats like the number of words, the number of lines, and the number of characters. This will give us a good idea of what we are working with for the next steps in the pipeline. I am using the Reuters dataset that can be found here."
},
{
"code": null,
"e": 2864,
"s": 2413,
"text": "data_folder = Path(\"/Users/emilyelia/Downloads/reuters/reuters/reuters/training\")file_to_open = data_folder / \"104\"f = open(file_to_open)print(f.read())num_lines =0num_words =0num_chars =0with open(file_to_open, 'r') as f: for line in f: words = line.split()num_lines += 1 num_words += len(words) num_chars += len(line)print (\"numbers of words\", num_words)print(\"number of lines\", num_lines)print(\"number of chars\", num_chars)"
},
{
"code": null,
"e": 2991,
"s": 2864,
"text": "Tokenization is the next preprocessing step. It takes the text corpus and it splits it into “tokens” (words, sentences, etc.)."
},
{
"code": null,
"e": 3362,
"s": 2991,
"text": "This process is not as simple as using some kind of separator. There are a lot of different situations where separators don’t work such as abbreviations with dots like “Dr.” or periods “.” at the end of sentences. A more complex model is needed to properly tokenize, but don’t worry because tokenization is a built-in feature in commonly used NLP libraries such as nltk."
},
{
"code": null,
"e": 3568,
"s": 3362,
"text": "from nltk.tokenize import sent_tokenize, word_tokenizef = open(file_to_open)#use built in tokenize to seperate each indiviual wordnltk_words = word_tokenize(f.read())print(f\"Tokenized words: {nltk_words}\")"
},
{
"code": null,
"e": 3771,
"s": 3568,
"text": "Cleaning is the process of removing all unnecessary content from the corpus. The unnecessary content includes stop words and punctuation since they do not add any value or meaning to the overall corpus."
},
{
"code": null,
"e": 4063,
"s": 3771,
"text": "Punctuation removal is an important step since punctuation does not provide any additional value or insight into the overall corpus and the vectorization of the corpus. Removing punctuation is best done after the tokenization step because doing so before might cause some unforeseen results."
},
{
"code": null,
"e": 4507,
"s": 4063,
"text": "Stop words are the most common words in the language that you are using. There are between 50–100 stop words depending on the library that you are using and they are words that don’t add meaning like “the”, “an”, and “it”. Removing these words will not change the meaning of the corpus that you are working with and it will lead to better results because the remaining words will be the most important to determining the meaning of the corpus."
},
{
"code": null,
"e": 4719,
"s": 4507,
"text": "print(nltk_words)punctuation = list(string.punctuation)stopWords = set(stopwords.words('english'))filter = []for w in nltk_words: if w.lower()not in stopWords and w not in punctuation: filter.append(w)"
},
{
"code": null,
"e": 5205,
"s": 4719,
"text": "Normalization is the process of returning to a standard form or state. In terms of text preprocessing, it means taking numbers, abbreviations, and special characters, and converting them to text. This process uses the same associations that our brains do when processing special characters, misspellings, and abbreviations by taking them and assigning them to the words that we say, read, or think in the language of our choice. I am using the library normalise that can be found here."
},
{
"code": null,
"e": 5471,
"s": 5205,
"text": "The most common features to normalize are dates, numbers, abbreviations, currency, percents, and misspellings. In normalise you have to list the abbreviations that you want to spell out and then call the normalise function to perform the rest of the normalizations."
},
{
"code": null,
"e": 5727,
"s": 5471,
"text": "from normalise import normaliseabbr = { \"lb\": \"pounds\", \"USDA\": \"United States Department of Agriculture\", \"cts\": \"cents\", \"U.S.\": \"United States\"}normalise(text, user_abbrevs=abbr)nt =normalise(filter, user_abbrevs=abbr)display( ' '.join(nt))"
},
{
"code": null,
"e": 5977,
"s": 5727,
"text": "These normalizations ensure that the model will be able to understand all of the text that is has to process because the numbers, special characters, misspellings, and abbreviations will have the same representation as everything else in the corpus."
}
] |
Java Examples - Implementation of Stack | How to implement stack ?
Following example shows how to implement stack by creating user defined push() method for entering elements and pop() method for retrieving elements from the stack.
public class MyStack {
private int maxSize;
private long[] stackArray;
private int top;
public MyStack(int s) {
maxSize = s;
stackArray = new long[maxSize];
top = -1;
}
public void push(long j) {
stackArray[++top] = j;
}
public long pop() {
return stackArray[top--];
}
public long peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
public static void main(String[] args) {
MyStack theStack = new MyStack(10);
theStack.push(10);
theStack.push(20);
theStack.push(30);
theStack.push(40);
theStack.push(50);
while (!theStack.isEmpty()) {
long value = theStack.pop();
System.out.print(value);
System.out.print(" ");
}
System.out.println("");
}
}
The above code sample will produce the following result.
50 40 30 20 10
The following is an another sample to implement stack by creating user defined push() method for entering elements and pop() method for retrieving elements from the stack.
import java.util.*;
public class Demo {
static void showpush(Stack stack1, int a) {
stack1.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + stack1);
}
static void showpop(Stack stack1) {
Integer a = (Integer) stack1.pop();
System.out.println(a);
System.out.println("stack: " + stack1);
}
public static void main(String args[]) {
Stack stack1 = new Stack();
System.out.println("stack: " + stack1);
showpush(stack1, 40);
showpush(stack1, 50);
showpush(stack1, 60);
showpop(stack1);
showpop(stack1);
showpop(stack1);
try {
showpop(stack1);
} catch (EmptyStackException e) {
System.out.println("it Is Empty Stack");
}
}
}
The above code sample will produce the following result.
stack: []
push(40)
stack: [40]
push(50)
stack: [40, 50]
push(60)
stack: [40, 50, 60]
60
stack: [40, 50]
50
stack: [40]
40
stack: []
it Is Empty Stack
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2093,
"s": 2068,
"text": "How to implement stack ?"
},
{
"code": null,
"e": 2258,
"s": 2093,
"text": "Following example shows how to implement stack by creating user defined push() method for entering elements and pop() method for retrieving elements from the stack."
},
{
"code": null,
"e": 3181,
"s": 2258,
"text": "public class MyStack {\n private int maxSize;\n private long[] stackArray;\n private int top;\n \n public MyStack(int s) {\n maxSize = s;\n stackArray = new long[maxSize];\n top = -1;\n }\n public void push(long j) {\n stackArray[++top] = j;\n }\n public long pop() {\n return stackArray[top--];\n }\n public long peek() {\n return stackArray[top];\n }\n public boolean isEmpty() {\n return (top == -1);\n }\n public boolean isFull() {\n return (top == maxSize - 1);\n }\n public static void main(String[] args) {\n MyStack theStack = new MyStack(10); \n theStack.push(10);\n theStack.push(20);\n theStack.push(30);\n theStack.push(40);\n theStack.push(50);\n \n while (!theStack.isEmpty()) {\n long value = theStack.pop();\n System.out.print(value);\n System.out.print(\" \");\n }\n System.out.println(\"\");\n }\n}"
},
{
"code": null,
"e": 3238,
"s": 3181,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3254,
"s": 3238,
"text": "50 40 30 20 10\n"
},
{
"code": null,
"e": 3426,
"s": 3254,
"text": "The following is an another sample to implement stack by creating user defined push() method for entering elements and pop() method for retrieving elements from the stack."
},
{
"code": null,
"e": 4229,
"s": 3426,
"text": "import java.util.*;\n\npublic class Demo {\n static void showpush(Stack stack1, int a) {\n stack1.push(new Integer(a));\n System.out.println(\"push(\" + a + \")\");\n System.out.println(\"stack: \" + stack1);\n } \n static void showpop(Stack stack1) {\n Integer a = (Integer) stack1.pop();\n System.out.println(a);\n System.out.println(\"stack: \" + stack1);\n } \n public static void main(String args[]) {\n Stack stack1 = new Stack();\n System.out.println(\"stack: \" + stack1);\n showpush(stack1, 40);\n showpush(stack1, 50);\n showpush(stack1, 60);\n showpop(stack1);\n showpop(stack1);\n showpop(stack1);\n try {\n showpop(stack1);\n } catch (EmptyStackException e) {\n System.out.println(\"it Is Empty Stack\");\n } \n }\n}"
},
{
"code": null,
"e": 4286,
"s": 4229,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 4437,
"s": 4286,
"text": "stack: []\npush(40)\nstack: [40]\npush(50)\nstack: [40, 50]\npush(60)\nstack: [40, 50, 60]\n60\nstack: [40, 50]\n50\nstack: [40]\n40\nstack: []\nit Is Empty Stack\n"
},
{
"code": null,
"e": 4444,
"s": 4437,
"text": " Print"
},
{
"code": null,
"e": 4455,
"s": 4444,
"text": " Add Notes"
}
] |
Collecting Movie Data. Using a bunch of APIs to assemble a... | by Zachary Ang | Towards Data Science | I started out with the initial premise that I could try and predict the price of an iTunes movie given its characteristics. I knew that we could get information on movies in iTunes with a well documented public API, so let’s take a look.
There are two main ways you can get movie information from the iTunes store on the iTunes API — via a keyword call or a lookup by ID. Obviously, using keywords to extract specific movies is generally not a good idea. Some keywords give you as many as 50 matches (try searching for “Harry Potter”).
A lookup by ID is not much of an improvement either. The iTunes ID trackId string is at least 10 digits long, meaning that there could be as many as 10 billion possible IDs I would have to look up one at a time. Not a good idea.
So I used the iTunes RSS Feed to narrow down my search. The snippet below defines a function collect_rss_movies() that pings the iTunes RSS Feed. I decided to rely on the RSS iTunes feed to get more up-to-date movies with complete price information. After getting the iTunes IDs from the iTunes RSS feed, I turned to the iTunes API to get the movie information from the iTunes store using the get_info_by_id() function.
I’ve also defined a settings.py file which defines the collection parameters. Here, I’m directing the function to collect data from 9 countries and across 2 main genres.
I eventually dropped the documentary titles as they looked a little obscure relative to the mainstream movies, but here’s a snippet of what a movie record looks like:
{'artistName': 'Christopher McQuarrie', 'contentAdvisoryRating': 'PG-13', 'country': 'USA', 'currency': 'USD', 'primaryGenreName': 'Action & Adventure', 'releaseDate': '2018-07-27T07:00:00Z', 'shortDescription': 'On a dangerous assignment to recover stolen plutonium, Ethan Hunt (Tom Cruise) chooses to save his', 'trackHdPrice': 19.99, 'trackHdRentalPrice': 5.99, 'trackId': 1406515547, 'trackName': 'Mission: Impossible - Fallout', 'trackNumber': 6, 'trackPrice': 14.99, 'trackRentalPrice': 5.99, 'trackTimeMillis': 8873322, 'wrapperType': 'track'}
That’s the gist of it — there are some features that I haven’t included here, but the data description is available at the official iTunes API documentation, or you can check out the data description at my Github.
Great! We’re all set to do a new exciting machine learning project. Right? But there’s so much more to a movie than that, isn’t there? So I did a little more digging as to how I could supplement this data set.
While IMdb is the authoritative source on all movie information, they don’t have a public API and I was going to run into trouble searching for the exact movie that I should collect even if I had relied on web scraping. I turned to two open databases on movies, the Open Movie Database (OMdb) and The Movie database (TMdb).
The Movie Database (TMDb) is a community built movie and TV database. Every piece of data has been added by our amazing community dating back to 2008. TMDb’s strong international focus and breadth of data is largely unmatched and something we’re incredibly proud of.
So that’s the provenance of TMdb. From OMdb’s website:
The OMDb API is a RESTful web service to obtain movie information, all content and images on the site are contributed and maintained by our users.
Although they were respectively well maintained, they each had their pros and cons, and I realised that I’d probably have to utilise both to extract the right blend of information for my feature set. Both databases did not log the iTunes ID in their database for each movie so I was going to have to rely on a title search to match each movie from the iTunes data to the movies database.
Features. OMdb had a lot more useful information than that I couldn’t find in the TMdb dataset. For instance, OMdb contained information on the movie ratings, eg. Rotten Tomatoes ratings, Metacritic score and IMdb ratings. OMdb data also recorded box office performance of the movie, which I felt would be a key feature to predict how much an iTunes movie could list for.
API capabilities. In general, the TMdb API was more capable and offered more methods to look for information. In OMdb, you could only look up movies by a keyword search or by IMdb ID. Also, doing a keyword search on the TMdb API generally yielded better results than the OMdb API.
API rate limits. OMdb had a pretty tight API rate limit of 1,000 calls per day while the TMdb API had a much higher rate limit of 4 requests per second (or ~340,000 calls per day).
So the OMdb API had more information that I needed, but the TMdb API was generally better to work with. I eventually decided that I needed to make very targeted and specific calls to the OMdb API to get movie information through a lookup by ID. OMdb indexed their movie records using the IMdb ID, so I was going to have to find the IMdb ID for every movie that was in my iTunes dataset via keyword search, which as I had mentioned, was better done through the TMdb API.
Though somewhat convoluted, I settled on the following strategy:
Parse the movie title to a search string to pass through the TMdb API, looking for an exact match. Include year of production to narrow down the search further.
Parse the movie title to a search string to pass through the TMdb API, looking for an exact match. Include year of production to narrow down the search further.
2. For exact matches, look for the IMdb ID using a lookup by TMdb ID. For results with no matches, relax the search criteria by dropping the year of production. For movie titles with mutliple matches or results, extract the IMdb from the first result from a Google search in the form of “Movie title + Year of Production + IMdb”
3. Match each movie to an IMdb ID, and lookup OMdb API for movie information for each movie.
Following this procedure, I managed to uniquely identify a rather healthy looking dataset of 603 unique movies from the OMdb API , which matched ~1,500 out of the 1,800 movies I collected on the iTunes store so a decent return overall, without delving into the messy world of entity resolution. There’s a pretty lengthy chunk of code for this, but you can also follow it at my Github repo.
I was pretty happy with the data that I had until I did some initial exploration on the OMdb data. I noticed a large chunk of missing values for box office information in my data.
I could have lived with missing ratings scores, but box office performance would have been a good feature to incorporate into my model.
And it seemed plainly obvious that I could get the information rather easily through public data sources. So I turned to Box Office Mojo, using the ever reliable requests and BeautifulSoup combo.
I found ~7,000 movies, filling all of my missing values and supplementing it with the breakdown of world-wide box office gross versus US box office gross. Now it was just a matter of putting it all together.
After all that wrangling, I have a dataset of ~1,500 movies with data merged from 4 different sources, joined by different keys and methods. They exist primarily in two csv files found in my repository, and I’ve included a broad schema for the database below.
That wraps up my post about collecting data on movies. I’ll be posting updates on the modelling and data exploration here over the next week or so. In the meanwhile, ping me if you have any feedback, suggestions or improvements to my data collection process! | [
{
"code": null,
"e": 410,
"s": 172,
"text": "I started out with the initial premise that I could try and predict the price of an iTunes movie given its characteristics. I knew that we could get information on movies in iTunes with a well documented public API, so let’s take a look."
},
{
"code": null,
"e": 708,
"s": 410,
"text": "There are two main ways you can get movie information from the iTunes store on the iTunes API — via a keyword call or a lookup by ID. Obviously, using keywords to extract specific movies is generally not a good idea. Some keywords give you as many as 50 matches (try searching for “Harry Potter”)."
},
{
"code": null,
"e": 937,
"s": 708,
"text": "A lookup by ID is not much of an improvement either. The iTunes ID trackId string is at least 10 digits long, meaning that there could be as many as 10 billion possible IDs I would have to look up one at a time. Not a good idea."
},
{
"code": null,
"e": 1357,
"s": 937,
"text": "So I used the iTunes RSS Feed to narrow down my search. The snippet below defines a function collect_rss_movies() that pings the iTunes RSS Feed. I decided to rely on the RSS iTunes feed to get more up-to-date movies with complete price information. After getting the iTunes IDs from the iTunes RSS feed, I turned to the iTunes API to get the movie information from the iTunes store using the get_info_by_id() function."
},
{
"code": null,
"e": 1527,
"s": 1357,
"text": "I’ve also defined a settings.py file which defines the collection parameters. Here, I’m directing the function to collect data from 9 countries and across 2 main genres."
},
{
"code": null,
"e": 1694,
"s": 1527,
"text": "I eventually dropped the documentary titles as they looked a little obscure relative to the mainstream movies, but here’s a snippet of what a movie record looks like:"
},
{
"code": null,
"e": 2245,
"s": 1694,
"text": "{'artistName': 'Christopher McQuarrie', 'contentAdvisoryRating': 'PG-13', 'country': 'USA', 'currency': 'USD', 'primaryGenreName': 'Action & Adventure', 'releaseDate': '2018-07-27T07:00:00Z', 'shortDescription': 'On a dangerous assignment to recover stolen plutonium, Ethan Hunt (Tom Cruise) chooses to save his', 'trackHdPrice': 19.99, 'trackHdRentalPrice': 5.99, 'trackId': 1406515547, 'trackName': 'Mission: Impossible - Fallout', 'trackNumber': 6, 'trackPrice': 14.99, 'trackRentalPrice': 5.99, 'trackTimeMillis': 8873322, 'wrapperType': 'track'}"
},
{
"code": null,
"e": 2459,
"s": 2245,
"text": "That’s the gist of it — there are some features that I haven’t included here, but the data description is available at the official iTunes API documentation, or you can check out the data description at my Github."
},
{
"code": null,
"e": 2669,
"s": 2459,
"text": "Great! We’re all set to do a new exciting machine learning project. Right? But there’s so much more to a movie than that, isn’t there? So I did a little more digging as to how I could supplement this data set."
},
{
"code": null,
"e": 2993,
"s": 2669,
"text": "While IMdb is the authoritative source on all movie information, they don’t have a public API and I was going to run into trouble searching for the exact movie that I should collect even if I had relied on web scraping. I turned to two open databases on movies, the Open Movie Database (OMdb) and The Movie database (TMdb)."
},
{
"code": null,
"e": 3260,
"s": 2993,
"text": "The Movie Database (TMDb) is a community built movie and TV database. Every piece of data has been added by our amazing community dating back to 2008. TMDb’s strong international focus and breadth of data is largely unmatched and something we’re incredibly proud of."
},
{
"code": null,
"e": 3315,
"s": 3260,
"text": "So that’s the provenance of TMdb. From OMdb’s website:"
},
{
"code": null,
"e": 3462,
"s": 3315,
"text": "The OMDb API is a RESTful web service to obtain movie information, all content and images on the site are contributed and maintained by our users."
},
{
"code": null,
"e": 3850,
"s": 3462,
"text": "Although they were respectively well maintained, they each had their pros and cons, and I realised that I’d probably have to utilise both to extract the right blend of information for my feature set. Both databases did not log the iTunes ID in their database for each movie so I was going to have to rely on a title search to match each movie from the iTunes data to the movies database."
},
{
"code": null,
"e": 4222,
"s": 3850,
"text": "Features. OMdb had a lot more useful information than that I couldn’t find in the TMdb dataset. For instance, OMdb contained information on the movie ratings, eg. Rotten Tomatoes ratings, Metacritic score and IMdb ratings. OMdb data also recorded box office performance of the movie, which I felt would be a key feature to predict how much an iTunes movie could list for."
},
{
"code": null,
"e": 4503,
"s": 4222,
"text": "API capabilities. In general, the TMdb API was more capable and offered more methods to look for information. In OMdb, you could only look up movies by a keyword search or by IMdb ID. Also, doing a keyword search on the TMdb API generally yielded better results than the OMdb API."
},
{
"code": null,
"e": 4684,
"s": 4503,
"text": "API rate limits. OMdb had a pretty tight API rate limit of 1,000 calls per day while the TMdb API had a much higher rate limit of 4 requests per second (or ~340,000 calls per day)."
},
{
"code": null,
"e": 5154,
"s": 4684,
"text": "So the OMdb API had more information that I needed, but the TMdb API was generally better to work with. I eventually decided that I needed to make very targeted and specific calls to the OMdb API to get movie information through a lookup by ID. OMdb indexed their movie records using the IMdb ID, so I was going to have to find the IMdb ID for every movie that was in my iTunes dataset via keyword search, which as I had mentioned, was better done through the TMdb API."
},
{
"code": null,
"e": 5219,
"s": 5154,
"text": "Though somewhat convoluted, I settled on the following strategy:"
},
{
"code": null,
"e": 5380,
"s": 5219,
"text": "Parse the movie title to a search string to pass through the TMdb API, looking for an exact match. Include year of production to narrow down the search further."
},
{
"code": null,
"e": 5541,
"s": 5380,
"text": "Parse the movie title to a search string to pass through the TMdb API, looking for an exact match. Include year of production to narrow down the search further."
},
{
"code": null,
"e": 5870,
"s": 5541,
"text": "2. For exact matches, look for the IMdb ID using a lookup by TMdb ID. For results with no matches, relax the search criteria by dropping the year of production. For movie titles with mutliple matches or results, extract the IMdb from the first result from a Google search in the form of “Movie title + Year of Production + IMdb”"
},
{
"code": null,
"e": 5963,
"s": 5870,
"text": "3. Match each movie to an IMdb ID, and lookup OMdb API for movie information for each movie."
},
{
"code": null,
"e": 6353,
"s": 5963,
"text": "Following this procedure, I managed to uniquely identify a rather healthy looking dataset of 603 unique movies from the OMdb API , which matched ~1,500 out of the 1,800 movies I collected on the iTunes store so a decent return overall, without delving into the messy world of entity resolution. There’s a pretty lengthy chunk of code for this, but you can also follow it at my Github repo."
},
{
"code": null,
"e": 6533,
"s": 6353,
"text": "I was pretty happy with the data that I had until I did some initial exploration on the OMdb data. I noticed a large chunk of missing values for box office information in my data."
},
{
"code": null,
"e": 6669,
"s": 6533,
"text": "I could have lived with missing ratings scores, but box office performance would have been a good feature to incorporate into my model."
},
{
"code": null,
"e": 6865,
"s": 6669,
"text": "And it seemed plainly obvious that I could get the information rather easily through public data sources. So I turned to Box Office Mojo, using the ever reliable requests and BeautifulSoup combo."
},
{
"code": null,
"e": 7073,
"s": 6865,
"text": "I found ~7,000 movies, filling all of my missing values and supplementing it with the breakdown of world-wide box office gross versus US box office gross. Now it was just a matter of putting it all together."
},
{
"code": null,
"e": 7333,
"s": 7073,
"text": "After all that wrangling, I have a dataset of ~1,500 movies with data merged from 4 different sources, joined by different keys and methods. They exist primarily in two csv files found in my repository, and I’ve included a broad schema for the database below."
}
] |
Backing up Cisco IOS Router image - GeeksforGeeks | 03 Mar, 2022
As a network administrator, you should always have a backup for worse conditions. One of the common worse conditions that can occur is the IOS image of a device deleted. This condition gets worse if there is no backup of the IOS image present.
So to ignore conditions like these, a backup should be a must and here we will take a Cisco IOS image backup on the TFTP server.
Trivial File Transfer Protocol (TFTP) – TFTP is a simple file transfer protocol that is either used to put or get a file from a remote host. It uses UDP port number 69. But TFTP is used where no authentication and control are required. Also, it takes less overhead. While on the other hand, it is less interactive than FTP. Therefore, according to the need, FTP or TFTP is used.
Configuration –
Here is a simple topology in which there is a router (for which we will take IOS backup) and a TFTP server. The router has IP address 10.1.1.1/24 and the TFTP server has IP address 10.1.1.2/24.
Note – Before taking IOS backup, make sure the Tftp server and router are able to ping each other.
As shown in the figure, we see an IOS image file in flash (.bin file) by command:
router#show flash
Now, we will copy this file to our Tftp server by command:
router#copy flash: tftp:
Source filename[]? c1841-advipservicesk9-mz.124-15.T1.bin
Address or name of remote host []? 10.1.1.2
Destination filename [c1841-advipservicesk9-mz.124-15.T1.bin]? routerios
Now, as we can see in the above image it is asking for source filename, Address of remote host, and destination filename.
Source filename – It is the name of the IOS image file. here, it is named c1841-advipservicesk9-mz.124-15.T1.bin (shown in flash).
Address or name of remote host – It is the IP address of the TFTP server. In our scenario, it is 10.1.1.2.
Destination filename – It is the name of the destination file that will be put in the TFTP server. Here, we have named it routerIOS.
As shown in the above figure, the file has been copied to the TFTP server. Now, we will delete the IOS image from the router:
router(config)#delete flash:
Note – Now, as the file is deleted still the router is running because the IOS has already been loaded into RAM. Therefore, when we will reload the router, it will enter ROMMON mode.
Therefore, now to copy the IOS file from the TFTP server we will use the command:
rommon 1>tftpdnld
Now, as soon as we type this command, we see the parameters which we have to enter next.
ROMMON 2>IP_ADDRESS=10.1.1.1
ROMMON 3>IP_SUBNET_MASK=255.255.255.0
ROMMON 4>DEFAULT_GATEWAY=10.1.1.2
ROMMON 5>TFTP_SERVER=10.1.1.2
ROMMON 6>TFTP_FILE=routerios
IP_ADDRESS – It is the IP address we want to give to our router’s interface fa0/0 but remember this IP address should be of the same subnet. Here, we have provided 10.1.1.1 on the router’s interface.
IP_SUBNET_MASK – This is the subnet mask that we want to give to the router’s interface IP address which is 255.255.255.0 in our scenario.
DEFAULT_GATEWAY – Here, we have to give the default gateway for that router’s interface IP address. Here, notice that our TFTP server is directly connected to the router’s interface, therefore, we can give the TFTP server’s IP address which has been given as 10.1.1.2 but if there is any router in between TFTP server and router then we have to give the default gateway IP address of the router.
TFTP_server – This command requires the IP address of the TFTP server which is 10.1.1.2 in our scenario.
TFTP_FILE – It is the name of the file which we have saved on the TFTP server. In our scenario, we have given the name routerios.bin.
After we have entered these commands, we will again enter the command tftpdnld.
After that, it will ask us to continue to say yes (as shown in the figure) if we have entered the right parameters otherwise enter no and again specify the correct parameters.
ROMMON 7>reset
After that just enter command reset to reload the router.
Pushpender007
marcosarcticseal
Computer Networks
Misc
Misc
Misc
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Introduction and IPv4 Datagram Header
Secure Socket Layer (SSL)
Cryptography and its Types
Top 10 algorithms in Interview Questions
vector::push_back() and vector::pop_back() in C++ STL
Overview of Data Structures | Set 1 (Linear Data Structures)
How to write Regular Expressions?
Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move) | [
{
"code": null,
"e": 25755,
"s": 25727,
"text": "\n03 Mar, 2022"
},
{
"code": null,
"e": 26000,
"s": 25755,
"text": "As a network administrator, you should always have a backup for worse conditions. One of the common worse conditions that can occur is the IOS image of a device deleted. This condition gets worse if there is no backup of the IOS image present. "
},
{
"code": null,
"e": 26130,
"s": 26000,
"text": "So to ignore conditions like these, a backup should be a must and here we will take a Cisco IOS image backup on the TFTP server. "
},
{
"code": null,
"e": 26510,
"s": 26130,
"text": "Trivial File Transfer Protocol (TFTP) – TFTP is a simple file transfer protocol that is either used to put or get a file from a remote host. It uses UDP port number 69. But TFTP is used where no authentication and control are required. Also, it takes less overhead. While on the other hand, it is less interactive than FTP. Therefore, according to the need, FTP or TFTP is used. "
},
{
"code": null,
"e": 26527,
"s": 26510,
"text": "Configuration – "
},
{
"code": null,
"e": 26724,
"s": 26529,
"text": "Here is a simple topology in which there is a router (for which we will take IOS backup) and a TFTP server. The router has IP address 10.1.1.1/24 and the TFTP server has IP address 10.1.1.2/24. "
},
{
"code": null,
"e": 26824,
"s": 26724,
"text": "Note – Before taking IOS backup, make sure the Tftp server and router are able to ping each other. "
},
{
"code": null,
"e": 26910,
"s": 26826,
"text": "As shown in the figure, we see an IOS image file in flash (.bin file) by command: "
},
{
"code": null,
"e": 26928,
"s": 26910,
"text": "router#show flash"
},
{
"code": null,
"e": 26989,
"s": 26928,
"text": "Now, we will copy this file to our Tftp server by command: "
},
{
"code": null,
"e": 27190,
"s": 26989,
"text": "router#copy flash: tftp:\nSource filename[]? c1841-advipservicesk9-mz.124-15.T1.bin\nAddress or name of remote host []? 10.1.1.2\nDestination filename [c1841-advipservicesk9-mz.124-15.T1.bin]? routerios "
},
{
"code": null,
"e": 27316,
"s": 27192,
"text": "Now, as we can see in the above image it is asking for source filename, Address of remote host, and destination filename. "
},
{
"code": null,
"e": 27449,
"s": 27316,
"text": "Source filename – It is the name of the IOS image file. here, it is named c1841-advipservicesk9-mz.124-15.T1.bin (shown in flash). "
},
{
"code": null,
"e": 27558,
"s": 27449,
"text": "Address or name of remote host – It is the IP address of the TFTP server. In our scenario, it is 10.1.1.2. "
},
{
"code": null,
"e": 27693,
"s": 27558,
"text": "Destination filename – It is the name of the destination file that will be put in the TFTP server. Here, we have named it routerIOS. "
},
{
"code": null,
"e": 27823,
"s": 27695,
"text": "As shown in the above figure, the file has been copied to the TFTP server. Now, we will delete the IOS image from the router: "
},
{
"code": null,
"e": 27852,
"s": 27823,
"text": "router(config)#delete flash:"
},
{
"code": null,
"e": 28036,
"s": 27852,
"text": "Note – Now, as the file is deleted still the router is running because the IOS has already been loaded into RAM. Therefore, when we will reload the router, it will enter ROMMON mode. "
},
{
"code": null,
"e": 28120,
"s": 28036,
"text": "Therefore, now to copy the IOS file from the TFTP server we will use the command: "
},
{
"code": null,
"e": 28138,
"s": 28120,
"text": "rommon 1>tftpdnld"
},
{
"code": null,
"e": 28231,
"s": 28140,
"text": "Now, as soon as we type this command, we see the parameters which we have to enter next. "
},
{
"code": null,
"e": 28391,
"s": 28231,
"text": "ROMMON 2>IP_ADDRESS=10.1.1.1\nROMMON 3>IP_SUBNET_MASK=255.255.255.0\nROMMON 4>DEFAULT_GATEWAY=10.1.1.2\nROMMON 5>TFTP_SERVER=10.1.1.2\nROMMON 6>TFTP_FILE=routerios"
},
{
"code": null,
"e": 28595,
"s": 28393,
"text": "IP_ADDRESS – It is the IP address we want to give to our router’s interface fa0/0 but remember this IP address should be of the same subnet. Here, we have provided 10.1.1.1 on the router’s interface. "
},
{
"code": null,
"e": 28736,
"s": 28595,
"text": "IP_SUBNET_MASK – This is the subnet mask that we want to give to the router’s interface IP address which is 255.255.255.0 in our scenario. "
},
{
"code": null,
"e": 29134,
"s": 28736,
"text": "DEFAULT_GATEWAY – Here, we have to give the default gateway for that router’s interface IP address. Here, notice that our TFTP server is directly connected to the router’s interface, therefore, we can give the TFTP server’s IP address which has been given as 10.1.1.2 but if there is any router in between TFTP server and router then we have to give the default gateway IP address of the router. "
},
{
"code": null,
"e": 29241,
"s": 29134,
"text": "TFTP_server – This command requires the IP address of the TFTP server which is 10.1.1.2 in our scenario. "
},
{
"code": null,
"e": 29377,
"s": 29241,
"text": "TFTP_FILE – It is the name of the file which we have saved on the TFTP server. In our scenario, we have given the name routerios.bin. "
},
{
"code": null,
"e": 29458,
"s": 29377,
"text": "After we have entered these commands, we will again enter the command tftpdnld. "
},
{
"code": null,
"e": 29638,
"s": 29460,
"text": "After that, it will ask us to continue to say yes (as shown in the figure) if we have entered the right parameters otherwise enter no and again specify the correct parameters. "
},
{
"code": null,
"e": 29653,
"s": 29638,
"text": "ROMMON 7>reset"
},
{
"code": null,
"e": 29713,
"s": 29653,
"text": "After that just enter command reset to reload the router. "
},
{
"code": null,
"e": 29727,
"s": 29713,
"text": "Pushpender007"
},
{
"code": null,
"e": 29744,
"s": 29727,
"text": "marcosarcticseal"
},
{
"code": null,
"e": 29762,
"s": 29744,
"text": "Computer Networks"
},
{
"code": null,
"e": 29767,
"s": 29762,
"text": "Misc"
},
{
"code": null,
"e": 29772,
"s": 29767,
"text": "Misc"
},
{
"code": null,
"e": 29777,
"s": 29772,
"text": "Misc"
},
{
"code": null,
"e": 29795,
"s": 29777,
"text": "Computer Networks"
},
{
"code": null,
"e": 29893,
"s": 29795,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29928,
"s": 29893,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 29961,
"s": 29928,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 29999,
"s": 29961,
"text": "Introduction and IPv4 Datagram Header"
},
{
"code": null,
"e": 30025,
"s": 29999,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 30052,
"s": 30025,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 30093,
"s": 30052,
"text": "Top 10 algorithms in Interview Questions"
},
{
"code": null,
"e": 30147,
"s": 30093,
"text": "vector::push_back() and vector::pop_back() in C++ STL"
},
{
"code": null,
"e": 30208,
"s": 30147,
"text": "Overview of Data Structures | Set 1 (Linear Data Structures)"
},
{
"code": null,
"e": 30242,
"s": 30208,
"text": "How to write Regular Expressions?"
}
] |
Python program to extract Email-id from URL text file - GeeksforGeeks | 29 Dec, 2020
Prerequisite : Pattern Matching with Python RegexGiven the URL text-file, the task is to extract all the email-ids from that text file and print the urllib.request library can be used to handle all the URL related work.
Example :
Input :
Hello
This is Geeksforgeeks
[email protected]
[email protected]
GfG is a portal for geeks
[email protected]
[email protected]
Output :
[]
[]
['[email protected]']
['[email protected]']
[]
['[email protected]']
['[email protected]']
URL text file can be handled using urllib.request. For extracting the emails using regular expressions, re library can be used. For more details of Regular Expression, refer this.
# library that handles the URL stuffimport urllib.request # Importing module required for# regular expressionsimport re # Assign urlopen to a file object variablefhand = urllib.request.urlopen ('https://media.geeksforgeeks.org/wp-content/uploads/e-mail-1.txt') for line in fhand: # Getting the text file # content line by line. s = line.decode().strip() # regex for extracting all email-ids # from the text file reg = re.findall(r"[A-Za-z0-9._%+-]+" r"@[A-Za-z0-9.-]+" r"\.[A-Za-z]{2,4}", s) # printing the list output print(reg)
Output :
[]
[]
['[email protected]']
['[email protected]']
[]
['[email protected]']
['[email protected]']
Python Regex-programs
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 25757,
"s": 25537,
"text": "Prerequisite : Pattern Matching with Python RegexGiven the URL text-file, the task is to extract all the email-ids from that text file and print the urllib.request library can be used to handle all the URL related work."
},
{
"code": null,
"e": 25767,
"s": 25757,
"text": "Example :"
},
{
"code": null,
"e": 26090,
"s": 25767,
"text": "Input : \nHello\nThis is Geeksforgeeks\[email protected]\[email protected]\nGfG is a portal for geeks\[email protected]\[email protected]\n\nOutput :\n[]\n[]\n['[email protected]']\n['[email protected]']\n[]\n['[email protected]']\n['[email protected]']\n"
},
{
"code": null,
"e": 26271,
"s": 26090,
"text": " URL text file can be handled using urllib.request. For extracting the emails using regular expressions, re library can be used. For more details of Regular Expression, refer this."
},
{
"code": "# library that handles the URL stuffimport urllib.request # Importing module required for# regular expressionsimport re # Assign urlopen to a file object variablefhand = urllib.request.urlopen ('https://media.geeksforgeeks.org/wp-content/uploads/e-mail-1.txt') for line in fhand: # Getting the text file # content line by line. s = line.decode().strip() # regex for extracting all email-ids # from the text file reg = re.findall(r\"[A-Za-z0-9._%+-]+\" r\"@[A-Za-z0-9.-]+\" r\"\\.[A-Za-z]{2,4}\", s) # printing the list output print(reg)",
"e": 26875,
"s": 26271,
"text": null
},
{
"code": null,
"e": 26884,
"s": 26875,
"text": "Output :"
},
{
"code": null,
"e": 27021,
"s": 26884,
"text": "[]\n[]\n['[email protected]']\n['[email protected]']\n[]\n['[email protected]']\n['[email protected]']"
},
{
"code": null,
"e": 27043,
"s": 27021,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 27056,
"s": 27043,
"text": "python-regex"
},
{
"code": null,
"e": 27063,
"s": 27056,
"text": "Python"
},
{
"code": null,
"e": 27161,
"s": 27063,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27193,
"s": 27161,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27235,
"s": 27193,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27277,
"s": 27235,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27304,
"s": 27277,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27360,
"s": 27304,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27399,
"s": 27360,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27421,
"s": 27399,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27452,
"s": 27421,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27481,
"s": 27452,
"text": "Create a directory in Python"
}
] |
PYGLET – On Key Press Event - GeeksforGeeks | 30 Jul, 2021
In this article we will see how we can trigger on key press event in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). A key on the keyboard was pressed (and held down). In pyglet 1.0 the default handler sets has_exit to True if the ESC key is pressed. Key press event is the major event to handle keyboard inputs.We can create a window with the help of command given below
pyglet.window.Window(width, height, title)
Below is the syntax of the on key press event, this method get called when this event is triggered :
@window.event
def on_key_press(symbol, modifiers):
print("Key is pressed")
Example : Below is the implementation
Python3
# importing pyglet moduleimport pygletimport pyglet.window.key # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = "Geeksforgeeks" # creating a windowwindow = pyglet.window.Window(width, height, title) # text text = "GeeksforGeeks" # creating a label with font = times roman# font size = 36# aligning it to the centrelabel = pyglet.text.Label(text, font_name ='Times New Roman', font_size = 36, x = window.width//2, y = window.height//2, anchor_x ='center', anchor_y ='center') new_label = pyglet.text.Label(text, font_name ='Times New Roman', font_size = 10, x = 25, y = 25) # on draw [email protected] on_draw(): # clearing the window window.clear() # drawing the label on the window label.draw() # key press event @window.eventdef on_key_press(symbol, modifier): print("Some key is pressed") # key "C" get press if symbol == pyglet.window.key.C: print("Key C is pressed") # on hide [email protected] on_hide(): # printing some message print("Window is minimized") # image for iconimg = image = pyglet.resource.image("logo.png") # setting image as iconwindow.set_icon(img) # start running the applicationpyglet.app.run()
Output :
Some key is pressed
Key C is pressed
varshagumber28
Python-gui
Python-Pyglet
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": "\n30 Jul, 2021"
},
{
"code": null,
"e": 26169,
"s": 25537,
"text": "In this article we will see how we can trigger on key press event in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). A key on the keyboard was pressed (and held down). In pyglet 1.0 the default handler sets has_exit to True if the ESC key is pressed. Key press event is the major event to handle keyboard inputs.We can create a window with the help of command given below "
},
{
"code": null,
"e": 26212,
"s": 26169,
"text": "pyglet.window.Window(width, height, title)"
},
{
"code": null,
"e": 26314,
"s": 26212,
"text": "Below is the syntax of the on key press event, this method get called when this event is triggered :"
},
{
"code": null,
"e": 26400,
"s": 26314,
"text": "@window.event \ndef on_key_press(symbol, modifiers):\n print(\"Key is pressed\")"
},
{
"code": null,
"e": 26438,
"s": 26400,
"text": "Example : Below is the implementation"
},
{
"code": null,
"e": 26446,
"s": 26438,
"text": "Python3"
},
{
"code": "# importing pyglet moduleimport pygletimport pyglet.window.key # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = \"Geeksforgeeks\" # creating a windowwindow = pyglet.window.Window(width, height, title) # text text = \"GeeksforGeeks\" # creating a label with font = times roman# font size = 36# aligning it to the centrelabel = pyglet.text.Label(text, font_name ='Times New Roman', font_size = 36, x = window.width//2, y = window.height//2, anchor_x ='center', anchor_y ='center') new_label = pyglet.text.Label(text, font_name ='Times New Roman', font_size = 10, x = 25, y = 25) # on draw [email protected] on_draw(): # clearing the window window.clear() # drawing the label on the window label.draw() # key press event @window.eventdef on_key_press(symbol, modifier): print(\"Some key is pressed\") # key \"C\" get press if symbol == pyglet.window.key.C: print(\"Key C is pressed\") # on hide [email protected] on_hide(): # printing some message print(\"Window is minimized\") # image for iconimg = image = pyglet.resource.image(\"logo.png\") # setting image as iconwindow.set_icon(img) # start running the applicationpyglet.app.run()",
"e": 27933,
"s": 26446,
"text": null
},
{
"code": null,
"e": 27944,
"s": 27933,
"text": "Output : "
},
{
"code": null,
"e": 27981,
"s": 27944,
"text": "Some key is pressed\nKey C is pressed"
},
{
"code": null,
"e": 27998,
"s": 27983,
"text": "varshagumber28"
},
{
"code": null,
"e": 28009,
"s": 27998,
"text": "Python-gui"
},
{
"code": null,
"e": 28023,
"s": 28009,
"text": "Python-Pyglet"
},
{
"code": null,
"e": 28030,
"s": 28023,
"text": "Python"
},
{
"code": null,
"e": 28128,
"s": 28030,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28160,
"s": 28128,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28202,
"s": 28160,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28244,
"s": 28202,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28271,
"s": 28244,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28327,
"s": 28271,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28349,
"s": 28327,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28388,
"s": 28349,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28419,
"s": 28388,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28448,
"s": 28419,
"text": "Create a directory in Python"
}
] |
How to detect whether the website is being opened in a mobile device or a desktop in JavaScript ? - GeeksforGeeks | 21 May, 2021
Using CSS Media Queries, we can easily know that a user is currently viewing our website in which device (using min-width and max-width). It is only limited to styling web pages, but we can control the functionality of the website according to the user’s device using the navigator userAgent Property in JavaScript.
We can get information about the user’s device. It returns a string containing the user browser’s name, version, operating system, etc.
Syntax:
navigator.userAgent
Return Type: It returns the following string for a Windows desktop:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/90.0.4430.85 Safari/537.36
Example: Using this property, we can easily predict that it is opened on a Desktop or Mobile Device as shown in the below code.
HTML
<html><body> <script> /* Storing user's device details in a variable*/ let details = navigator.userAgent; /* Creating a regular expression containing some mobile devices keywords to search it in details string*/ let regexp = /android|iphone|kindle|ipad/i; /* Using test() method to search regexp in details it returns boolean value*/ let isMobileDevice = regexp.test(details); if (isMobileDevice) { document.write("You are using a Mobile Device"); } else { document.write("You are using Desktop"); } </script></body></html>
Output: Following will be the output for desktop browser:
You are using Desktop
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 26861,
"s": 26545,
"text": "Using CSS Media Queries, we can easily know that a user is currently viewing our website in which device (using min-width and max-width). It is only limited to styling web pages, but we can control the functionality of the website according to the user’s device using the navigator userAgent Property in JavaScript."
},
{
"code": null,
"e": 26997,
"s": 26861,
"text": "We can get information about the user’s device. It returns a string containing the user browser’s name, version, operating system, etc."
},
{
"code": null,
"e": 27005,
"s": 26997,
"text": "Syntax:"
},
{
"code": null,
"e": 27026,
"s": 27005,
"text": "navigator.userAgent "
},
{
"code": null,
"e": 27094,
"s": 27026,
"text": "Return Type: It returns the following string for a Windows desktop:"
},
{
"code": null,
"e": 27210,
"s": 27094,
"text": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \nChrome/90.0.4430.85 Safari/537.36"
},
{
"code": null,
"e": 27338,
"s": 27210,
"text": "Example: Using this property, we can easily predict that it is opened on a Desktop or Mobile Device as shown in the below code."
},
{
"code": null,
"e": 27343,
"s": 27338,
"text": "HTML"
},
{
"code": "<html><body> <script> /* Storing user's device details in a variable*/ let details = navigator.userAgent; /* Creating a regular expression containing some mobile devices keywords to search it in details string*/ let regexp = /android|iphone|kindle|ipad/i; /* Using test() method to search regexp in details it returns boolean value*/ let isMobileDevice = regexp.test(details); if (isMobileDevice) { document.write(\"You are using a Mobile Device\"); } else { document.write(\"You are using Desktop\"); } </script></body></html>",
"e": 27987,
"s": 27343,
"text": null
},
{
"code": null,
"e": 28045,
"s": 27987,
"text": "Output: Following will be the output for desktop browser:"
},
{
"code": null,
"e": 28067,
"s": 28045,
"text": "You are using Desktop"
},
{
"code": null,
"e": 28088,
"s": 28067,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 28095,
"s": 28088,
"text": "Picked"
},
{
"code": null,
"e": 28106,
"s": 28095,
"text": "JavaScript"
},
{
"code": null,
"e": 28123,
"s": 28106,
"text": "Web Technologies"
},
{
"code": null,
"e": 28221,
"s": 28123,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28261,
"s": 28221,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28322,
"s": 28261,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28363,
"s": 28322,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28385,
"s": 28363,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28439,
"s": 28385,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28479,
"s": 28439,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28512,
"s": 28479,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28555,
"s": 28512,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28617,
"s": 28555,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Array of Vectors in C++ STL - GeeksforGeeks | 14 Feb, 2020
Prerequisite: Arrays in C++, Vector in C++ STL
An array is a collection of items stored at contiguous memory locations. It is to store multiple items of the same type together. This makes it easier to get access to the elements stored in it by the position of each element.
Vectors are known as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container automatically.
Therefore, array of vectors is two dimensional array with fixed number of rows where each row is vector of variable length. Each index of array stores a vector which can be traversed and accessed using iterators.
Syntax:
vector <data_type> V[size];
Example:
vector <int> A[5];
where A is the array of vectors of int of size 5
Insertion: Insertion in array of vectors is done using push_back() function.
For Example:
for i in [0, n) {
A[i].push_back(35)
}
Above pseudo-code inserts element 35 at every index of vector <int> A[n].
Traversal: Traversal in an array of vectors is perform using iterators.
For Example:
for i in [0, n) {
for(iterator it = A[i].begin();
it!=A[i].end(); it++) {
print(*it)
}
}
Above pseudo-code traverses vector <int> A[n] at each index using starting iterators A[i].begin() and ending iterator A[i].end(). For accessing the element it uses (*it) as iterators are pointers pointing to elements in vector <int> A[n].
Below is the program to illustrate the insertion in the array of vectors.
// C++ program to illustrate// array of vectors #include <iostream>#include <vector>using namespace std; // Declaring array of vectors// globallyvector<int> v[5]; // Function for inserting elements// in array of vectorsvoid insertionInArrayOfVectors(){ for (int i = 0; i < 5; i++) { // Inserting elements at every // row i using push_back() // function in vector for (int j = i + 1; j < 5; j++) { v[i].push_back(j); } }} // Function to print elements in array// of vectorsvoid printElements(){ // Traversing of vectors v to print // elements stored in it for (int i = 0; i < 5; i++) { cout << "Elements at index " << i << ": "; // Displaying element at each column, // begin() is the starting iterator, // end() is the ending iterator for (auto it = v[i].begin(); it != v[i].end(); it++) { // (*it) is used to get the // value at iterator is // pointing cout << *it << ' '; } cout << endl; }} // Function to illustrate array// of vectorsvoid arrayOfVectors(){ // Inserting elements in array // of vectors insertionInArrayOfVectors(); // Print elements stored in array // of vectors printElements();} // Driver codeint main(){ arrayOfVectors(); return 0;}
Elements at index 0: 1 2 3 4
Elements at index 1: 2 3 4
Elements at index 2: 3 4
Elements at index 3: 4
Elements at index 4:
Arrays
cpp-iterator
cpp-vector
STL
Technical Scripter 2019
Algorithms
C++
Technical Scripter
Arrays
STL
Algorithms
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to Start Learning DSA?
Introduction to Algorithms
Difference between NP hard and NP complete problem
Arrays in C/C++
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
std::sort() in C++ STL | [
{
"code": null,
"e": 25842,
"s": 25814,
"text": "\n14 Feb, 2020"
},
{
"code": null,
"e": 25889,
"s": 25842,
"text": "Prerequisite: Arrays in C++, Vector in C++ STL"
},
{
"code": null,
"e": 26116,
"s": 25889,
"text": "An array is a collection of items stored at contiguous memory locations. It is to store multiple items of the same type together. This makes it easier to get access to the elements stored in it by the position of each element."
},
{
"code": null,
"e": 26319,
"s": 26116,
"text": "Vectors are known as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container automatically."
},
{
"code": null,
"e": 26532,
"s": 26319,
"text": "Therefore, array of vectors is two dimensional array with fixed number of rows where each row is vector of variable length. Each index of array stores a vector which can be traversed and accessed using iterators."
},
{
"code": null,
"e": 26540,
"s": 26532,
"text": "Syntax:"
},
{
"code": null,
"e": 26569,
"s": 26540,
"text": "vector <data_type> V[size];\n"
},
{
"code": null,
"e": 26578,
"s": 26569,
"text": "Example:"
},
{
"code": null,
"e": 26647,
"s": 26578,
"text": "vector <int> A[5];\nwhere A is the array of vectors of int of size 5\n"
},
{
"code": null,
"e": 26724,
"s": 26647,
"text": "Insertion: Insertion in array of vectors is done using push_back() function."
},
{
"code": null,
"e": 26737,
"s": 26724,
"text": "For Example:"
},
{
"code": null,
"e": 26779,
"s": 26737,
"text": "for i in [0, n) {\n A[i].push_back(35)\n}\n"
},
{
"code": null,
"e": 26853,
"s": 26779,
"text": "Above pseudo-code inserts element 35 at every index of vector <int> A[n]."
},
{
"code": null,
"e": 26925,
"s": 26853,
"text": "Traversal: Traversal in an array of vectors is perform using iterators."
},
{
"code": null,
"e": 26938,
"s": 26925,
"text": "For Example:"
},
{
"code": null,
"e": 27049,
"s": 26938,
"text": "for i in [0, n) {\n for(iterator it = A[i].begin(); \n it!=A[i].end(); it++) {\n print(*it)\n }\n}\n"
},
{
"code": null,
"e": 27288,
"s": 27049,
"text": "Above pseudo-code traverses vector <int> A[n] at each index using starting iterators A[i].begin() and ending iterator A[i].end(). For accessing the element it uses (*it) as iterators are pointers pointing to elements in vector <int> A[n]."
},
{
"code": null,
"e": 27362,
"s": 27288,
"text": "Below is the program to illustrate the insertion in the array of vectors."
},
{
"code": "// C++ program to illustrate// array of vectors #include <iostream>#include <vector>using namespace std; // Declaring array of vectors// globallyvector<int> v[5]; // Function for inserting elements// in array of vectorsvoid insertionInArrayOfVectors(){ for (int i = 0; i < 5; i++) { // Inserting elements at every // row i using push_back() // function in vector for (int j = i + 1; j < 5; j++) { v[i].push_back(j); } }} // Function to print elements in array// of vectorsvoid printElements(){ // Traversing of vectors v to print // elements stored in it for (int i = 0; i < 5; i++) { cout << \"Elements at index \" << i << \": \"; // Displaying element at each column, // begin() is the starting iterator, // end() is the ending iterator for (auto it = v[i].begin(); it != v[i].end(); it++) { // (*it) is used to get the // value at iterator is // pointing cout << *it << ' '; } cout << endl; }} // Function to illustrate array// of vectorsvoid arrayOfVectors(){ // Inserting elements in array // of vectors insertionInArrayOfVectors(); // Print elements stored in array // of vectors printElements();} // Driver codeint main(){ arrayOfVectors(); return 0;}",
"e": 28742,
"s": 27362,
"text": null
},
{
"code": null,
"e": 28872,
"s": 28742,
"text": "Elements at index 0: 1 2 3 4 \nElements at index 1: 2 3 4 \nElements at index 2: 3 4 \nElements at index 3: 4 \nElements at index 4:\n"
},
{
"code": null,
"e": 28879,
"s": 28872,
"text": "Arrays"
},
{
"code": null,
"e": 28892,
"s": 28879,
"text": "cpp-iterator"
},
{
"code": null,
"e": 28903,
"s": 28892,
"text": "cpp-vector"
},
{
"code": null,
"e": 28907,
"s": 28903,
"text": "STL"
},
{
"code": null,
"e": 28931,
"s": 28907,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 28942,
"s": 28931,
"text": "Algorithms"
},
{
"code": null,
"e": 28946,
"s": 28942,
"text": "C++"
},
{
"code": null,
"e": 28965,
"s": 28946,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28972,
"s": 28965,
"text": "Arrays"
},
{
"code": null,
"e": 28976,
"s": 28972,
"text": "STL"
},
{
"code": null,
"e": 28987,
"s": 28976,
"text": "Algorithms"
},
{
"code": null,
"e": 28991,
"s": 28987,
"text": "CPP"
},
{
"code": null,
"e": 29089,
"s": 28991,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29138,
"s": 29089,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 29163,
"s": 29138,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 29190,
"s": 29163,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 29217,
"s": 29190,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 29268,
"s": 29217,
"text": "Difference between NP hard and NP complete problem"
},
{
"code": null,
"e": 29284,
"s": 29268,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 29303,
"s": 29284,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29349,
"s": 29303,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29392,
"s": 29349,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
LinkedList addAll() Method in Java - GeeksforGeeks | 10 Dec, 2018
java.util.LinkedList.addAll(Collection C): This method is used to append all of the elements from the collection passed as parameter to this function to the end of a list keeping in mind the order of return by the collections iterator.Syntax:boolean addAll(Collection C)Parameters: The parameter C is a collection of ArrayList. It is the collection whose elements are needed to be appended at the end of the list.Return Value: The method returns true if at least one action of append is performed.Below program illustrate the Java.util.LinkedList.addAll() method:// Java code to illustrate boolean addAll()import java.util.*;import java.util.LinkedList;import java.util.ArrayList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // A collection is created Collection<String> collect = new ArrayList<String>(); collect.add("A"); collect.add("Computer"); collect.add("Portal"); collect.add("for"); collect.add("Geeks"); // Displaying the list System.out.println("The LinkedList is: " + list); // Appending the collection to the list list.addAll(collect); // Clearing the list using clear() and displaying System.out.println("The new linked list is: " + list); }}Output:The LinkedList is: [Geeks, for, Geeks, 10, 20]
The new linked list is: [Geeks, for, Geeks, 10, 20, A, Computer, Portal, for, Geeks]
java.util.LinkedList.addAll(int index, Collection C): This method is used to append all of the elements from the collection passed as parameter to this function at a specific index or position of a list.Syntax:boolean addAll(int index, Collection C)Parameters: This function accepts two parameters as shown in the above syntax and are described below.index: This parameter is of integer datatype and specifies the position in the list starting from where the elements from the container will be inserted.C: It is a collection of ArrayList. It is the collection whose elements are needed to be appended.Return Value: The method returns TRUE if at least one action of append is performed.Below program illustrate the Java.util.LinkedList.addAll() method:// Java code to illustrate boolean addAll()import java.util.*;import java.util.LinkedList;import java.util.ArrayList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Creating a Collection Collection<String> collect = new ArrayList<String>(); collect.add("A"); collect.add("Computer"); collect.add("Portal"); collect.add("for"); collect.add("Geeks"); // Displaying the list System.out.println("The LinkedList is: " + list); // Appending the collection to the list list.addAll(1, collect); // Clearing the list using clear() and displaying System.out.println("The new linked list is: " + list); }}Output:The LinkedList is: [Geeks, for, Geeks, 10, 20]
The new linked list is: [Geeks, A, Computer, Portal, for, Geeks, for, Geeks, 10, 20]
java.util.LinkedList.addAll(Collection C): This method is used to append all of the elements from the collection passed as parameter to this function to the end of a list keeping in mind the order of return by the collections iterator.Syntax:boolean addAll(Collection C)Parameters: The parameter C is a collection of ArrayList. It is the collection whose elements are needed to be appended at the end of the list.Return Value: The method returns true if at least one action of append is performed.Below program illustrate the Java.util.LinkedList.addAll() method:// Java code to illustrate boolean addAll()import java.util.*;import java.util.LinkedList;import java.util.ArrayList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // A collection is created Collection<String> collect = new ArrayList<String>(); collect.add("A"); collect.add("Computer"); collect.add("Portal"); collect.add("for"); collect.add("Geeks"); // Displaying the list System.out.println("The LinkedList is: " + list); // Appending the collection to the list list.addAll(collect); // Clearing the list using clear() and displaying System.out.println("The new linked list is: " + list); }}Output:The LinkedList is: [Geeks, for, Geeks, 10, 20]
The new linked list is: [Geeks, for, Geeks, 10, 20, A, Computer, Portal, for, Geeks]
Syntax:
boolean addAll(Collection C)
Parameters: The parameter C is a collection of ArrayList. It is the collection whose elements are needed to be appended at the end of the list.
Return Value: The method returns true if at least one action of append is performed.
Below program illustrate the Java.util.LinkedList.addAll() method:
// Java code to illustrate boolean addAll()import java.util.*;import java.util.LinkedList;import java.util.ArrayList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // A collection is created Collection<String> collect = new ArrayList<String>(); collect.add("A"); collect.add("Computer"); collect.add("Portal"); collect.add("for"); collect.add("Geeks"); // Displaying the list System.out.println("The LinkedList is: " + list); // Appending the collection to the list list.addAll(collect); // Clearing the list using clear() and displaying System.out.println("The new linked list is: " + list); }}
The LinkedList is: [Geeks, for, Geeks, 10, 20]
The new linked list is: [Geeks, for, Geeks, 10, 20, A, Computer, Portal, for, Geeks]
java.util.LinkedList.addAll(int index, Collection C): This method is used to append all of the elements from the collection passed as parameter to this function at a specific index or position of a list.Syntax:boolean addAll(int index, Collection C)Parameters: This function accepts two parameters as shown in the above syntax and are described below.index: This parameter is of integer datatype and specifies the position in the list starting from where the elements from the container will be inserted.C: It is a collection of ArrayList. It is the collection whose elements are needed to be appended.Return Value: The method returns TRUE if at least one action of append is performed.Below program illustrate the Java.util.LinkedList.addAll() method:// Java code to illustrate boolean addAll()import java.util.*;import java.util.LinkedList;import java.util.ArrayList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Creating a Collection Collection<String> collect = new ArrayList<String>(); collect.add("A"); collect.add("Computer"); collect.add("Portal"); collect.add("for"); collect.add("Geeks"); // Displaying the list System.out.println("The LinkedList is: " + list); // Appending the collection to the list list.addAll(1, collect); // Clearing the list using clear() and displaying System.out.println("The new linked list is: " + list); }}Output:The LinkedList is: [Geeks, for, Geeks, 10, 20]
The new linked list is: [Geeks, A, Computer, Portal, for, Geeks, for, Geeks, 10, 20]
Syntax:
boolean addAll(int index, Collection C)
Parameters: This function accepts two parameters as shown in the above syntax and are described below.
index: This parameter is of integer datatype and specifies the position in the list starting from where the elements from the container will be inserted.
C: It is a collection of ArrayList. It is the collection whose elements are needed to be appended.
Return Value: The method returns TRUE if at least one action of append is performed.
Below program illustrate the Java.util.LinkedList.addAll() method:
// Java code to illustrate boolean addAll()import java.util.*;import java.util.LinkedList;import java.util.ArrayList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Creating a Collection Collection<String> collect = new ArrayList<String>(); collect.add("A"); collect.add("Computer"); collect.add("Portal"); collect.add("for"); collect.add("Geeks"); // Displaying the list System.out.println("The LinkedList is: " + list); // Appending the collection to the list list.addAll(1, collect); // Clearing the list using clear() and displaying System.out.println("The new linked list is: " + list); }}
The LinkedList is: [Geeks, for, Geeks, 10, 20]
The new linked list is: [Geeks, A, Computer, Portal, for, Geeks, for, Geeks, 10, 20]
Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java | [
{
"code": null,
"e": 25250,
"s": 25222,
"text": "\n10 Dec, 2018"
},
{
"code": null,
"e": 28803,
"s": 25250,
"text": "java.util.LinkedList.addAll(Collection C): This method is used to append all of the elements from the collection passed as parameter to this function to the end of a list keeping in mind the order of return by the collections iterator.Syntax:boolean addAll(Collection C)Parameters: The parameter C is a collection of ArrayList. It is the collection whose elements are needed to be appended at the end of the list.Return Value: The method returns true if at least one action of append is performed.Below program illustrate the Java.util.LinkedList.addAll() method:// Java code to illustrate boolean addAll()import java.util.*;import java.util.LinkedList;import java.util.ArrayList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // A collection is created Collection<String> collect = new ArrayList<String>(); collect.add(\"A\"); collect.add(\"Computer\"); collect.add(\"Portal\"); collect.add(\"for\"); collect.add(\"Geeks\"); // Displaying the list System.out.println(\"The LinkedList is: \" + list); // Appending the collection to the list list.addAll(collect); // Clearing the list using clear() and displaying System.out.println(\"The new linked list is: \" + list); }}Output:The LinkedList is: [Geeks, for, Geeks, 10, 20]\nThe new linked list is: [Geeks, for, Geeks, 10, 20, A, Computer, Portal, for, Geeks]\njava.util.LinkedList.addAll(int index, Collection C): This method is used to append all of the elements from the collection passed as parameter to this function at a specific index or position of a list.Syntax:boolean addAll(int index, Collection C)Parameters: This function accepts two parameters as shown in the above syntax and are described below.index: This parameter is of integer datatype and specifies the position in the list starting from where the elements from the container will be inserted.C: It is a collection of ArrayList. It is the collection whose elements are needed to be appended.Return Value: The method returns TRUE if at least one action of append is performed.Below program illustrate the Java.util.LinkedList.addAll() method:// Java code to illustrate boolean addAll()import java.util.*;import java.util.LinkedList;import java.util.ArrayList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Creating a Collection Collection<String> collect = new ArrayList<String>(); collect.add(\"A\"); collect.add(\"Computer\"); collect.add(\"Portal\"); collect.add(\"for\"); collect.add(\"Geeks\"); // Displaying the list System.out.println(\"The LinkedList is: \" + list); // Appending the collection to the list list.addAll(1, collect); // Clearing the list using clear() and displaying System.out.println(\"The new linked list is: \" + list); }}Output:The LinkedList is: [Geeks, for, Geeks, 10, 20]\nThe new linked list is: [Geeks, A, Computer, Portal, for, Geeks, for, Geeks, 10, 20]\n"
},
{
"code": null,
"e": 30485,
"s": 28803,
"text": "java.util.LinkedList.addAll(Collection C): This method is used to append all of the elements from the collection passed as parameter to this function to the end of a list keeping in mind the order of return by the collections iterator.Syntax:boolean addAll(Collection C)Parameters: The parameter C is a collection of ArrayList. It is the collection whose elements are needed to be appended at the end of the list.Return Value: The method returns true if at least one action of append is performed.Below program illustrate the Java.util.LinkedList.addAll() method:// Java code to illustrate boolean addAll()import java.util.*;import java.util.LinkedList;import java.util.ArrayList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // A collection is created Collection<String> collect = new ArrayList<String>(); collect.add(\"A\"); collect.add(\"Computer\"); collect.add(\"Portal\"); collect.add(\"for\"); collect.add(\"Geeks\"); // Displaying the list System.out.println(\"The LinkedList is: \" + list); // Appending the collection to the list list.addAll(collect); // Clearing the list using clear() and displaying System.out.println(\"The new linked list is: \" + list); }}Output:The LinkedList is: [Geeks, for, Geeks, 10, 20]\nThe new linked list is: [Geeks, for, Geeks, 10, 20, A, Computer, Portal, for, Geeks]\n"
},
{
"code": null,
"e": 30493,
"s": 30485,
"text": "Syntax:"
},
{
"code": null,
"e": 30522,
"s": 30493,
"text": "boolean addAll(Collection C)"
},
{
"code": null,
"e": 30666,
"s": 30522,
"text": "Parameters: The parameter C is a collection of ArrayList. It is the collection whose elements are needed to be appended at the end of the list."
},
{
"code": null,
"e": 30751,
"s": 30666,
"text": "Return Value: The method returns true if at least one action of append is performed."
},
{
"code": null,
"e": 30818,
"s": 30751,
"text": "Below program illustrate the Java.util.LinkedList.addAll() method:"
},
{
"code": "// Java code to illustrate boolean addAll()import java.util.*;import java.util.LinkedList;import java.util.ArrayList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // A collection is created Collection<String> collect = new ArrayList<String>(); collect.add(\"A\"); collect.add(\"Computer\"); collect.add(\"Portal\"); collect.add(\"for\"); collect.add(\"Geeks\"); // Displaying the list System.out.println(\"The LinkedList is: \" + list); // Appending the collection to the list list.addAll(collect); // Clearing the list using clear() and displaying System.out.println(\"The new linked list is: \" + list); }}",
"e": 31798,
"s": 30818,
"text": null
},
{
"code": null,
"e": 31931,
"s": 31798,
"text": "The LinkedList is: [Geeks, for, Geeks, 10, 20]\nThe new linked list is: [Geeks, for, Geeks, 10, 20, A, Computer, Portal, for, Geeks]\n"
},
{
"code": null,
"e": 33803,
"s": 31931,
"text": "java.util.LinkedList.addAll(int index, Collection C): This method is used to append all of the elements from the collection passed as parameter to this function at a specific index or position of a list.Syntax:boolean addAll(int index, Collection C)Parameters: This function accepts two parameters as shown in the above syntax and are described below.index: This parameter is of integer datatype and specifies the position in the list starting from where the elements from the container will be inserted.C: It is a collection of ArrayList. It is the collection whose elements are needed to be appended.Return Value: The method returns TRUE if at least one action of append is performed.Below program illustrate the Java.util.LinkedList.addAll() method:// Java code to illustrate boolean addAll()import java.util.*;import java.util.LinkedList;import java.util.ArrayList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Creating a Collection Collection<String> collect = new ArrayList<String>(); collect.add(\"A\"); collect.add(\"Computer\"); collect.add(\"Portal\"); collect.add(\"for\"); collect.add(\"Geeks\"); // Displaying the list System.out.println(\"The LinkedList is: \" + list); // Appending the collection to the list list.addAll(1, collect); // Clearing the list using clear() and displaying System.out.println(\"The new linked list is: \" + list); }}Output:The LinkedList is: [Geeks, for, Geeks, 10, 20]\nThe new linked list is: [Geeks, A, Computer, Portal, for, Geeks, for, Geeks, 10, 20]\n"
},
{
"code": null,
"e": 33811,
"s": 33803,
"text": "Syntax:"
},
{
"code": null,
"e": 33851,
"s": 33811,
"text": "boolean addAll(int index, Collection C)"
},
{
"code": null,
"e": 33954,
"s": 33851,
"text": "Parameters: This function accepts two parameters as shown in the above syntax and are described below."
},
{
"code": null,
"e": 34108,
"s": 33954,
"text": "index: This parameter is of integer datatype and specifies the position in the list starting from where the elements from the container will be inserted."
},
{
"code": null,
"e": 34207,
"s": 34108,
"text": "C: It is a collection of ArrayList. It is the collection whose elements are needed to be appended."
},
{
"code": null,
"e": 34292,
"s": 34207,
"text": "Return Value: The method returns TRUE if at least one action of append is performed."
},
{
"code": null,
"e": 34359,
"s": 34292,
"text": "Below program illustrate the Java.util.LinkedList.addAll() method:"
},
{
"code": "// Java code to illustrate boolean addAll()import java.util.*;import java.util.LinkedList;import java.util.ArrayList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Creating a Collection Collection<String> collect = new ArrayList<String>(); collect.add(\"A\"); collect.add(\"Computer\"); collect.add(\"Portal\"); collect.add(\"for\"); collect.add(\"Geeks\"); // Displaying the list System.out.println(\"The LinkedList is: \" + list); // Appending the collection to the list list.addAll(1, collect); // Clearing the list using clear() and displaying System.out.println(\"The new linked list is: \" + list); }}",
"e": 35340,
"s": 34359,
"text": null
},
{
"code": null,
"e": 35473,
"s": 35340,
"text": "The LinkedList is: [Geeks, for, Geeks, 10, 20]\nThe new linked list is: [Geeks, A, Computer, Portal, for, Geeks, for, Geeks, 10, 20]\n"
},
{
"code": null,
"e": 35493,
"s": 35473,
"text": "Java - util package"
},
{
"code": null,
"e": 35510,
"s": 35493,
"text": "Java-Collections"
},
{
"code": null,
"e": 35525,
"s": 35510,
"text": "Java-Functions"
},
{
"code": null,
"e": 35541,
"s": 35525,
"text": "java-LinkedList"
},
{
"code": null,
"e": 35546,
"s": 35541,
"text": "Java"
},
{
"code": null,
"e": 35551,
"s": 35546,
"text": "Java"
},
{
"code": null,
"e": 35568,
"s": 35551,
"text": "Java-Collections"
},
{
"code": null,
"e": 35666,
"s": 35568,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35681,
"s": 35666,
"text": "Stream In Java"
},
{
"code": null,
"e": 35702,
"s": 35681,
"text": "Constructors in Java"
},
{
"code": null,
"e": 35721,
"s": 35702,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 35751,
"s": 35721,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 35797,
"s": 35751,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 35814,
"s": 35797,
"text": "Generics in Java"
},
{
"code": null,
"e": 35835,
"s": 35814,
"text": "Introduction to Java"
},
{
"code": null,
"e": 35878,
"s": 35835,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 35914,
"s": 35878,
"text": "Internal Working of HashMap in Java"
}
] |
Memoization (1D, 2D and 3D) - GeeksforGeeks | 08 Nov, 2021
Most of the Dynamic Programming problems are solved in two ways:
Tabulation: Bottom UpMemoization: Top Down
Tabulation: Bottom Up
Memoization: Top Down
One of the easier approaches to solve most of the problems in DP is to write the recursive code at first and then write the Bottom-up Tabulation Method or Top-down Memoization of the recursive function. The steps to write the DP solution of Top-down approach to any problem is to:
Write the recursive codeMemoize the return value and use it to reduce recursive calls.
Write the recursive code
Memoize the return value and use it to reduce recursive calls.
1-D MemoizationThe first step will be to write the recursive code. In the program below, a program related to recursion where only one parameter changes its value has been shown. Since only one parameter is non-constant, this method is known as 1-D memoization. E.g., the Fibonacci series problem to find the N-th term in the Fibonacci series. The recursive approach has been discussed here.Given below is the recursive code to find the N-th term:
C++
Java
Python3
C#
Javascript
PHP
// C++ program to find the Nth term// of Fibonacci series#include <bits/stdc++.h>using namespace std; // Fibonacci Series using Recursionint fib(int n){ // Base case if (n <= 1) return n; // recursive calls return fib(n - 1) + fib(n - 2);} // Driver Codeint main(){ int n = 6; printf("%d", fib(n)); return 0;}
// Java program to find the// Nth term of Fibonacci seriesimport java.io.*; class GFG{ // Fibonacci Series// using Recursionstatic int fib(int n){ // Base case if (n <= 1) return n; // recursive calls return fib(n - 1) + fib(n - 2);} // Driver Codepublic static void main (String[] args){ int n = 6; System.out.println(fib(n));}} // This code is contributed// by ajit
# Python3 program to find the Nth term# of Fibonacci series # Fibonacci Series using Recursiondef fib(n): # Base case if (n <= 1): return n # recursive calls return fib(n - 1) + fib(n - 2) # Driver Codeif __name__=='__main__': n = 6 print (fib(n)) # This code is contributed by# Shivi_Aggarwal
// C# program to find// the Nth term of// Fibonacci seriesusing System; class GFG{ // Fibonacci Series// using Recursionstatic int fib(int n){ // Base case if (n <= 1) return n; // recursive calls return fib(n - 1) + fib(n - 2);}// Driver Codestatic public void Main (){ int n = 6; Console.WriteLine(fib(n));}} // This code is contributed// by akt_mit
<script>// Javascript program to find the Nth term// of Fibonacci series // Fibonacci Series using Recursionfunction fib(n){ // Base case if (n <= 1) return n; // recursive calls return fib(n - 1) + fib(n - 2);} // Driver Codelet n = 6;document.write(fib(n)); // This code is contributed by subhammahato348.</script>
<?php// PHP program to find// the Nth term of// Fibonacci series// using Recursion function fib($n){ // Base case if ($n <= 1) return $n; // recursive calls return fib($n - 1) + fib($n - 2);} // Driver Code$n = 6;echo fib($n); // This code is contributed// by ajit?>
8
A common observation is that this implementation does a lot of repeated work (see the following recursion tree). So this will consume a lot of time for finding the N-th Fibonacci number if done.
fib(5)
/ \
fib(4) fib(3)
/ \ / \
fib(3) fib(2) fib(2) fib(1)
/ \ / \ / \
fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)
/ \
fib(1) fib(0)
In the above tree fib(3), fib(2), fib(1), fib(0) all are called more then once.
The following problem has been solved using the Tabulation method. In the program below, the steps to write a Top-Down approach program have been explained. Some modifications in the recursive program will reduce the complexity of the program and give the desired result. If fib(x) has not occurred previously, then we store the value of fib(x) in an array term at index x and return term[x]. By memoizing the return value of fib(x) at index x of an array, reduce the number of recursive calls at the next step when fib(x) has already been called. So without doing further recursive calls to compute the value of fib(x), return term[x] when fib(x) has already been computed previously to avoid a lot of repeated work as shown in the tree. Given below is the memoized recursive code to find the N-th term.
C++
Java
Python3
C#
Javascript
// CPP program to find the Nth term// of Fibonacci series#include <bits/stdc++.h>using namespace std;int term[1000];// Fibonacci Series using memoized Recursionint fib(int n){ // base case if (n <= 1) return n; // if fib(n) has already been computed // we do not do further recursive calls // and hence reduce the number of repeated // work if (term[n] != 0) return term[n]; else { // store the computed value of fib(n) // in an array term at index n to // so that it does not needs to be // precomputed again term[n] = fib(n - 1) + fib(n - 2); return term[n]; }} // Driver Codeint main(){ int n = 6; printf("%d", fib(n)); return 0;}
// Java program to find// the Nth term of// Fibonacci seriesimport java.io.*; class GFG{ static int []term = new int [1000];// Fibonacci Series using// memoized Recursionstatic int fib(int n){ // base case if (n <= 1) return n; // if fib(n) has already // been computed we do not // do further recursive // calls and hence reduce // the number of repeated // work if (term[n] != 0) return term[n]; else { // store the computed value // of fib(n) in an array // term at index n to so that // it does not needs to be // precomputed again term[n] = fib(n - 1) + fib(n - 2); return term[n]; }} // Driver Codepublic static void main (String[] args){ int n = 6; System.out.println(fib(n));}} // This code is contributed by ajit
# Python program to find the Nth term# of Fibonacci seriesterm = [0 for i in range(1000)] # Fibonacci Series using memoized Recursiondef fib(n): # base case if n <= 1: return n # if fib(n) has already been computed # we do not do further recursive calls # and hence reduce the number of repeated # work if term[n] != 0: return term[n] else: # store the computed value of fib(n) # in an array term at index n to # so that it does not needs to be # precomputed again term[n] = fib(n - 1) + fib(n - 2) return term[n] # Driver Coden = 6print(fib(n)) # This code is contributed by rohitsingh07052
// C# program to find// the Nth term of// Fibonacci series using System;class GFG{ // Fibonacci Series using// memoized Recursionstatic int fib(int n){ int[] term = new int [1000]; // base case if (n <= 1) return n; // if fib(n) has already // been computed we do not // do further recursive // calls and hence reduce // the number of repeated // work if (term[n] != 0) return term[n]; else { // store the computed value // of fib(n) in an array // term at index n to so that // it does not needs to be // precomputed again term[n] = fib(n - 1) + fib(n - 2); return term[n]; }} // Driver Codepublic static void Main (){ int n = 6; Console.Write(fib(n));}}
<script> // Javascript program to find // the Nth term of // Fibonacci series // Fibonacci Series using // memoized Recursion function fib(n) { let term = new Array(1000); term.fill(0); // base case if (n <= 1) return n; // if fib(n) has already // been computed we do not // do further recursive // calls and hence reduce // the number of repeated // work if (term[n] != 0) return term[n]; else { // store the computed value // of fib(n) in an array // term at index n to so that // it does not needs to be // precomputed again term[n] = fib(n - 1) + fib(n - 2); return term[n]; } } let n = 6; document.write(fib(n)); // This code is contributed by mukesh07.</script>
8
If the recursive code has been written once, then memoization is just modifying the recursive program and storing the return values to avoid repetitive calls of functions that have been computed previously.
2-D MemoizationIn the above program, the recursive function had only one argument whose value was not constant after every function call. Below, an implementation where the recursive program has two non-constant arguments has been shown. For e.g., Program to solve the standard Dynamic Problem LCS problem when two strings are given. The general recursive solution of the problem is to generate all subsequences of both given sequences and find the longest matching subsequence. The total possible combinations will be 2n. Hence, the recursive solution will take O(2n). The approach to writing the recursive solution has been discussed here. Given below is the recursive solution to the LCS problem:
C++
Java
Python3
C#
Javascript
// A Naive recursive implementation of LCS problem#include <bits/stdc++.h> int max(int a, int b); // Returns length of LCS for X[0..m-1], Y[0..n-1]int lcs(char* X, char* Y, int m, int n){ if (m == 0 || n == 0) return 0; if (X[m - 1] == Y[n - 1]) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));} // Utility function to get max of 2 integersint max(int a, int b){ return (a > b) ? a : b;} // Driver Codeint main(){ char X[] = "AGGTAB"; char Y[] = "GXTXAYB"; int m = strlen(X); int n = strlen(Y); printf("Length of LCS is %dn", lcs(X, Y, m, n)); return 0;}
// A Naive recursive implementation of LCS problemimport java.io.*;class GFG{ // Utility function to get max of 2 integers static int max(int a, int b) { return (a > b) ? a : b; } // Returns length of LCS for X[0..m-1], Y[0..n-1] static int lcs(String X, String Y, int m, int n) { if (m == 0 || n == 0) return 0; if (X.charAt(m - 1) == Y.charAt(n - 1)) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } // Driver Code public static void main(String[] args) { String X = "AGGTAB"; String Y = "GXTXAYB"; int m = X.length(); int n = Y.length(); System.out.print("Length of LCS is " + lcs(X, Y, m, n)); }} // This code is contributed by subhammahato348
# A Naive recursive implementation of LCS problem # Returns length of LCS for X[0..m-1], Y[0..n-1]def lcs(X, Y, m, n): if (m == 0 or n == 0): return 0; if (X[m - 1] == Y[n - 1]): return 1 + lcs(X, Y, m - 1, n - 1); else: return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); # Driver Codeif __name__=='__main__': X = "AGGTAB"; Y = "GXTXAYB"; m = len(X); n = len(Y); print("Length of LCS is {}n".format(lcs(X, Y, m, n))) # This code is contributed by rutvik_56.
// A Naive recursive implementation of LCS problemusing System;class GFG{ // Utility function to get max of 2 integers static int max(int a, int b) { return (a > b) ? a : b; } // Returns length of LCS for X[0..m-1], Y[0..n-1] static int lcs(string X, string Y, int m, int n) { if (m == 0 || n == 0) return 0; if (X[m - 1] == Y[n - 1]) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } // Driver Code public static void Main() { string X = "AGGTAB"; string Y = "GXTXAYB"; int m = X.Length; int n = Y.Length; Console.Write("Length of LCS is " + lcs(X, Y, m, n)); }} // This code is contributed by subhammahato348
<script>// A Naive recursive implementation of LCS problem // Utility function to get max of 2 integers function max(a,b) { return (a > b) ? a : b; } // Returns length of LCS for X[0..m-1], Y[0..n-1] function lcs(X,Y,m,n) { if (m == 0 || n == 0) return 0; if (X[m-1] == Y[n-1]) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } // Driver Code let X = "AGGTAB"; let Y = "GXTXAYB"; let m = X.length; let n = Y.length; document.write("Length of LCS is " + lcs(X, Y, m, n)); // This code is contributed by avanitrachhadiya2155</script>
Output:
Length of LCS is 4
Considering the above implementation, the following is a partial recursion tree for input strings “AXYT” and “AYZX”
lcs("AXYT", "AYZX")
/ \
lcs("AXY", "AYZX") lcs("AXYT", "AYZ")
/ \ / \
lcs("AX", "AYZX") lcs("AXY", "AYZ") lcs("AXY", "AYZ") lcs("AXYT", "AY")
In the above partial recursion tree, lcs(“AXY”, “AYZ”) is being solved twice. On drawing the complete recursion tree, it has been observed that there are many subproblems that are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation. The tabulation method has been discussed here. A common point of observation to use memoization in the recursive code will be the two non-constant arguments M and N in every function call. The function has 4 arguments, but 2 arguments are constant which does not affect the Memoization. The repetitive calls occur for N and M which have been called previously. So use a 2-D array to store the computed lcs(m, n) value at arr[m-1][n-1] as the string index starts from 0. Whenever the function with the same argument m and n are called again, we do not perform any further recursive call and return arr[m-1][n-1] as the previous computation of the lcs(m, n) has already been stored in arr[m-1][n-1], hence reducing the recursive calls that happen more than once. Below is the implementation of the Memoization approach of the recursive code.
C++
Java
Python3
C#
Javascript
// C++ program to memoize// recursive implementation of LCS problem#include <bits/stdc++.h>int arr[1000][1000];int max(int a, int b); // Returns length of LCS for X[0..m-1], Y[0..n-1] */// memoization applied in recursive solutionint lcs(char* X, char* Y, int m, int n){ // base case if (m == 0 || n == 0) return 0; // if the same state has already been // computed if (arr[m - 1][n - 1] != -1) return arr[m - 1][n - 1]; // if equal, then we store the value of the // function call if (X[m - 1] == Y[n - 1]) { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1); return arr[m - 1][n - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1][n - 1] = max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); return arr[m - 1][n - 1]; }} // Utility function to get max of 2 integersint max(int a, int b){ return (a > b) ? a : b;} // Driver Codeint main(){ memset(arr, -1, sizeof(arr)); char X[] = "AGGTAB"; char Y[] = "GXTXAYB"; int m = strlen(X); int n = strlen(Y); printf("Length of LCS is %d", lcs(X, Y, m, n)); return 0;}
// Java program to memoize// recursive implementation of LCS problemimport java.io.*;import java.lang.*;class GFG{ public static int arr[][] = new int[1000][1000]; // Returns length of LCS for X[0..m-1], Y[0..n-1] */ // memoization applied in recursive solution public static int lcs(String X, String Y, int m, int n) { // base case if (m == 0 || n == 0) return 0; // if the same state has already been // computed if (arr[m - 1][n - 1] != -1) return arr[m - 1][n - 1]; // if equal, then we store the value of the // function call if ( X.charAt(m - 1) == Y.charAt(n - 1)) { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1); return arr[m - 1][n - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1][n - 1] = max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); return arr[m - 1][n - 1]; } } // Utility function to get max of 2 integers public static int max(int a, int b) { return (a > b) ? a : b; } // Driver code public static void main (String[] args) { for(int i = 0; i < 1000; i++) { for(int j = 0; j < 1000; j++) { arr[i][j] = -1; } } String X = "AGGTAB"; String Y = "GXTXAYB"; int m = X.length(); int n = Y.length(); System.out.println("Length of LCS is " + lcs(X, Y, m, n)); }} // This code is contributed by manupathria.
# Python3 program to memoize# recursive implementation of LCS problem # Returns length of LCS for X[0..m-1], Y[0..n-1]# memoization applied in recursive solutiondef lcs(X, Y, m, n): global arr # base case if (m == 0 or n == 0): return 0 # if the same state has already been # computed if (arr[m - 1][n - 1] != -1): return arr[m - 1][n - 1] # if equal, then we store the value of the # function call if (X[m - 1] == Y[n - 1]): # store it in arr to avoid further repetitive # work in future function calls arr[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1) return arr[m - 1][n - 1] else: # store it in arr to avoid further repetitive # work in future function calls arr[m - 1][n - 1] = max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)) return arr[m - 1][n - 1] # Driver code arr = [[0]*1000]*1000 for i in range(0, 1000): for j in range(0, 1000): arr[i][j] = -1 X = "AGGTAB"Y = "GXTXAYB" m = len(X)n = len(Y) print("Length of LCS is ", lcs(X, Y, m, n)) # This code is contributed by Dharanendra L V.
// C# program to memoize// recursive implementation of LCS problemusing System;public class GFG{ public static int[, ] arr = new int[1000, 1000]; // Returns length of LCS for X[0..m-1], Y[0..n-1] */ // memoization applied in recursive solution public static int lcs(String X, String Y, int m, int n) { // base case if (m == 0 || n == 0) return 0; // if the same state has already been // computed if (arr[m - 1, n - 1] != -1) return arr[m - 1, n - 1]; // if equal, then we store the value of the // function call if ( X[m - 1] == Y[n - 1]) { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1, n - 1] = 1 + lcs(X, Y, m - 1, n - 1); return arr[m - 1, n - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1, n - 1] = max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); return arr[m - 1, n - 1]; } } // Utility function to get max of 2 integers public static int max(int a, int b) { return (a > b) ? a : b; } // Driver code static public void Main (){ for(int i = 0; i < 1000; i++) { for(int j = 0; j < 1000; j++) { arr[i, j] = -1; } } String X = "AGGTAB"; String Y = "GXTXAYB"; int m = X.Length; int n = Y.Length; Console.WriteLine("Length of LCS is " + lcs(X, Y, m, n)); }} // This code is contributed by Dharanendra L V.
<script>// Javascript program to memoize// recursive implementation of LCS problem let arr=new Array(1000); for(let i=0;i<1000;i++) { arr[i]=new Array(1000); for(let j=0;j<1000;j++) { arr[i][j]=-1; } } // Returns length of LCS for X[0..m-1], Y[0..n-1] */ // memoization applied in recursive solution function lcs(X,Y,m,n) { // base case if (m == 0 || n == 0) return 0; // if the same state has already been // computed if (arr[m - 1][n - 1] != -1) return arr[m - 1][n - 1]; // if equal, then we store the value of the // function call if ( X[m-1] == Y[n-1]) { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1); return arr[m - 1][n - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1][n - 1] = Math.max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); return arr[m - 1][n - 1]; } } // Driver code let X = "AGGTAB"; let Y = "GXTXAYB"; let m = X.length; let n = Y.length; document.write("Length of LCS is " + lcs(X, Y, m, n)); // This code is contributed by rag2127</script>
Length of LCS is 4
3-D Memoization
In the above program, the recursive function had only two arguments whose values were not constant after every function call. Below, an implementation where the recursive program has three non-constant arguments is done. For e.g., Program to solve the standard Dynamic Problem LCS problem for three strings. The general recursive solution of the problem is to generate all subsequences of both given sequences and find the longest matching subsequence. The total possible combinations will be 3n. Hence, a recursive solution will take O(3n). Given below is the recursive solution to the LCS problem:
C++
Java
Python3
C#
Javascript
// A recursive implementation of LCS problem// of three strings#include <bits/stdc++.h>int max(int a, int b); // Returns length of LCS for X[0..m-1], Y[0..n-1]int lcs(char* X, char* Y, char* Z, int m, int n, int o){ // base case if (m == 0 || n == 0 || o == 0) return 0; // if equal, then check for next combination if (X[m - 1] == Y[n - 1] and Y[n - 1] == Z[o - 1]) { // recursive call return 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); } else { // return the maximum of the three other // possible states in recursion return max(lcs(X, Y, Z, m, n - 1, o), max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); }} // Utility function to get max of 2 integersint max(int a, int b){ return (a > b) ? a : b;} // Driver Codeint main(){ char X[] = "geeks"; char Y[] = "geeksfor"; char Z[] = "geeksforge"; int m = strlen(X); int n = strlen(Y); int o = strlen(Z); printf("Length of LCS is %d", lcs(X, Y, Z, m, n, o)); return 0;}
// A recursive implementation of LCS problem// of three stringsclass GFG{ // Utility function to get max of 2 integers static int max(int a, int b) { return (a > b) ? a : b; } // Returns length of LCS for X[0..m-1], Y[0..n-1] static int lcs(char[] X, char[] Y, char[] Z, int m, int n, int o) { // base case if (m == 0 || n == 0 || o == 0) return 0; // if equal, then check for next combination if (X[m - 1] == Y[n - 1] && Y[n - 1] == Z[o - 1]) { // recursive call return 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); } else { // return the maximum of the three other // possible states in recursion return Math.max(lcs(X, Y, Z, m, n - 1, o), Math.max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); } } // Driver code public static void main(String[] args) { char[] X = "geeks".toCharArray(); char[] Y = "geeksfor".toCharArray(); char[] Z = "geeksforge".toCharArray(); int m = X.length; int n = Y.length; int o = Z.length; System.out.println("Length of LCS is " + lcs(X, Y, Z, m, n, o)); }} // This code is contributed by divyesh072019.
# A recursive implementation of LCS problem of three strings # Returns length of LCS for X[0..m-1], Y[0..n-1]def lcs(X, Y, Z, m, n, o): # base case if m == 0 or n == 0 or o == 0: return 5 # if equal, then check for next combination if X[m - 1] == Y[n - 1] and Y[n - 1] == Z[o - 1]: # recursive call return 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1) else: # return the maximum of the three other # possible states in recursion return max(lcs(X, Y, Z, m, n - 1, o), max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))) X = "geeks".split()Y = "geeksfor".split()Z = "geeksforge".split()m = len(X)n = len(Y)o = len(Z)print("Length of LCS is", lcs(X, Y, Z, m, n, o)) # This code is contributed by rameshtravel07.
// A recursive implementation of LCS problem// of three stringsusing System;class GFG { // Utility function to get max of 2 integers static int max(int a, int b) { return (a > b) ? a : b; } // Returns length of LCS for X[0..m-1], Y[0..n-1] static int lcs(char[] X, char[] Y, char[] Z, int m, int n, int o) { // base case if (m == 0 || n == 0 || o == 0) return 0; // if equal, then check for next combination if (X[m - 1] == Y[n - 1] && Y[n - 1] == Z[o - 1]) { // recursive call return 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); } else { // return the maximum of the three other // possible states in recursion return Math.Max(lcs(X, Y, Z, m, n - 1, o), Math.Max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); } } // Driver code static void Main() { char[] X = "geeks".ToCharArray(); char[] Y = "geeksfor".ToCharArray(); char[] Z = "geeksforge".ToCharArray(); int m = X.Length; int n = Y.Length; int o = Z.Length; Console.WriteLine("Length of LCS is " + lcs(X, Y, Z, m, n, o)); }} // This code is contributed by divyeshrabadiya07
<script> // A recursive implementation of LCS problem// of three strings // Returns length of LCS for X[0..m-1], Y[0..n-1] function lcs(X,Y,Z,m,n,o) { // base case if (m == 0 || n == 0 || o == 0) return 0; // if equal, then check for next combination if (X[m - 1] == Y[n - 1] && Y[n - 1] == Z[o - 1]) { // recursive call return 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); } else { // return the maximum of the three other // possible states in recursion return Math.max(lcs(X, Y, Z, m, n - 1, o), Math.max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); } } // Driver code let X = "geeks".split(""); let Y = "geeksfor".split(""); let Z = "geeksforge".split(""); let m = X.length; let n = Y.length; let o = Z.length; document.write( "Length of LCS is " + lcs(X, Y, Z, m, n, o) ); // This code is contributed by unknown2108 </script>
Length of LCS is 5
The tabulation method has been shown here. On drawing the recursion tree completely, it has been noticed that there are many overlapping sub-problems which are been calculated multiple times. Since the function parameter has three non-constant parameters, hence a 3-D array will be used to memorize the value that was returned when lcs(x, y, z, m, n, o) for any value of m, n, and o was called so that if lcs(x, y, z, m, n, o) is again called for the same value of m, n, and o then the function will return the already stored value as it has been computed previously in the recursive call. arr[m][n][o] stores the value returned by the lcs(x, y, z, m, n, o) function call. The only modification that needs to be done in the recursive program is to store the return value of (m, n, o) state of the recursive function. The rest remains the same in the above recursive program. Below is the implementation of the Memoization approach of the recursive code:
C++
Java
Python3
C#
Javascript
// A memoize recursive implementation of LCS problem#include <bits/stdc++.h>int arr[100][100][100];int max(int a, int b); // Returns length of LCS for X[0..m-1], Y[0..n-1] */// memoization applied in recursive solutionint lcs(char* X, char* Y, char* Z, int m, int n, int o){ // base case if (m == 0 || n == 0 || o == 0) return 0; // if the same state has already been // computed if (arr[m - 1][n - 1][o - 1] != -1) return arr[m - 1][n - 1][o - 1]; // if equal, then we store the value of the // function call if (X[m - 1] == Y[n - 1] and Y[n - 1] == Z[o - 1]) { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1][n - 1][o - 1] = 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); return arr[m - 1][n - 1][o - 1]; } else { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1][n - 1][o - 1] = max(lcs(X, Y, Z, m, n - 1, o), max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); return arr[m - 1][n - 1][o - 1]; }} // Utility function to get max of 2 integersint max(int a, int b){ return (a > b) ? a : b;} // Driver Codeint main(){ memset(arr, -1, sizeof(arr)); char X[] = "geeks"; char Y[] = "geeksfor"; char Z[] = "geeksforgeeks"; int m = strlen(X); int n = strlen(Y); int o = strlen(Z); printf("Length of LCS is %d", lcs(X, Y, Z, m, n, o)); return 0;}
// A memoize recursive implementation of LCS problemimport java.io.*;class GFG{ public static int[][][] arr = new int[100][100][100]; // Returns length of LCS for X[0..m-1], Y[0..n-1] */ // memoization applied in recursive solution static int lcs(String X, String Y, String Z, int m, int n, int o) { // base case if (m == 0 || n == 0 || o == 0) return 0; // if the same state has already been // computed if (arr[m - 1][n - 1][o - 1] != -1) return arr[m - 1][n - 1][o - 1]; // if equal, then we store the value of the // function call if (X.charAt(m - 1) == Y.charAt(n - 1) && Y.charAt(n - 1) == Z.charAt(o - 1)) { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1][n - 1][o - 1] = 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); return arr[m - 1][n - 1][o - 1]; } else { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1][n - 1][o - 1] = max(lcs(X, Y, Z, m, n - 1, o), max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); return arr[m - 1][n - 1][o - 1]; } } // Utility function to get max of 2 integers static int max(int a, int b) { return (a > b) ? a : b; } // Driver Code public static void main (String[] args) { for(int i = 0; i < 100; i++) { for(int j = 0; j < 100; j++) { for(int k = 0; k < 100; k++) { arr[i][j][k] = -1; } } } String X = "geeks"; String Y = "geeksfor"; String Z = "geeksforgeeks"; int m = X.length(); int n = Y.length(); int o = Z.length(); System.out.print("Length of LCS is " + lcs(X, Y, Z, m, n, o)); }} // This code is contributed by Dharanendra L V.
# A memoize recursive implementation of LCS problem # Returns length of LCS for X[0..m-1], Y[0..n-1] */# memoization applied in recursive solutiondef lcs(X, Y, Z, m, n, o): global arr # base case if(m == 0 or n == 0 or o == 0): return 0 # if the same state has already been # computed if (arr[m - 1][n - 1][o - 1] != -1): return arr[m - 1][n - 1][o - 1] # if equal, then we store the value of the # function call if (X[m - 1] == Y[n - 1] and Y[n - 1] == Z[o - 1]): # store it in arr to avoid further repetitive work # in future function calls arr[m - 1][n - 1][o - 1] = 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1) return arr[m - 1][n - 1][o - 1] else: # store it in arr to avoid further repetitive work # in future function calls arr[m - 1][n - 1][o - 1] = max(lcs(X, Y, Z, m, n - 1, o), max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))) return arr[m - 1][n - 1][o - 1] # Driver Codearr = [[[0 for k in range(100)] for j in range(100)] for i in range(100)] for i in range(100): for j in range(100): for k in range(100): arr[i][j][k] = -1 X = "geeks"Y = "geeksfor"Z = "geeksforgeeks"m = len(X)n = len(Y)o = len(Z)print("Length of LCS is ", lcs(X, Y, Z, m, n, o)) # This code is contributed by Dharanendra L V.
// A memoize recursive implementation of LCS problemusing System;public class GFG{ public static int[, , ] arr = new int[100, 100, 100]; // Returns length of LCS for X[0..m-1], Y[0..n-1] */ // memoization applied in recursive solution static int lcs(String X, String Y, String Z, int m, int n, int o) { // base case if (m == 0 || n == 0 || o == 0) return 0; // if the same state has already been // computed if (arr[m - 1, n - 1, o - 1] != -1) return arr[m - 1, n - 1, o - 1]; // if equal, then we store the value of the // function call if (X[m - 1] == Y[n - 1] && Y[n - 1] == Z[o - 1]) { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1, n - 1, o - 1] = 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); return arr[m - 1, n - 1, o - 1]; } else { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1, n - 1, o - 1] = max(lcs(X, Y, Z, m, n - 1, o), max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); return arr[m - 1, n - 1, o - 1]; } } // Utility function to get max of 2 integers static int max(int a, int b) { return (a > b) ? a : b; } // Driver Code static public void Main (){ for(int i = 0; i < 100; i++) { for(int j = 0; j < 100; j++) { for(int k = 0; k < 100; k++) { arr[i, j, k] = -1; } } } String X = "geeks"; String Y = "geeksfor"; String Z = "geeksforgeeks"; int m = X.Length; int n = Y.Length; int o = Z.Length; Console.WriteLine("Length of LCS is " + lcs(X, Y, Z, m, n, o)); }} // This code is contributed by Dharanendra L V.
<script>// A memoize recursive implementation of LCS problem let arr=new Array(100); for(let i=0;i<100;i++) { arr[i]=new Array(100); for(let j=0;j<100;j++) { arr[i][j]=new Array(100); for(let k=0;k<100;k++) { arr[i][j][k]=-1; } } } // Returns length of LCS for X[0..m-1], Y[0..n-1] */ // memoization applied in recursive solution function lcs(X,Y,Z,m,n,o) { // base case if (m == 0 || n == 0 || o == 0) return 0; // if the same state has already been // computed if (arr[m - 1][n - 1][o - 1] != -1) return arr[m - 1][n - 1][o - 1]; // if equal, then we store the value of the // function call if (X[m-1] == Y[n-1] && Y[n-1] == Z[o-1]) { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1][n - 1][o - 1] = 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); return arr[m - 1][n - 1][o - 1]; } else { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1][n - 1][o - 1] = max(lcs(X, Y, Z, m, n - 1, o), max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); return arr[m - 1][n - 1][o - 1]; } } // Utility function to get max of 2 integers function max(a,b) { return (a > b) ? a : b; } // Driver Code let X = "geeks"; let Y = "geeksfor"; let Z = "geeksforgeeks"; let m = X.length; let n = Y.length; let o = Z.length; document.write("Length of LCS is " + lcs(X, Y, Z, m, n, o)); // This code is contributed by patel2127</script>
Length of LCS is 5
Note: The array used to Memoize is initialized to some value (say -1) before the function call to mark if the function with the same parameters has been previously called or not.
jit_t
Shivi_Aggarwal
ukasp
vvkbisht
rohitsingh07052
subhammahato348
divyeshrabadiya07
divyesh072019
rutvik_56
manupathria
dharanendralv23
mukesh07
avanitrachhadiya2155
rag2127
unknown2108
patel2127
akshaysingh98088
rameshtravel07
Fibonacci
LCS
Dynamic Programming
Recursion
Dynamic Programming
Recursion
Fibonacci
LCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Subset Sum Problem | DP-25
Coin Change | DP-7
Matrix Chain Multiplication | DP-8
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction | [
{
"code": null,
"e": 26507,
"s": 26479,
"text": "\n08 Nov, 2021"
},
{
"code": null,
"e": 26574,
"s": 26507,
"text": "Most of the Dynamic Programming problems are solved in two ways: "
},
{
"code": null,
"e": 26617,
"s": 26574,
"text": "Tabulation: Bottom UpMemoization: Top Down"
},
{
"code": null,
"e": 26639,
"s": 26617,
"text": "Tabulation: Bottom Up"
},
{
"code": null,
"e": 26661,
"s": 26639,
"text": "Memoization: Top Down"
},
{
"code": null,
"e": 26944,
"s": 26661,
"text": "One of the easier approaches to solve most of the problems in DP is to write the recursive code at first and then write the Bottom-up Tabulation Method or Top-down Memoization of the recursive function. The steps to write the DP solution of Top-down approach to any problem is to: "
},
{
"code": null,
"e": 27031,
"s": 26944,
"text": "Write the recursive codeMemoize the return value and use it to reduce recursive calls."
},
{
"code": null,
"e": 27056,
"s": 27031,
"text": "Write the recursive code"
},
{
"code": null,
"e": 27119,
"s": 27056,
"text": "Memoize the return value and use it to reduce recursive calls."
},
{
"code": null,
"e": 27569,
"s": 27119,
"text": "1-D MemoizationThe first step will be to write the recursive code. In the program below, a program related to recursion where only one parameter changes its value has been shown. Since only one parameter is non-constant, this method is known as 1-D memoization. E.g., the Fibonacci series problem to find the N-th term in the Fibonacci series. The recursive approach has been discussed here.Given below is the recursive code to find the N-th term: "
},
{
"code": null,
"e": 27573,
"s": 27569,
"text": "C++"
},
{
"code": null,
"e": 27578,
"s": 27573,
"text": "Java"
},
{
"code": null,
"e": 27586,
"s": 27578,
"text": "Python3"
},
{
"code": null,
"e": 27589,
"s": 27586,
"text": "C#"
},
{
"code": null,
"e": 27600,
"s": 27589,
"text": "Javascript"
},
{
"code": null,
"e": 27604,
"s": 27600,
"text": "PHP"
},
{
"code": "// C++ program to find the Nth term// of Fibonacci series#include <bits/stdc++.h>using namespace std; // Fibonacci Series using Recursionint fib(int n){ // Base case if (n <= 1) return n; // recursive calls return fib(n - 1) + fib(n - 2);} // Driver Codeint main(){ int n = 6; printf(\"%d\", fib(n)); return 0;}",
"e": 27944,
"s": 27604,
"text": null
},
{
"code": "// Java program to find the// Nth term of Fibonacci seriesimport java.io.*; class GFG{ // Fibonacci Series// using Recursionstatic int fib(int n){ // Base case if (n <= 1) return n; // recursive calls return fib(n - 1) + fib(n - 2);} // Driver Codepublic static void main (String[] args){ int n = 6; System.out.println(fib(n));}} // This code is contributed// by ajit",
"e": 28353,
"s": 27944,
"text": null
},
{
"code": "# Python3 program to find the Nth term# of Fibonacci series # Fibonacci Series using Recursiondef fib(n): # Base case if (n <= 1): return n # recursive calls return fib(n - 1) + fib(n - 2) # Driver Codeif __name__=='__main__': n = 6 print (fib(n)) # This code is contributed by# Shivi_Aggarwal",
"e": 28676,
"s": 28353,
"text": null
},
{
"code": "// C# program to find// the Nth term of// Fibonacci seriesusing System; class GFG{ // Fibonacci Series// using Recursionstatic int fib(int n){ // Base case if (n <= 1) return n; // recursive calls return fib(n - 1) + fib(n - 2);}// Driver Codestatic public void Main (){ int n = 6; Console.WriteLine(fib(n));}} // This code is contributed// by akt_mit",
"e": 29068,
"s": 28676,
"text": null
},
{
"code": "<script>// Javascript program to find the Nth term// of Fibonacci series // Fibonacci Series using Recursionfunction fib(n){ // Base case if (n <= 1) return n; // recursive calls return fib(n - 1) + fib(n - 2);} // Driver Codelet n = 6;document.write(fib(n)); // This code is contributed by subhammahato348.</script>",
"e": 29406,
"s": 29068,
"text": null
},
{
"code": "<?php// PHP program to find// the Nth term of// Fibonacci series// using Recursion function fib($n){ // Base case if ($n <= 1) return $n; // recursive calls return fib($n - 1) + fib($n - 2);} // Driver Code$n = 6;echo fib($n); // This code is contributed// by ajit?>",
"e": 29704,
"s": 29406,
"text": null
},
{
"code": null,
"e": 29706,
"s": 29704,
"text": "8"
},
{
"code": null,
"e": 29905,
"s": 29708,
"text": "A common observation is that this implementation does a lot of repeated work (see the following recursion tree). So this will consume a lot of time for finding the N-th Fibonacci number if done. "
},
{
"code": null,
"e": 30340,
"s": 29905,
"text": " fib(5) \n / \\ \n fib(4) fib(3) \n / \\ / \\\n fib(3) fib(2) fib(2) fib(1)\n / \\ / \\ / \\ \n fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)\n / \\ \nfib(1) fib(0) \n\nIn the above tree fib(3), fib(2), fib(1), fib(0) all are called more then once."
},
{
"code": null,
"e": 31147,
"s": 30340,
"text": "The following problem has been solved using the Tabulation method. In the program below, the steps to write a Top-Down approach program have been explained. Some modifications in the recursive program will reduce the complexity of the program and give the desired result. If fib(x) has not occurred previously, then we store the value of fib(x) in an array term at index x and return term[x]. By memoizing the return value of fib(x) at index x of an array, reduce the number of recursive calls at the next step when fib(x) has already been called. So without doing further recursive calls to compute the value of fib(x), return term[x] when fib(x) has already been computed previously to avoid a lot of repeated work as shown in the tree. Given below is the memoized recursive code to find the N-th term. "
},
{
"code": null,
"e": 31151,
"s": 31147,
"text": "C++"
},
{
"code": null,
"e": 31156,
"s": 31151,
"text": "Java"
},
{
"code": null,
"e": 31164,
"s": 31156,
"text": "Python3"
},
{
"code": null,
"e": 31167,
"s": 31164,
"text": "C#"
},
{
"code": null,
"e": 31178,
"s": 31167,
"text": "Javascript"
},
{
"code": "// CPP program to find the Nth term// of Fibonacci series#include <bits/stdc++.h>using namespace std;int term[1000];// Fibonacci Series using memoized Recursionint fib(int n){ // base case if (n <= 1) return n; // if fib(n) has already been computed // we do not do further recursive calls // and hence reduce the number of repeated // work if (term[n] != 0) return term[n]; else { // store the computed value of fib(n) // in an array term at index n to // so that it does not needs to be // precomputed again term[n] = fib(n - 1) + fib(n - 2); return term[n]; }} // Driver Codeint main(){ int n = 6; printf(\"%d\", fib(n)); return 0;}",
"e": 31908,
"s": 31178,
"text": null
},
{
"code": "// Java program to find// the Nth term of// Fibonacci seriesimport java.io.*; class GFG{ static int []term = new int [1000];// Fibonacci Series using// memoized Recursionstatic int fib(int n){ // base case if (n <= 1) return n; // if fib(n) has already // been computed we do not // do further recursive // calls and hence reduce // the number of repeated // work if (term[n] != 0) return term[n]; else { // store the computed value // of fib(n) in an array // term at index n to so that // it does not needs to be // precomputed again term[n] = fib(n - 1) + fib(n - 2); return term[n]; }} // Driver Codepublic static void main (String[] args){ int n = 6; System.out.println(fib(n));}} // This code is contributed by ajit",
"e": 32757,
"s": 31908,
"text": null
},
{
"code": "# Python program to find the Nth term# of Fibonacci seriesterm = [0 for i in range(1000)] # Fibonacci Series using memoized Recursiondef fib(n): # base case if n <= 1: return n # if fib(n) has already been computed # we do not do further recursive calls # and hence reduce the number of repeated # work if term[n] != 0: return term[n] else: # store the computed value of fib(n) # in an array term at index n to # so that it does not needs to be # precomputed again term[n] = fib(n - 1) + fib(n - 2) return term[n] # Driver Coden = 6print(fib(n)) # This code is contributed by rohitsingh07052",
"e": 33391,
"s": 32757,
"text": null
},
{
"code": "// C# program to find// the Nth term of// Fibonacci series using System;class GFG{ // Fibonacci Series using// memoized Recursionstatic int fib(int n){ int[] term = new int [1000]; // base case if (n <= 1) return n; // if fib(n) has already // been computed we do not // do further recursive // calls and hence reduce // the number of repeated // work if (term[n] != 0) return term[n]; else { // store the computed value // of fib(n) in an array // term at index n to so that // it does not needs to be // precomputed again term[n] = fib(n - 1) + fib(n - 2); return term[n]; }} // Driver Codepublic static void Main (){ int n = 6; Console.Write(fib(n));}}",
"e": 34192,
"s": 33391,
"text": null
},
{
"code": "<script> // Javascript program to find // the Nth term of // Fibonacci series // Fibonacci Series using // memoized Recursion function fib(n) { let term = new Array(1000); term.fill(0); // base case if (n <= 1) return n; // if fib(n) has already // been computed we do not // do further recursive // calls and hence reduce // the number of repeated // work if (term[n] != 0) return term[n]; else { // store the computed value // of fib(n) in an array // term at index n to so that // it does not needs to be // precomputed again term[n] = fib(n - 1) + fib(n - 2); return term[n]; } } let n = 6; document.write(fib(n)); // This code is contributed by mukesh07.</script>",
"e": 35128,
"s": 34192,
"text": null
},
{
"code": null,
"e": 35130,
"s": 35128,
"text": "8"
},
{
"code": null,
"e": 35340,
"s": 35132,
"text": "If the recursive code has been written once, then memoization is just modifying the recursive program and storing the return values to avoid repetitive calls of functions that have been computed previously. "
},
{
"code": null,
"e": 36041,
"s": 35340,
"text": "2-D MemoizationIn the above program, the recursive function had only one argument whose value was not constant after every function call. Below, an implementation where the recursive program has two non-constant arguments has been shown. For e.g., Program to solve the standard Dynamic Problem LCS problem when two strings are given. The general recursive solution of the problem is to generate all subsequences of both given sequences and find the longest matching subsequence. The total possible combinations will be 2n. Hence, the recursive solution will take O(2n). The approach to writing the recursive solution has been discussed here. Given below is the recursive solution to the LCS problem: "
},
{
"code": null,
"e": 36045,
"s": 36041,
"text": "C++"
},
{
"code": null,
"e": 36050,
"s": 36045,
"text": "Java"
},
{
"code": null,
"e": 36058,
"s": 36050,
"text": "Python3"
},
{
"code": null,
"e": 36061,
"s": 36058,
"text": "C#"
},
{
"code": null,
"e": 36072,
"s": 36061,
"text": "Javascript"
},
{
"code": "// A Naive recursive implementation of LCS problem#include <bits/stdc++.h> int max(int a, int b); // Returns length of LCS for X[0..m-1], Y[0..n-1]int lcs(char* X, char* Y, int m, int n){ if (m == 0 || n == 0) return 0; if (X[m - 1] == Y[n - 1]) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));} // Utility function to get max of 2 integersint max(int a, int b){ return (a > b) ? a : b;} // Driver Codeint main(){ char X[] = \"AGGTAB\"; char Y[] = \"GXTXAYB\"; int m = strlen(X); int n = strlen(Y); printf(\"Length of LCS is %dn\", lcs(X, Y, m, n)); return 0;}",
"e": 36744,
"s": 36072,
"text": null
},
{
"code": "// A Naive recursive implementation of LCS problemimport java.io.*;class GFG{ // Utility function to get max of 2 integers static int max(int a, int b) { return (a > b) ? a : b; } // Returns length of LCS for X[0..m-1], Y[0..n-1] static int lcs(String X, String Y, int m, int n) { if (m == 0 || n == 0) return 0; if (X.charAt(m - 1) == Y.charAt(n - 1)) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } // Driver Code public static void main(String[] args) { String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; int m = X.length(); int n = Y.length(); System.out.print(\"Length of LCS is \" + lcs(X, Y, m, n)); }} // This code is contributed by subhammahato348",
"e": 37610,
"s": 36744,
"text": null
},
{
"code": "# A Naive recursive implementation of LCS problem # Returns length of LCS for X[0..m-1], Y[0..n-1]def lcs(X, Y, m, n): if (m == 0 or n == 0): return 0; if (X[m - 1] == Y[n - 1]): return 1 + lcs(X, Y, m - 1, n - 1); else: return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); # Driver Codeif __name__=='__main__': X = \"AGGTAB\"; Y = \"GXTXAYB\"; m = len(X); n = len(Y); print(\"Length of LCS is {}n\".format(lcs(X, Y, m, n))) # This code is contributed by rutvik_56.",
"e": 38133,
"s": 37610,
"text": null
},
{
"code": "// A Naive recursive implementation of LCS problemusing System;class GFG{ // Utility function to get max of 2 integers static int max(int a, int b) { return (a > b) ? a : b; } // Returns length of LCS for X[0..m-1], Y[0..n-1] static int lcs(string X, string Y, int m, int n) { if (m == 0 || n == 0) return 0; if (X[m - 1] == Y[n - 1]) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } // Driver Code public static void Main() { string X = \"AGGTAB\"; string Y = \"GXTXAYB\"; int m = X.Length; int n = Y.Length; Console.Write(\"Length of LCS is \" + lcs(X, Y, m, n)); }} // This code is contributed by subhammahato348",
"e": 38878,
"s": 38133,
"text": null
},
{
"code": "<script>// A Naive recursive implementation of LCS problem // Utility function to get max of 2 integers function max(a,b) { return (a > b) ? a : b; } // Returns length of LCS for X[0..m-1], Y[0..n-1] function lcs(X,Y,m,n) { if (m == 0 || n == 0) return 0; if (X[m-1] == Y[n-1]) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } // Driver Code let X = \"AGGTAB\"; let Y = \"GXTXAYB\"; let m = X.length; let n = Y.length; document.write(\"Length of LCS is \" + lcs(X, Y, m, n)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 39628,
"s": 38878,
"text": null
},
{
"code": null,
"e": 39636,
"s": 39628,
"text": "Output:"
},
{
"code": null,
"e": 39655,
"s": 39636,
"text": "Length of LCS is 4"
},
{
"code": null,
"e": 39773,
"s": 39655,
"text": "Considering the above implementation, the following is a partial recursion tree for input strings “AXYT” and “AYZX” "
},
{
"code": null,
"e": 40045,
"s": 39773,
"text": " lcs(\"AXYT\", \"AYZX\")\n / \\\n lcs(\"AXY\", \"AYZX\") lcs(\"AXYT\", \"AYZ\")\n / \\ / \\\nlcs(\"AX\", \"AYZX\") lcs(\"AXY\", \"AYZ\") lcs(\"AXY\", \"AYZ\") lcs(\"AXYT\", \"AY\")"
},
{
"code": null,
"e": 41241,
"s": 40045,
"text": "In the above partial recursion tree, lcs(“AXY”, “AYZ”) is being solved twice. On drawing the complete recursion tree, it has been observed that there are many subproblems that are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation. The tabulation method has been discussed here. A common point of observation to use memoization in the recursive code will be the two non-constant arguments M and N in every function call. The function has 4 arguments, but 2 arguments are constant which does not affect the Memoization. The repetitive calls occur for N and M which have been called previously. So use a 2-D array to store the computed lcs(m, n) value at arr[m-1][n-1] as the string index starts from 0. Whenever the function with the same argument m and n are called again, we do not perform any further recursive call and return arr[m-1][n-1] as the previous computation of the lcs(m, n) has already been stored in arr[m-1][n-1], hence reducing the recursive calls that happen more than once. Below is the implementation of the Memoization approach of the recursive code. "
},
{
"code": null,
"e": 41245,
"s": 41241,
"text": "C++"
},
{
"code": null,
"e": 41250,
"s": 41245,
"text": "Java"
},
{
"code": null,
"e": 41258,
"s": 41250,
"text": "Python3"
},
{
"code": null,
"e": 41261,
"s": 41258,
"text": "C#"
},
{
"code": null,
"e": 41272,
"s": 41261,
"text": "Javascript"
},
{
"code": "// C++ program to memoize// recursive implementation of LCS problem#include <bits/stdc++.h>int arr[1000][1000];int max(int a, int b); // Returns length of LCS for X[0..m-1], Y[0..n-1] */// memoization applied in recursive solutionint lcs(char* X, char* Y, int m, int n){ // base case if (m == 0 || n == 0) return 0; // if the same state has already been // computed if (arr[m - 1][n - 1] != -1) return arr[m - 1][n - 1]; // if equal, then we store the value of the // function call if (X[m - 1] == Y[n - 1]) { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1); return arr[m - 1][n - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1][n - 1] = max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); return arr[m - 1][n - 1]; }} // Utility function to get max of 2 integersint max(int a, int b){ return (a > b) ? a : b;} // Driver Codeint main(){ memset(arr, -1, sizeof(arr)); char X[] = \"AGGTAB\"; char Y[] = \"GXTXAYB\"; int m = strlen(X); int n = strlen(Y); printf(\"Length of LCS is %d\", lcs(X, Y, m, n)); return 0;}",
"e": 42574,
"s": 41272,
"text": null
},
{
"code": "// Java program to memoize// recursive implementation of LCS problemimport java.io.*;import java.lang.*;class GFG{ public static int arr[][] = new int[1000][1000]; // Returns length of LCS for X[0..m-1], Y[0..n-1] */ // memoization applied in recursive solution public static int lcs(String X, String Y, int m, int n) { // base case if (m == 0 || n == 0) return 0; // if the same state has already been // computed if (arr[m - 1][n - 1] != -1) return arr[m - 1][n - 1]; // if equal, then we store the value of the // function call if ( X.charAt(m - 1) == Y.charAt(n - 1)) { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1); return arr[m - 1][n - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1][n - 1] = max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); return arr[m - 1][n - 1]; } } // Utility function to get max of 2 integers public static int max(int a, int b) { return (a > b) ? a : b; } // Driver code public static void main (String[] args) { for(int i = 0; i < 1000; i++) { for(int j = 0; j < 1000; j++) { arr[i][j] = -1; } } String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; int m = X.length(); int n = Y.length(); System.out.println(\"Length of LCS is \" + lcs(X, Y, m, n)); }} // This code is contributed by manupathria.",
"e": 44119,
"s": 42574,
"text": null
},
{
"code": "# Python3 program to memoize# recursive implementation of LCS problem # Returns length of LCS for X[0..m-1], Y[0..n-1]# memoization applied in recursive solutiondef lcs(X, Y, m, n): global arr # base case if (m == 0 or n == 0): return 0 # if the same state has already been # computed if (arr[m - 1][n - 1] != -1): return arr[m - 1][n - 1] # if equal, then we store the value of the # function call if (X[m - 1] == Y[n - 1]): # store it in arr to avoid further repetitive # work in future function calls arr[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1) return arr[m - 1][n - 1] else: # store it in arr to avoid further repetitive # work in future function calls arr[m - 1][n - 1] = max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)) return arr[m - 1][n - 1] # Driver code arr = [[0]*1000]*1000 for i in range(0, 1000): for j in range(0, 1000): arr[i][j] = -1 X = \"AGGTAB\"Y = \"GXTXAYB\" m = len(X)n = len(Y) print(\"Length of LCS is \", lcs(X, Y, m, n)) # This code is contributed by Dharanendra L V.",
"e": 45259,
"s": 44119,
"text": null
},
{
"code": "// C# program to memoize// recursive implementation of LCS problemusing System;public class GFG{ public static int[, ] arr = new int[1000, 1000]; // Returns length of LCS for X[0..m-1], Y[0..n-1] */ // memoization applied in recursive solution public static int lcs(String X, String Y, int m, int n) { // base case if (m == 0 || n == 0) return 0; // if the same state has already been // computed if (arr[m - 1, n - 1] != -1) return arr[m - 1, n - 1]; // if equal, then we store the value of the // function call if ( X[m - 1] == Y[n - 1]) { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1, n - 1] = 1 + lcs(X, Y, m - 1, n - 1); return arr[m - 1, n - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1, n - 1] = max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); return arr[m - 1, n - 1]; } } // Utility function to get max of 2 integers public static int max(int a, int b) { return (a > b) ? a : b; } // Driver code static public void Main (){ for(int i = 0; i < 1000; i++) { for(int j = 0; j < 1000; j++) { arr[i, j] = -1; } } String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; int m = X.Length; int n = Y.Length; Console.WriteLine(\"Length of LCS is \" + lcs(X, Y, m, n)); }} // This code is contributed by Dharanendra L V.",
"e": 46758,
"s": 45259,
"text": null
},
{
"code": "<script>// Javascript program to memoize// recursive implementation of LCS problem let arr=new Array(1000); for(let i=0;i<1000;i++) { arr[i]=new Array(1000); for(let j=0;j<1000;j++) { arr[i][j]=-1; } } // Returns length of LCS for X[0..m-1], Y[0..n-1] */ // memoization applied in recursive solution function lcs(X,Y,m,n) { // base case if (m == 0 || n == 0) return 0; // if the same state has already been // computed if (arr[m - 1][n - 1] != -1) return arr[m - 1][n - 1]; // if equal, then we store the value of the // function call if ( X[m-1] == Y[n-1]) { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1); return arr[m - 1][n - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls arr[m - 1][n - 1] = Math.max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); return arr[m - 1][n - 1]; } } // Driver code let X = \"AGGTAB\"; let Y = \"GXTXAYB\"; let m = X.length; let n = Y.length; document.write(\"Length of LCS is \" + lcs(X, Y, m, n)); // This code is contributed by rag2127</script>",
"e": 48104,
"s": 46758,
"text": null
},
{
"code": null,
"e": 48123,
"s": 48104,
"text": "Length of LCS is 4"
},
{
"code": null,
"e": 48141,
"s": 48125,
"text": "3-D Memoization"
},
{
"code": null,
"e": 48743,
"s": 48141,
"text": "In the above program, the recursive function had only two arguments whose values were not constant after every function call. Below, an implementation where the recursive program has three non-constant arguments is done. For e.g., Program to solve the standard Dynamic Problem LCS problem for three strings. The general recursive solution of the problem is to generate all subsequences of both given sequences and find the longest matching subsequence. The total possible combinations will be 3n. Hence, a recursive solution will take O(3n). Given below is the recursive solution to the LCS problem: "
},
{
"code": null,
"e": 48747,
"s": 48743,
"text": "C++"
},
{
"code": null,
"e": 48752,
"s": 48747,
"text": "Java"
},
{
"code": null,
"e": 48760,
"s": 48752,
"text": "Python3"
},
{
"code": null,
"e": 48763,
"s": 48760,
"text": "C#"
},
{
"code": null,
"e": 48774,
"s": 48763,
"text": "Javascript"
},
{
"code": "// A recursive implementation of LCS problem// of three strings#include <bits/stdc++.h>int max(int a, int b); // Returns length of LCS for X[0..m-1], Y[0..n-1]int lcs(char* X, char* Y, char* Z, int m, int n, int o){ // base case if (m == 0 || n == 0 || o == 0) return 0; // if equal, then check for next combination if (X[m - 1] == Y[n - 1] and Y[n - 1] == Z[o - 1]) { // recursive call return 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); } else { // return the maximum of the three other // possible states in recursion return max(lcs(X, Y, Z, m, n - 1, o), max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); }} // Utility function to get max of 2 integersint max(int a, int b){ return (a > b) ? a : b;} // Driver Codeint main(){ char X[] = \"geeks\"; char Y[] = \"geeksfor\"; char Z[] = \"geeksforge\"; int m = strlen(X); int n = strlen(Y); int o = strlen(Z); printf(\"Length of LCS is %d\", lcs(X, Y, Z, m, n, o)); return 0;}",
"e": 49833,
"s": 48774,
"text": null
},
{
"code": "// A recursive implementation of LCS problem// of three stringsclass GFG{ // Utility function to get max of 2 integers static int max(int a, int b) { return (a > b) ? a : b; } // Returns length of LCS for X[0..m-1], Y[0..n-1] static int lcs(char[] X, char[] Y, char[] Z, int m, int n, int o) { // base case if (m == 0 || n == 0 || o == 0) return 0; // if equal, then check for next combination if (X[m - 1] == Y[n - 1] && Y[n - 1] == Z[o - 1]) { // recursive call return 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); } else { // return the maximum of the three other // possible states in recursion return Math.max(lcs(X, Y, Z, m, n - 1, o), Math.max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); } } // Driver code public static void main(String[] args) { char[] X = \"geeks\".toCharArray(); char[] Y = \"geeksfor\".toCharArray(); char[] Z = \"geeksforge\".toCharArray(); int m = X.length; int n = Y.length; int o = Z.length; System.out.println(\"Length of LCS is \" + lcs(X, Y, Z, m, n, o)); }} // This code is contributed by divyesh072019.",
"e": 51037,
"s": 49833,
"text": null
},
{
"code": "# A recursive implementation of LCS problem of three strings # Returns length of LCS for X[0..m-1], Y[0..n-1]def lcs(X, Y, Z, m, n, o): # base case if m == 0 or n == 0 or o == 0: return 5 # if equal, then check for next combination if X[m - 1] == Y[n - 1] and Y[n - 1] == Z[o - 1]: # recursive call return 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1) else: # return the maximum of the three other # possible states in recursion return max(lcs(X, Y, Z, m, n - 1, o), max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))) X = \"geeks\".split()Y = \"geeksfor\".split()Z = \"geeksforge\".split()m = len(X)n = len(Y)o = len(Z)print(\"Length of LCS is\", lcs(X, Y, Z, m, n, o)) # This code is contributed by rameshtravel07.",
"e": 51795,
"s": 51037,
"text": null
},
{
"code": "// A recursive implementation of LCS problem// of three stringsusing System;class GFG { // Utility function to get max of 2 integers static int max(int a, int b) { return (a > b) ? a : b; } // Returns length of LCS for X[0..m-1], Y[0..n-1] static int lcs(char[] X, char[] Y, char[] Z, int m, int n, int o) { // base case if (m == 0 || n == 0 || o == 0) return 0; // if equal, then check for next combination if (X[m - 1] == Y[n - 1] && Y[n - 1] == Z[o - 1]) { // recursive call return 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); } else { // return the maximum of the three other // possible states in recursion return Math.Max(lcs(X, Y, Z, m, n - 1, o), Math.Max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); } } // Driver code static void Main() { char[] X = \"geeks\".ToCharArray(); char[] Y = \"geeksfor\".ToCharArray(); char[] Z = \"geeksforge\".ToCharArray(); int m = X.Length; int n = Y.Length; int o = Z.Length; Console.WriteLine(\"Length of LCS is \" + lcs(X, Y, Z, m, n, o)); }} // This code is contributed by divyeshrabadiya07",
"e": 53094,
"s": 51795,
"text": null
},
{
"code": "<script> // A recursive implementation of LCS problem// of three strings // Returns length of LCS for X[0..m-1], Y[0..n-1] function lcs(X,Y,Z,m,n,o) { // base case if (m == 0 || n == 0 || o == 0) return 0; // if equal, then check for next combination if (X[m - 1] == Y[n - 1] && Y[n - 1] == Z[o - 1]) { // recursive call return 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); } else { // return the maximum of the three other // possible states in recursion return Math.max(lcs(X, Y, Z, m, n - 1, o), Math.max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); } } // Driver code let X = \"geeks\".split(\"\"); let Y = \"geeksfor\".split(\"\"); let Z = \"geeksforge\".split(\"\"); let m = X.length; let n = Y.length; let o = Z.length; document.write( \"Length of LCS is \" + lcs(X, Y, Z, m, n, o) ); // This code is contributed by unknown2108 </script>",
"e": 54104,
"s": 53094,
"text": null
},
{
"code": null,
"e": 54123,
"s": 54104,
"text": "Length of LCS is 5"
},
{
"code": null,
"e": 55081,
"s": 54125,
"text": "The tabulation method has been shown here. On drawing the recursion tree completely, it has been noticed that there are many overlapping sub-problems which are been calculated multiple times. Since the function parameter has three non-constant parameters, hence a 3-D array will be used to memorize the value that was returned when lcs(x, y, z, m, n, o) for any value of m, n, and o was called so that if lcs(x, y, z, m, n, o) is again called for the same value of m, n, and o then the function will return the already stored value as it has been computed previously in the recursive call. arr[m][n][o] stores the value returned by the lcs(x, y, z, m, n, o) function call. The only modification that needs to be done in the recursive program is to store the return value of (m, n, o) state of the recursive function. The rest remains the same in the above recursive program. Below is the implementation of the Memoization approach of the recursive code: "
},
{
"code": null,
"e": 55085,
"s": 55081,
"text": "C++"
},
{
"code": null,
"e": 55090,
"s": 55085,
"text": "Java"
},
{
"code": null,
"e": 55098,
"s": 55090,
"text": "Python3"
},
{
"code": null,
"e": 55101,
"s": 55098,
"text": "C#"
},
{
"code": null,
"e": 55112,
"s": 55101,
"text": "Javascript"
},
{
"code": "// A memoize recursive implementation of LCS problem#include <bits/stdc++.h>int arr[100][100][100];int max(int a, int b); // Returns length of LCS for X[0..m-1], Y[0..n-1] */// memoization applied in recursive solutionint lcs(char* X, char* Y, char* Z, int m, int n, int o){ // base case if (m == 0 || n == 0 || o == 0) return 0; // if the same state has already been // computed if (arr[m - 1][n - 1][o - 1] != -1) return arr[m - 1][n - 1][o - 1]; // if equal, then we store the value of the // function call if (X[m - 1] == Y[n - 1] and Y[n - 1] == Z[o - 1]) { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1][n - 1][o - 1] = 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); return arr[m - 1][n - 1][o - 1]; } else { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1][n - 1][o - 1] = max(lcs(X, Y, Z, m, n - 1, o), max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); return arr[m - 1][n - 1][o - 1]; }} // Utility function to get max of 2 integersint max(int a, int b){ return (a > b) ? a : b;} // Driver Codeint main(){ memset(arr, -1, sizeof(arr)); char X[] = \"geeks\"; char Y[] = \"geeksfor\"; char Z[] = \"geeksforgeeks\"; int m = strlen(X); int n = strlen(Y); int o = strlen(Z); printf(\"Length of LCS is %d\", lcs(X, Y, Z, m, n, o)); return 0;}",
"e": 56716,
"s": 55112,
"text": null
},
{
"code": "// A memoize recursive implementation of LCS problemimport java.io.*;class GFG{ public static int[][][] arr = new int[100][100][100]; // Returns length of LCS for X[0..m-1], Y[0..n-1] */ // memoization applied in recursive solution static int lcs(String X, String Y, String Z, int m, int n, int o) { // base case if (m == 0 || n == 0 || o == 0) return 0; // if the same state has already been // computed if (arr[m - 1][n - 1][o - 1] != -1) return arr[m - 1][n - 1][o - 1]; // if equal, then we store the value of the // function call if (X.charAt(m - 1) == Y.charAt(n - 1) && Y.charAt(n - 1) == Z.charAt(o - 1)) { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1][n - 1][o - 1] = 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); return arr[m - 1][n - 1][o - 1]; } else { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1][n - 1][o - 1] = max(lcs(X, Y, Z, m, n - 1, o), max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); return arr[m - 1][n - 1][o - 1]; } } // Utility function to get max of 2 integers static int max(int a, int b) { return (a > b) ? a : b; } // Driver Code public static void main (String[] args) { for(int i = 0; i < 100; i++) { for(int j = 0; j < 100; j++) { for(int k = 0; k < 100; k++) { arr[i][j][k] = -1; } } } String X = \"geeks\"; String Y = \"geeksfor\"; String Z = \"geeksforgeeks\"; int m = X.length(); int n = Y.length(); int o = Z.length(); System.out.print(\"Length of LCS is \" + lcs(X, Y, Z, m, n, o)); }} // This code is contributed by Dharanendra L V.",
"e": 58714,
"s": 56716,
"text": null
},
{
"code": "# A memoize recursive implementation of LCS problem # Returns length of LCS for X[0..m-1], Y[0..n-1] */# memoization applied in recursive solutiondef lcs(X, Y, Z, m, n, o): global arr # base case if(m == 0 or n == 0 or o == 0): return 0 # if the same state has already been # computed if (arr[m - 1][n - 1][o - 1] != -1): return arr[m - 1][n - 1][o - 1] # if equal, then we store the value of the # function call if (X[m - 1] == Y[n - 1] and Y[n - 1] == Z[o - 1]): # store it in arr to avoid further repetitive work # in future function calls arr[m - 1][n - 1][o - 1] = 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1) return arr[m - 1][n - 1][o - 1] else: # store it in arr to avoid further repetitive work # in future function calls arr[m - 1][n - 1][o - 1] = max(lcs(X, Y, Z, m, n - 1, o), max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))) return arr[m - 1][n - 1][o - 1] # Driver Codearr = [[[0 for k in range(100)] for j in range(100)] for i in range(100)] for i in range(100): for j in range(100): for k in range(100): arr[i][j][k] = -1 X = \"geeks\"Y = \"geeksfor\"Z = \"geeksforgeeks\"m = len(X)n = len(Y)o = len(Z)print(\"Length of LCS is \", lcs(X, Y, Z, m, n, o)) # This code is contributed by Dharanendra L V.",
"e": 60144,
"s": 58714,
"text": null
},
{
"code": "// A memoize recursive implementation of LCS problemusing System;public class GFG{ public static int[, , ] arr = new int[100, 100, 100]; // Returns length of LCS for X[0..m-1], Y[0..n-1] */ // memoization applied in recursive solution static int lcs(String X, String Y, String Z, int m, int n, int o) { // base case if (m == 0 || n == 0 || o == 0) return 0; // if the same state has already been // computed if (arr[m - 1, n - 1, o - 1] != -1) return arr[m - 1, n - 1, o - 1]; // if equal, then we store the value of the // function call if (X[m - 1] == Y[n - 1] && Y[n - 1] == Z[o - 1]) { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1, n - 1, o - 1] = 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); return arr[m - 1, n - 1, o - 1]; } else { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1, n - 1, o - 1] = max(lcs(X, Y, Z, m, n - 1, o), max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); return arr[m - 1, n - 1, o - 1]; } } // Utility function to get max of 2 integers static int max(int a, int b) { return (a > b) ? a : b; } // Driver Code static public void Main (){ for(int i = 0; i < 100; i++) { for(int j = 0; j < 100; j++) { for(int k = 0; k < 100; k++) { arr[i, j, k] = -1; } } } String X = \"geeks\"; String Y = \"geeksfor\"; String Z = \"geeksforgeeks\"; int m = X.Length; int n = Y.Length; int o = Z.Length; Console.WriteLine(\"Length of LCS is \" + lcs(X, Y, Z, m, n, o)); }} // This code is contributed by Dharanendra L V.",
"e": 62054,
"s": 60144,
"text": null
},
{
"code": "<script>// A memoize recursive implementation of LCS problem let arr=new Array(100); for(let i=0;i<100;i++) { arr[i]=new Array(100); for(let j=0;j<100;j++) { arr[i][j]=new Array(100); for(let k=0;k<100;k++) { arr[i][j][k]=-1; } } } // Returns length of LCS for X[0..m-1], Y[0..n-1] */ // memoization applied in recursive solution function lcs(X,Y,Z,m,n,o) { // base case if (m == 0 || n == 0 || o == 0) return 0; // if the same state has already been // computed if (arr[m - 1][n - 1][o - 1] != -1) return arr[m - 1][n - 1][o - 1]; // if equal, then we store the value of the // function call if (X[m-1] == Y[n-1] && Y[n-1] == Z[o-1]) { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1][n - 1][o - 1] = 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1); return arr[m - 1][n - 1][o - 1]; } else { // store it in arr to avoid further repetitive work // in future function calls arr[m - 1][n - 1][o - 1] = max(lcs(X, Y, Z, m, n - 1, o), max(lcs(X, Y, Z, m - 1, n, o), lcs(X, Y, Z, m, n, o - 1))); return arr[m - 1][n - 1][o - 1]; } } // Utility function to get max of 2 integers function max(a,b) { return (a > b) ? a : b; } // Driver Code let X = \"geeks\"; let Y = \"geeksfor\"; let Z = \"geeksforgeeks\"; let m = X.length; let n = Y.length; let o = Z.length; document.write(\"Length of LCS is \" + lcs(X, Y, Z, m, n, o)); // This code is contributed by patel2127</script>",
"e": 63951,
"s": 62054,
"text": null
},
{
"code": null,
"e": 63970,
"s": 63951,
"text": "Length of LCS is 5"
},
{
"code": null,
"e": 64152,
"s": 63972,
"text": "Note: The array used to Memoize is initialized to some value (say -1) before the function call to mark if the function with the same parameters has been previously called or not. "
},
{
"code": null,
"e": 64158,
"s": 64152,
"text": "jit_t"
},
{
"code": null,
"e": 64173,
"s": 64158,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 64179,
"s": 64173,
"text": "ukasp"
},
{
"code": null,
"e": 64188,
"s": 64179,
"text": "vvkbisht"
},
{
"code": null,
"e": 64204,
"s": 64188,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 64220,
"s": 64204,
"text": "subhammahato348"
},
{
"code": null,
"e": 64238,
"s": 64220,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 64252,
"s": 64238,
"text": "divyesh072019"
},
{
"code": null,
"e": 64262,
"s": 64252,
"text": "rutvik_56"
},
{
"code": null,
"e": 64274,
"s": 64262,
"text": "manupathria"
},
{
"code": null,
"e": 64290,
"s": 64274,
"text": "dharanendralv23"
},
{
"code": null,
"e": 64299,
"s": 64290,
"text": "mukesh07"
},
{
"code": null,
"e": 64320,
"s": 64299,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 64328,
"s": 64320,
"text": "rag2127"
},
{
"code": null,
"e": 64340,
"s": 64328,
"text": "unknown2108"
},
{
"code": null,
"e": 64350,
"s": 64340,
"text": "patel2127"
},
{
"code": null,
"e": 64367,
"s": 64350,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 64382,
"s": 64367,
"text": "rameshtravel07"
},
{
"code": null,
"e": 64392,
"s": 64382,
"text": "Fibonacci"
},
{
"code": null,
"e": 64396,
"s": 64392,
"text": "LCS"
},
{
"code": null,
"e": 64416,
"s": 64396,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 64426,
"s": 64416,
"text": "Recursion"
},
{
"code": null,
"e": 64446,
"s": 64426,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 64456,
"s": 64446,
"text": "Recursion"
},
{
"code": null,
"e": 64466,
"s": 64456,
"text": "Fibonacci"
},
{
"code": null,
"e": 64470,
"s": 64466,
"text": "LCS"
},
{
"code": null,
"e": 64568,
"s": 64470,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 64599,
"s": 64568,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 64632,
"s": 64599,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 64659,
"s": 64632,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 64678,
"s": 64659,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 64713,
"s": 64678,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 64773,
"s": 64713,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 64858,
"s": 64773,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 64868,
"s": 64858,
"text": "Recursion"
},
{
"code": null,
"e": 64895,
"s": 64868,
"text": "Program for Tower of Hanoi"
}
] |
Hungarian Algorithm for Assignment Problem | Set 1 (Introduction) - GeeksforGeeks | 04 Mar, 2020
Let there be n agents and n tasks. Any agent can be assigned to perform any task, incurring some cost that may vary depending on the agent-task assignment. It is required to perform all tasks by assigning exactly one agent to each task and exactly one task to each agent in such a way that the total cost of the assignment is minimized.
Example: You work as a manager for a chip manufacturer, and you currently have 3 people on the road meeting clients. Your salespeople are in Jaipur, Pune and Bangalore, and you want them to fly to three other cities: Delhi, Mumbai and Kerala. The table below shows the cost of airline tickets in INR between the cities:
The question: where would you send each of your salespeople in order to minimize fair?
Possible assignment: Cost = 11000 INR
Other Possible assignment: Cost = 9500 INR and this is the best of the 3! possible assignments.
Brute force solution is to consider every possible assignment implies a complexity of Ω(n!).
The Hungarian algorithm, aka Munkres assignment algorithm, utilizes the following theorem for polynomial runtime complexity (worst case O(n3)) and guaranteed optimality:If a number is added to or subtracted from all of the entries of any one row or column of a cost matrix, then an optimal assignment for the resulting cost matrix is also an optimal assignment for the original cost matrix.
We reduce our original weight matrix to contain zeros, by using the above theorem. We try to assign tasks to agents such that each agent is doing only one task and the penalty incurred in each case is zero.
Core of the algorithm (assuming square matrix):
For each row of the matrix, find the smallest element and subtract it from every element in its row.Do the same (as step 1) for all columns.Cover all zeros in the matrix using minimum number of horizontal and vertical lines.Test for Optimality: If the minimum number of covering lines is n, an optimal assignment is possible and we are finished. Else if lines are lesser than n, we haven’t found the optimal assignment, and must proceed to step 5.Determine the smallest entry not covered by any line. Subtract this entry from each uncovered row, and then add it to each covered column. Return to step 3.
For each row of the matrix, find the smallest element and subtract it from every element in its row.
Do the same (as step 1) for all columns.
Cover all zeros in the matrix using minimum number of horizontal and vertical lines.
Test for Optimality: If the minimum number of covering lines is n, an optimal assignment is possible and we are finished. Else if lines are lesser than n, we haven’t found the optimal assignment, and must proceed to step 5.
Determine the smallest entry not covered by any line. Subtract this entry from each uncovered row, and then add it to each covered column. Return to step 3.
Explanation for above simple example:
Below is the cost matrix of example given in above diagrams.
2500 4000 3500
4000 6000 3500
2000 4000 2500
Step 1: Subtract minimum of every row.
2500, 3500 and 2000 are subtracted from rows 1, 2 and
3 respectively.
0 1500 1000
500 2500 0
0 2000 500
Step 2: Subtract minimum of every column.
0, 1500 and 0 are subtracted from columns 1, 2 and 3
respectively.
0 0 1000
500 1000 0
0 500 500
Step 3: Cover all zeroes with minimum number of
horizontal and vertical lines.
Step 4: Since we need 3 lines to cover all zeroes,
we have found the optimal assignment.
2500 4000 3500
4000 6000 3500
2000 4000 2500
So the optimal cost is 4000 + 3500 + 2000 = 9500
An example that doesn’t lead to optimal value in first attempt:In the above example, the first check for optimality did give us solution. What if we the number covering lines is less than n.
cost matrix:
1500 4000 4500
2000 6000 3500
2000 4000 2500
Step 1: Subtract minimum of every row.
1500, 2000 and 2000 are subtracted from rows 1, 2 and
3 respectively.
0 2500 3000
0 4000 1500
0 2000 500
Step 2: Subtract minimum of every column.
0, 2000 and 500 are subtracted from columns 1, 2 and 3
respectively.
0 500 2500
0 2000 1000
0 0 0
Step 3: Cover all zeroes with minimum number of
horizontal and vertical lines.
Step 4: Since we only need 2 lines to cover all zeroes,
we have NOT found the optimal assignment.
Step 5: We subtract the smallest uncovered entry
from all uncovered rows. Smallest entry is 500.
-500 0 2000
-500 1500 500
0 0 0
Then we add the smallest entry to all covered columns, we get
0 0 2000
0 1500 500
500 0 0
Now we return to Step 3:. Here we cover again using
lines. and go to Step 4:. Since we need 3 lines to
cover, we found the optimal solution.
1500 4000 4500
2000 6000 3500
2000 4000 2500
So the optimal cost is 4000 + 2000 + 2500 = 8500
In the next post, we will be discussing implementation of the above algorithm. The implementation requires more steps as we need to find minimum number of lines to cover all 0’s using a program.
References:http://www.math.harvard.edu/archive/20_spring_05/handouts/assignment_overheads.pdfhttps://www.youtube.com/watch?v=dQDZNHwuuOY
This article is contributed by Yash Varyani. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Rohit_Goyal
Google
Graph
Mathematical
Google
Mathematical
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ford-Fulkerson Algorithm for Maximum Flow Problem
Traveling Salesman Problem (TSP) Implementation
Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8
m Coloring Problem | Backtracking-5
Hamiltonian Cycle | Backtracking-6
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 26571,
"s": 26543,
"text": "\n04 Mar, 2020"
},
{
"code": null,
"e": 26908,
"s": 26571,
"text": "Let there be n agents and n tasks. Any agent can be assigned to perform any task, incurring some cost that may vary depending on the agent-task assignment. It is required to perform all tasks by assigning exactly one agent to each task and exactly one task to each agent in such a way that the total cost of the assignment is minimized."
},
{
"code": null,
"e": 27228,
"s": 26908,
"text": "Example: You work as a manager for a chip manufacturer, and you currently have 3 people on the road meeting clients. Your salespeople are in Jaipur, Pune and Bangalore, and you want them to fly to three other cities: Delhi, Mumbai and Kerala. The table below shows the cost of airline tickets in INR between the cities:"
},
{
"code": null,
"e": 27315,
"s": 27228,
"text": "The question: where would you send each of your salespeople in order to minimize fair?"
},
{
"code": null,
"e": 27353,
"s": 27315,
"text": "Possible assignment: Cost = 11000 INR"
},
{
"code": null,
"e": 27449,
"s": 27353,
"text": "Other Possible assignment: Cost = 9500 INR and this is the best of the 3! possible assignments."
},
{
"code": null,
"e": 27542,
"s": 27449,
"text": "Brute force solution is to consider every possible assignment implies a complexity of Ω(n!)."
},
{
"code": null,
"e": 27933,
"s": 27542,
"text": "The Hungarian algorithm, aka Munkres assignment algorithm, utilizes the following theorem for polynomial runtime complexity (worst case O(n3)) and guaranteed optimality:If a number is added to or subtracted from all of the entries of any one row or column of a cost matrix, then an optimal assignment for the resulting cost matrix is also an optimal assignment for the original cost matrix."
},
{
"code": null,
"e": 28140,
"s": 27933,
"text": "We reduce our original weight matrix to contain zeros, by using the above theorem. We try to assign tasks to agents such that each agent is doing only one task and the penalty incurred in each case is zero."
},
{
"code": null,
"e": 28188,
"s": 28140,
"text": "Core of the algorithm (assuming square matrix):"
},
{
"code": null,
"e": 28792,
"s": 28188,
"text": "For each row of the matrix, find the smallest element and subtract it from every element in its row.Do the same (as step 1) for all columns.Cover all zeros in the matrix using minimum number of horizontal and vertical lines.Test for Optimality: If the minimum number of covering lines is n, an optimal assignment is possible and we are finished. Else if lines are lesser than n, we haven’t found the optimal assignment, and must proceed to step 5.Determine the smallest entry not covered by any line. Subtract this entry from each uncovered row, and then add it to each covered column. Return to step 3."
},
{
"code": null,
"e": 28893,
"s": 28792,
"text": "For each row of the matrix, find the smallest element and subtract it from every element in its row."
},
{
"code": null,
"e": 28934,
"s": 28893,
"text": "Do the same (as step 1) for all columns."
},
{
"code": null,
"e": 29019,
"s": 28934,
"text": "Cover all zeros in the matrix using minimum number of horizontal and vertical lines."
},
{
"code": null,
"e": 29243,
"s": 29019,
"text": "Test for Optimality: If the minimum number of covering lines is n, an optimal assignment is possible and we are finished. Else if lines are lesser than n, we haven’t found the optimal assignment, and must proceed to step 5."
},
{
"code": null,
"e": 29400,
"s": 29243,
"text": "Determine the smallest entry not covered by any line. Subtract this entry from each uncovered row, and then add it to each covered column. Return to step 3."
},
{
"code": null,
"e": 29438,
"s": 29400,
"text": "Explanation for above simple example:"
},
{
"code": null,
"e": 30158,
"s": 29438,
"text": " \nBelow is the cost matrix of example given in above diagrams.\n 2500 4000 3500\n 4000 6000 3500\n 2000 4000 2500\n\nStep 1: Subtract minimum of every row.\n2500, 3500 and 2000 are subtracted from rows 1, 2 and \n3 respectively.\n\n 0 1500 1000\n 500 2500 0\n 0 2000 500\n\nStep 2: Subtract minimum of every column.\n0, 1500 and 0 are subtracted from columns 1, 2 and 3 \nrespectively.\n\n 0 0 1000\n 500 1000 0\n 0 500 500\n\nStep 3: Cover all zeroes with minimum number of \nhorizontal and vertical lines.\n\n\nStep 4: Since we need 3 lines to cover all zeroes,\nwe have found the optimal assignment. \n 2500 4000 3500\n 4000 6000 3500\n 2000 4000 2500\n\nSo the optimal cost is 4000 + 3500 + 2000 = 9500\n"
},
{
"code": null,
"e": 30351,
"s": 30160,
"text": "An example that doesn’t lead to optimal value in first attempt:In the above example, the first check for optimality did give us solution. What if we the number covering lines is less than n."
},
{
"code": null,
"e": 31458,
"s": 30351,
"text": " \ncost matrix:\n 1500 4000 4500\n 2000 6000 3500\n 2000 4000 2500\n\nStep 1: Subtract minimum of every row.\n1500, 2000 and 2000 are subtracted from rows 1, 2 and \n3 respectively.\n\n 0 2500 3000\n 0 4000 1500\n 0 2000 500\n\nStep 2: Subtract minimum of every column.\n0, 2000 and 500 are subtracted from columns 1, 2 and 3 \nrespectively.\n\n 0 500 2500\n 0 2000 1000 \n 0 0 0 \n\nStep 3: Cover all zeroes with minimum number of \nhorizontal and vertical lines.\n\n\nStep 4: Since we only need 2 lines to cover all zeroes,\nwe have NOT found the optimal assignment. \n\nStep 5: We subtract the smallest uncovered entry \nfrom all uncovered rows. Smallest entry is 500.\n -500 0 2000\n -500 1500 500\n 0 0 0\n\nThen we add the smallest entry to all covered columns, we get\n 0 0 2000\n 0 1500 500\n 500 0 0\n\nNow we return to Step 3:. Here we cover again using\nlines. and go to Step 4:. Since we need 3 lines to \ncover, we found the optimal solution.\n 1500 4000 4500\n 2000 6000 3500\n 2000 4000 2500\n\nSo the optimal cost is 4000 + 2000 + 2500 = 8500\n"
},
{
"code": null,
"e": 31653,
"s": 31458,
"text": "In the next post, we will be discussing implementation of the above algorithm. The implementation requires more steps as we need to find minimum number of lines to cover all 0’s using a program."
},
{
"code": null,
"e": 31790,
"s": 31653,
"text": "References:http://www.math.harvard.edu/archive/20_spring_05/handouts/assignment_overheads.pdfhttps://www.youtube.com/watch?v=dQDZNHwuuOY"
},
{
"code": null,
"e": 31960,
"s": 31790,
"text": "This article is contributed by Yash Varyani. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31972,
"s": 31960,
"text": "Rohit_Goyal"
},
{
"code": null,
"e": 31979,
"s": 31972,
"text": "Google"
},
{
"code": null,
"e": 31985,
"s": 31979,
"text": "Graph"
},
{
"code": null,
"e": 31998,
"s": 31985,
"text": "Mathematical"
},
{
"code": null,
"e": 32005,
"s": 31998,
"text": "Google"
},
{
"code": null,
"e": 32018,
"s": 32005,
"text": "Mathematical"
},
{
"code": null,
"e": 32024,
"s": 32018,
"text": "Graph"
},
{
"code": null,
"e": 32122,
"s": 32024,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32172,
"s": 32122,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 32220,
"s": 32172,
"text": "Traveling Salesman Problem (TSP) Implementation"
},
{
"code": null,
"e": 32291,
"s": 32220,
"text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8"
},
{
"code": null,
"e": 32327,
"s": 32291,
"text": "m Coloring Problem | Backtracking-5"
},
{
"code": null,
"e": 32362,
"s": 32327,
"text": "Hamiltonian Cycle | Backtracking-6"
},
{
"code": null,
"e": 32392,
"s": 32362,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32452,
"s": 32392,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32467,
"s": 32452,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32510,
"s": 32467,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Maximize the bitwise OR of an array - GeeksforGeeks | 05 May, 2021
Given an array of N integers. The bitwise OR of all the elements of the array has to be maximized by performing one task. The task is to multiply any element of the array at-most k times with a given integer x.Examples :
Input: a = {1, 1, 1}, k = 1, x = 2 Output: 3 Explanation: Any possible choice of doing one element of the array will result the same three numbers 1, 1, 2. So, the result is 1 | 1 | 2 = 3.Input: a = {1, 2, 4, 8}, k = 2, x = 3 Output: 79
Approach: Precompute the prefix and suffix OR arrays. In one iteration, multiply an element with x^k and do Bitwise OR it with prefix OR i.e. Bitwise OR of all previous elements and suffix OR i.e. Bitwise OR of all next elements and return the maximum value after all iterations.
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to maximize the Bitwise// OR Sum in given array#include <bits/stdc++.h>using namespace std; // Function to maximize the bitwise// OR sumint maxOR(long long arr[], int n, int k, int x){ long long preSum[n + 1], suffSum[n + 1]; long long res, pow = 1; // Compute x^k for (int i = 0; i < k; i++) pow *= x; // Find prefix bitwise OR preSum[0] = 0; for (int i = 0; i < n; i++) preSum[i + 1] = preSum[i] | arr[i]; // Find suffix bitwise OR suffSum[n] = 0; for (int i = n - 1; i >= 0; i--) suffSum[i] = suffSum[i + 1] | arr[i]; // Find maximum OR value res = 0; for (int i = 0; i < n; i++) res = max(res, preSum[i] | (arr[i] * pow) | suffSum[i + 1]); return res;} // Drivers codeint main(){ long long arr[] = { 1, 2, 4, 8 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2, x = 3; cout << maxOR(arr, n, k, x) << "\n"; return 0;}
// Java program to maximize the Bitwise// OR Sum in given arrayimport java.io.*; class GFG { // Function to maximize the bitwise OR sum public static long maxOR(long arr[], int n, int k, int x) { long preSum[] = new long[n + 1]; long suffSum[] = new long[n + 1]; long res = 0, pow = 1; // Compute x^k for (int i = 0; i < k; i++) pow *= x; // Find prefix bitwise OR preSum[0] = 0; for (int i = 0; i < n; i++) preSum[i + 1] = preSum[i] | arr[i]; // Find suffix bitwise OR suffSum[n] = 0; for (int i = n - 1; i >= 0; i--) suffSum[i] = suffSum[i + 1] | arr[i]; // Find maximum OR value res = 0; for (int i = 0; i < n; i++) res = Math.max(res, preSum[i] | (arr[i] * pow) | suffSum[i + 1]); return res; } // Drivers code public static void main(String args[]) { long arr[] = { 1, 2, 4, 8 }; int n = 4; int k = 2, x = 3; long ans = maxOR(arr, n, k, x); System.out.println(ans); }} // This code is contributed by Jaideep Pyne
# Python3 program to maximize the Bitwise# OR Sum in given array # Function to maximize the bitwise# OR sumdef maxOR(arr, n, k, x): preSum = [0] * (n + 1) suffSum = [0] * (n + 1) pow = 1 # Compute x^k for i in range(0 ,k): pow *= x # Find prefix bitwise OR preSum[0] = 0 for i in range(0, n): preSum[i + 1] = preSum[i] | arr[i] # Find suffix bitwise OR suffSum[n] = 0 for i in range(n-1, -1, -1): suffSum[i] = suffSum[i + 1] | arr[i] # Find maximum OR value res = 0 for i in range(0 ,n): res = max(res, preSum[i] | (arr[i] * pow) | suffSum[i + 1]) return res # Drivers codearr = [1, 2, 4, 8 ]n = len(arr)k = 2x = 3print(maxOR(arr, n, k, x)) # This code is contributed by Smitha
// C# program to maximize the Bitwise// OR Sum in given arrayusing System; class GFG { // Function to maximize the bitwise OR sum public static long maxOR(long []arr, int n, int k, int x) { long []preSum = new long[n + 1]; long []suffSum = new long[n + 1]; long res = 0, pow = 1; // Compute x^k for (int i = 0; i < k; i++) pow *= x; // Find prefix bitwise OR preSum[0] = 0; for (int i = 0; i < n; i++) preSum[i + 1] = preSum[i] | arr[i]; // Find suffix bitwise OR suffSum[n] = 0; for (int i = n - 1; i >= 0; i--) suffSum[i] = suffSum[i + 1] | arr[i]; // Find maximum OR value res = 0; for (int i = 0; i < n; i++) res = Math.Max(res, preSum[i] | (arr[i] * pow) | suffSum[i + 1]); return res; } // Drivers code public static void Main() { long []arr = { 1, 2, 4, 8 }; int n = 4; int k = 2, x = 3; long ans = maxOR(arr, n, k, x); Console.Write(ans); }} // This code is contributed by Smitha
<?php// PHP program to maximize the// Bitwise OR Sum in given array // Function to maximize// the bitwise OR sum function maxOR($arr, $n, $k, $x){ $res; $pow = 1; // Compute x^k for ($i = 0; $i < $k; $i++) $pow *= $x; // Find prefix bitwise OR $preSum[0] = 0; for ($i = 0; $i < $n; $i++) $preSum[$i + 1] = $preSum[$i] | $arr[$i]; // Find suffix bitwise OR $suffSum[$n] = 0; for ($i = $n - 1; $i >= 0; $i--) $suffSum[$i] = $suffSum[$i + 1] | $arr[$i]; // Find maximum OR value $res = 0; for ($i = 0; $i < $n; $i++) $res = max($res, $preSum[$i] | ($arr[$i] * $pow) | $suffSum[$i + 1]); return $res;} // Driver Code$arr = array(1, 2, 4, 8);$n = sizeof($arr);$k = 2; $x = 3; echo maxOR($arr, $n, $k, $x),"\n"; // This code is contributed by jit_t?>
<script> // Javascript program to maximize the Bitwise OR Sum in given array // Function to maximize the bitwise OR sum function maxOR(arr, n, k, x) { let preSum = new Array(n + 1); let suffSum = new Array(n + 1); let res = 0, pow = 1; // Compute x^k for (let i = 0; i < k; i++) pow *= x; // Find prefix bitwise OR preSum[0] = 0; for (let i = 0; i < n; i++) preSum[i + 1] = preSum[i] | arr[i]; // Find suffix bitwise OR suffSum[n] = 0; for (let i = n - 1; i >= 0; i--) suffSum[i] = suffSum[i + 1] | arr[i]; // Find maximum OR value res = 0; for (let i = 0; i < n; i++) res = Math.max(res, preSum[i] | (arr[i] * pow) | suffSum[i + 1]); return res; } let arr = [ 1, 2, 4, 8 ]; let n = 4; let k = 2, x = 3; let ans = maxOR(arr, n, k, x); document.write(ans); // This code is contributed by suresh07.</script>
79
jaideeppyne1997
jit_t
Smitha Dinesh Semwal
nidhi_biet
suresh07
Bitwise-OR
Arrays
Bit Magic
Competitive Programming
Arrays
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable? | [
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 26290,
"s": 26067,
"text": "Given an array of N integers. The bitwise OR of all the elements of the array has to be maximized by performing one task. The task is to multiply any element of the array at-most k times with a given integer x.Examples : "
},
{
"code": null,
"e": 26528,
"s": 26290,
"text": "Input: a = {1, 1, 1}, k = 1, x = 2 Output: 3 Explanation: Any possible choice of doing one element of the array will result the same three numbers 1, 1, 2. So, the result is 1 | 1 | 2 = 3.Input: a = {1, 2, 4, 8}, k = 2, x = 3 Output: 79 "
},
{
"code": null,
"e": 26811,
"s": 26530,
"text": "Approach: Precompute the prefix and suffix OR arrays. In one iteration, multiply an element with x^k and do Bitwise OR it with prefix OR i.e. Bitwise OR of all previous elements and suffix OR i.e. Bitwise OR of all next elements and return the maximum value after all iterations. "
},
{
"code": null,
"e": 26815,
"s": 26811,
"text": "C++"
},
{
"code": null,
"e": 26820,
"s": 26815,
"text": "Java"
},
{
"code": null,
"e": 26829,
"s": 26820,
"text": "Python 3"
},
{
"code": null,
"e": 26832,
"s": 26829,
"text": "C#"
},
{
"code": null,
"e": 26836,
"s": 26832,
"text": "PHP"
},
{
"code": null,
"e": 26847,
"s": 26836,
"text": "Javascript"
},
{
"code": "// C++ program to maximize the Bitwise// OR Sum in given array#include <bits/stdc++.h>using namespace std; // Function to maximize the bitwise// OR sumint maxOR(long long arr[], int n, int k, int x){ long long preSum[n + 1], suffSum[n + 1]; long long res, pow = 1; // Compute x^k for (int i = 0; i < k; i++) pow *= x; // Find prefix bitwise OR preSum[0] = 0; for (int i = 0; i < n; i++) preSum[i + 1] = preSum[i] | arr[i]; // Find suffix bitwise OR suffSum[n] = 0; for (int i = n - 1; i >= 0; i--) suffSum[i] = suffSum[i + 1] | arr[i]; // Find maximum OR value res = 0; for (int i = 0; i < n; i++) res = max(res, preSum[i] | (arr[i] * pow) | suffSum[i + 1]); return res;} // Drivers codeint main(){ long long arr[] = { 1, 2, 4, 8 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2, x = 3; cout << maxOR(arr, n, k, x) << \"\\n\"; return 0;}",
"e": 27777,
"s": 26847,
"text": null
},
{
"code": "// Java program to maximize the Bitwise// OR Sum in given arrayimport java.io.*; class GFG { // Function to maximize the bitwise OR sum public static long maxOR(long arr[], int n, int k, int x) { long preSum[] = new long[n + 1]; long suffSum[] = new long[n + 1]; long res = 0, pow = 1; // Compute x^k for (int i = 0; i < k; i++) pow *= x; // Find prefix bitwise OR preSum[0] = 0; for (int i = 0; i < n; i++) preSum[i + 1] = preSum[i] | arr[i]; // Find suffix bitwise OR suffSum[n] = 0; for (int i = n - 1; i >= 0; i--) suffSum[i] = suffSum[i + 1] | arr[i]; // Find maximum OR value res = 0; for (int i = 0; i < n; i++) res = Math.max(res, preSum[i] | (arr[i] * pow) | suffSum[i + 1]); return res; } // Drivers code public static void main(String args[]) { long arr[] = { 1, 2, 4, 8 }; int n = 4; int k = 2, x = 3; long ans = maxOR(arr, n, k, x); System.out.println(ans); }} // This code is contributed by Jaideep Pyne",
"e": 28971,
"s": 27777,
"text": null
},
{
"code": "# Python3 program to maximize the Bitwise# OR Sum in given array # Function to maximize the bitwise# OR sumdef maxOR(arr, n, k, x): preSum = [0] * (n + 1) suffSum = [0] * (n + 1) pow = 1 # Compute x^k for i in range(0 ,k): pow *= x # Find prefix bitwise OR preSum[0] = 0 for i in range(0, n): preSum[i + 1] = preSum[i] | arr[i] # Find suffix bitwise OR suffSum[n] = 0 for i in range(n-1, -1, -1): suffSum[i] = suffSum[i + 1] | arr[i] # Find maximum OR value res = 0 for i in range(0 ,n): res = max(res, preSum[i] | (arr[i] * pow) | suffSum[i + 1]) return res # Drivers codearr = [1, 2, 4, 8 ]n = len(arr)k = 2x = 3print(maxOR(arr, n, k, x)) # This code is contributed by Smitha",
"e": 29738,
"s": 28971,
"text": null
},
{
"code": "// C# program to maximize the Bitwise// OR Sum in given arrayusing System; class GFG { // Function to maximize the bitwise OR sum public static long maxOR(long []arr, int n, int k, int x) { long []preSum = new long[n + 1]; long []suffSum = new long[n + 1]; long res = 0, pow = 1; // Compute x^k for (int i = 0; i < k; i++) pow *= x; // Find prefix bitwise OR preSum[0] = 0; for (int i = 0; i < n; i++) preSum[i + 1] = preSum[i] | arr[i]; // Find suffix bitwise OR suffSum[n] = 0; for (int i = n - 1; i >= 0; i--) suffSum[i] = suffSum[i + 1] | arr[i]; // Find maximum OR value res = 0; for (int i = 0; i < n; i++) res = Math.Max(res, preSum[i] | (arr[i] * pow) | suffSum[i + 1]); return res; } // Drivers code public static void Main() { long []arr = { 1, 2, 4, 8 }; int n = 4; int k = 2, x = 3; long ans = maxOR(arr, n, k, x); Console.Write(ans); }} // This code is contributed by Smitha",
"e": 30902,
"s": 29738,
"text": null
},
{
"code": "<?php// PHP program to maximize the// Bitwise OR Sum in given array // Function to maximize// the bitwise OR sum function maxOR($arr, $n, $k, $x){ $res; $pow = 1; // Compute x^k for ($i = 0; $i < $k; $i++) $pow *= $x; // Find prefix bitwise OR $preSum[0] = 0; for ($i = 0; $i < $n; $i++) $preSum[$i + 1] = $preSum[$i] | $arr[$i]; // Find suffix bitwise OR $suffSum[$n] = 0; for ($i = $n - 1; $i >= 0; $i--) $suffSum[$i] = $suffSum[$i + 1] | $arr[$i]; // Find maximum OR value $res = 0; for ($i = 0; $i < $n; $i++) $res = max($res, $preSum[$i] | ($arr[$i] * $pow) | $suffSum[$i + 1]); return $res;} // Driver Code$arr = array(1, 2, 4, 8);$n = sizeof($arr);$k = 2; $x = 3; echo maxOR($arr, $n, $k, $x),\"\\n\"; // This code is contributed by jit_t?>",
"e": 31820,
"s": 30902,
"text": null
},
{
"code": "<script> // Javascript program to maximize the Bitwise OR Sum in given array // Function to maximize the bitwise OR sum function maxOR(arr, n, k, x) { let preSum = new Array(n + 1); let suffSum = new Array(n + 1); let res = 0, pow = 1; // Compute x^k for (let i = 0; i < k; i++) pow *= x; // Find prefix bitwise OR preSum[0] = 0; for (let i = 0; i < n; i++) preSum[i + 1] = preSum[i] | arr[i]; // Find suffix bitwise OR suffSum[n] = 0; for (let i = n - 1; i >= 0; i--) suffSum[i] = suffSum[i + 1] | arr[i]; // Find maximum OR value res = 0; for (let i = 0; i < n; i++) res = Math.max(res, preSum[i] | (arr[i] * pow) | suffSum[i + 1]); return res; } let arr = [ 1, 2, 4, 8 ]; let n = 4; let k = 2, x = 3; let ans = maxOR(arr, n, k, x); document.write(ans); // This code is contributed by suresh07.</script>",
"e": 32831,
"s": 31820,
"text": null
},
{
"code": null,
"e": 32834,
"s": 32831,
"text": "79"
},
{
"code": null,
"e": 32852,
"s": 32836,
"text": "jaideeppyne1997"
},
{
"code": null,
"e": 32858,
"s": 32852,
"text": "jit_t"
},
{
"code": null,
"e": 32879,
"s": 32858,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 32890,
"s": 32879,
"text": "nidhi_biet"
},
{
"code": null,
"e": 32899,
"s": 32890,
"text": "suresh07"
},
{
"code": null,
"e": 32910,
"s": 32899,
"text": "Bitwise-OR"
},
{
"code": null,
"e": 32917,
"s": 32910,
"text": "Arrays"
},
{
"code": null,
"e": 32927,
"s": 32917,
"text": "Bit Magic"
},
{
"code": null,
"e": 32951,
"s": 32927,
"text": "Competitive Programming"
},
{
"code": null,
"e": 32958,
"s": 32951,
"text": "Arrays"
},
{
"code": null,
"e": 32968,
"s": 32958,
"text": "Bit Magic"
},
{
"code": null,
"e": 33066,
"s": 32968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33093,
"s": 33066,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 33124,
"s": 33093,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 33149,
"s": 33124,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 33187,
"s": 33149,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 33208,
"s": 33187,
"text": "Next Greater Element"
},
{
"code": null,
"e": 33235,
"s": 33208,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 33281,
"s": 33235,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 33349,
"s": 33281,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 33378,
"s": 33349,
"text": "Count set bits in an integer"
}
] |
How to get highcharts dates in the x-axis ? - GeeksforGeeks | 22 Jun, 2020
Graphs or charts are the best way to represent data as they are more user-friendly than viewing raw data. It also makes it easy to perform analytics on the data. There are many libraries in JavaScript that make it easy to create these visualizations and use them in mobile or web applications. One such library is Highcharts JS. It is a SVG based multi-platform JavaScript charting library that makes it easy to add interactive visualizations to applications.
Example: The below example shows a simple line chart with random data and the x-axis having DateTime type. The code below will be used to define the HTML document where the graph would be drawn.
html
<!DOCTYPE html><html> <head> <title>Highcharts JS line chart</title> <!-- Include the highcharts library --> <script src="https://code.highcharts.com/highcharts.js"> </script> <!-- Include additional JavaScript here --> </head> <body> <div id="plot-container" style="height: 500px; width: 700px"> </div> </body></html>
The JavaScript code shows the chart along with its required parameters.
javascript
// Define the chartvar chart = new Highcharts.Chart({ chart: { renderTo: 'plot-container', type: 'line' }, title: { text: 'Daily random data' }, xAxis: { title: { text: 'Date' }, type: 'datetime' }, yAxis: { title: { text: 'Reading (in units)' } }, // Define the data to be represented series: [{ data: [ 12.2, 54.5, 39.1, 29.9, 100, 35.4, 93.7, 106.4, 150, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 84.7, 122.9, 137.4, 135.2, 163.1, 195.2, 195.1, 182.7, 174.3, 201.8, 199.2, ], pointStart: Date.UTC(2010, 0, 1), pointInterval: 3600 * 1000 // one hour }]});
Output:
The above chart has some values for each hour of a day. For Example, at 4:00 hrs, the value on the y-axis is 100, at 8:00 hrs, the value is 150, and so on. Is it possible to determine the date from the x-axis for each time label? Yes, by observing, we see there are two dates: 1. Jan and 2. Jan and all of the time labels lying between them represent the time on 1. Jan and those lying after 2. Jan represents time on that day.
This observation was easy in the case of this example as the dataset for the chart is small. But in real-world projects, often the data represented on the charts is huge and a user looking at such a chart might expect to get the data about a particular day and time just by glancing through the chart.
This is where the flexibility and control provided by the Highcharts library becomes useful. The default behavior of the library can be modified by explicitly defining the DateTime label format for the axis of choice. By default, it uses the following formats for the DateTime labels according to the intervals defined below:
{
millisecond: '%H:%M:%S.%L',
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'
}
The labels used to represent the time are defined below:
%a: Short weekday, like 'Mon'.
%A: Long weekday, like 'Monday'.
%d: Two digit day of the month, 01 to 31.
%e: Day of the month, 1 through 31.
%b: Short month, like 'Jan'.
%B: Long month, like 'January'.
%m: Two digit month number, 01 through 12.
%y: Two digits year, like 09 for 2009.
%Y: Four digits year, like 2009.
%H: Two digits hours in 24h format, 00 through 23.
%I: Two digits hours in 12h format, 00 through 11.
%l (Lower case L): Hours in 12h format, 1 through 11.
%M: Two digits minutes, 00 through 59.
%p: Upper case AM or PM.
%P: Lower case AM or PM.
%S: Two digits seconds, 00 through 59
In the example, the time is being represented on the x-axis with the interval of hours. Therefore the default label used is ‘%H:%M’, which represents a two-digit hour and two-digit minute value for the data points.
This has to be changed such that along with time, it also shows the two-digit day, short month, and four digits year. Referring to the label definitions above, the new label to be used would be: ‘%H:%M %d %b %Y’
This change has to be made in the labels property by defining a formatter function with the required format. This code is added for the x-axis:
labels: {
formatter: function() {
return Highcharts.dateFormat('%H:%M %d %b %Y',this.value);
}
}
The final code including the changes is:
javascript
var chart = new Highcharts.Chart({ chart: { renderTo: 'plot-container', type: 'line' }, title: { text: 'Daily random data' }, xAxis: { title: { text: 'Date' }, type: 'datetime', // Use the date format in the // labels property of the chart labels: { formatter: function() { return Highcharts.dateFormat('%H:%M %d %b %Y', this.value); } } }, yAxis: { title: { text: 'Reading (in units)' } }, series: [{ data: [ 12.2, 54.5, 39.1, 29.9, 100, 35.4, 93.7, 106.4, 150, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 84.7, 122.9, 137.4, 135.2, 163.1, 195.2, 195.1, 182.7, 174.3, 201.8, 199.2, ], pointStart: Date.UTC(2010, 0, 1), pointInterval: 3600 * 1000 // one hour }]});
Output:
The above chart now displays the dates along with the time on the x-axis.
References:https://api.highcharts.com/highcharts/xAxis.dateTimeLabelFormatshttps://www.highcharts.com/forum/viewtopic.php?t=13389
amarjeet_singh
JavaScript-Misc
Picked
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript? | [
{
"code": null,
"e": 25815,
"s": 25787,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 26275,
"s": 25815,
"text": "Graphs or charts are the best way to represent data as they are more user-friendly than viewing raw data. It also makes it easy to perform analytics on the data. There are many libraries in JavaScript that make it easy to create these visualizations and use them in mobile or web applications. One such library is Highcharts JS. It is a SVG based multi-platform JavaScript charting library that makes it easy to add interactive visualizations to applications."
},
{
"code": null,
"e": 26470,
"s": 26275,
"text": "Example: The below example shows a simple line chart with random data and the x-axis having DateTime type. The code below will be used to define the HTML document where the graph would be drawn."
},
{
"code": null,
"e": 26475,
"s": 26470,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Highcharts JS line chart</title> <!-- Include the highcharts library --> <script src=\"https://code.highcharts.com/highcharts.js\"> </script> <!-- Include additional JavaScript here --> </head> <body> <div id=\"plot-container\" style=\"height: 500px; width: 700px\"> </div> </body></html>",
"e": 26831,
"s": 26475,
"text": null
},
{
"code": null,
"e": 26903,
"s": 26831,
"text": "The JavaScript code shows the chart along with its required parameters."
},
{
"code": null,
"e": 26914,
"s": 26903,
"text": "javascript"
},
{
"code": "// Define the chartvar chart = new Highcharts.Chart({ chart: { renderTo: 'plot-container', type: 'line' }, title: { text: 'Daily random data' }, xAxis: { title: { text: 'Date' }, type: 'datetime' }, yAxis: { title: { text: 'Reading (in units)' } }, // Define the data to be represented series: [{ data: [ 12.2, 54.5, 39.1, 29.9, 100, 35.4, 93.7, 106.4, 150, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 84.7, 122.9, 137.4, 135.2, 163.1, 195.2, 195.1, 182.7, 174.3, 201.8, 199.2, ], pointStart: Date.UTC(2010, 0, 1), pointInterval: 3600 * 1000 // one hour }]});",
"e": 27581,
"s": 26914,
"text": null
},
{
"code": null,
"e": 27590,
"s": 27581,
"text": "Output: "
},
{
"code": null,
"e": 28018,
"s": 27590,
"text": "The above chart has some values for each hour of a day. For Example, at 4:00 hrs, the value on the y-axis is 100, at 8:00 hrs, the value is 150, and so on. Is it possible to determine the date from the x-axis for each time label? Yes, by observing, we see there are two dates: 1. Jan and 2. Jan and all of the time labels lying between them represent the time on 1. Jan and those lying after 2. Jan represents time on that day."
},
{
"code": null,
"e": 28320,
"s": 28018,
"text": "This observation was easy in the case of this example as the dataset for the chart is small. But in real-world projects, often the data represented on the charts is huge and a user looking at such a chart might expect to get the data about a particular day and time just by glancing through the chart."
},
{
"code": null,
"e": 28647,
"s": 28320,
"text": "This is where the flexibility and control provided by the Highcharts library becomes useful. The default behavior of the library can be modified by explicitly defining the DateTime label format for the axis of choice. By default, it uses the following formats for the DateTime labels according to the intervals defined below: "
},
{
"code": null,
"e": 28824,
"s": 28647,
"text": "{\n millisecond: '%H:%M:%S.%L',\n second: '%H:%M:%S',\n minute: '%H:%M',\n hour: '%H:%M',\n day: '%e. %b',\n week: '%e. %b',\n month: '%b \\'%y',\n year: '%Y'\n}\n"
},
{
"code": null,
"e": 28883,
"s": 28824,
"text": "The labels used to represent the time are defined below: "
},
{
"code": null,
"e": 29486,
"s": 28883,
"text": "%a: Short weekday, like 'Mon'.\n%A: Long weekday, like 'Monday'.\n%d: Two digit day of the month, 01 to 31.\n%e: Day of the month, 1 through 31.\n%b: Short month, like 'Jan'.\n%B: Long month, like 'January'.\n%m: Two digit month number, 01 through 12.\n%y: Two digits year, like 09 for 2009.\n%Y: Four digits year, like 2009.\n%H: Two digits hours in 24h format, 00 through 23.\n%I: Two digits hours in 12h format, 00 through 11.\n%l (Lower case L): Hours in 12h format, 1 through 11.\n%M: Two digits minutes, 00 through 59.\n%p: Upper case AM or PM.\n%P: Lower case AM or PM.\n%S: Two digits seconds, 00 through 59\n\n"
},
{
"code": null,
"e": 29701,
"s": 29486,
"text": "In the example, the time is being represented on the x-axis with the interval of hours. Therefore the default label used is ‘%H:%M’, which represents a two-digit hour and two-digit minute value for the data points."
},
{
"code": null,
"e": 29913,
"s": 29701,
"text": "This has to be changed such that along with time, it also shows the two-digit day, short month, and four digits year. Referring to the label definitions above, the new label to be used would be: ‘%H:%M %d %b %Y’"
},
{
"code": null,
"e": 30059,
"s": 29913,
"text": "This change has to be made in the labels property by defining a formatter function with the required format. This code is added for the x-axis: "
},
{
"code": null,
"e": 30166,
"s": 30059,
"text": "labels: {\n formatter: function() {\n return Highcharts.dateFormat('%H:%M %d %b %Y',this.value);\n }\n}\n\n"
},
{
"code": null,
"e": 30207,
"s": 30166,
"text": "The final code including the changes is:"
},
{
"code": null,
"e": 30218,
"s": 30207,
"text": "javascript"
},
{
"code": "var chart = new Highcharts.Chart({ chart: { renderTo: 'plot-container', type: 'line' }, title: { text: 'Daily random data' }, xAxis: { title: { text: 'Date' }, type: 'datetime', // Use the date format in the // labels property of the chart labels: { formatter: function() { return Highcharts.dateFormat('%H:%M %d %b %Y', this.value); } } }, yAxis: { title: { text: 'Reading (in units)' } }, series: [{ data: [ 12.2, 54.5, 39.1, 29.9, 100, 35.4, 93.7, 106.4, 150, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 84.7, 122.9, 137.4, 135.2, 163.1, 195.2, 195.1, 182.7, 174.3, 201.8, 199.2, ], pointStart: Date.UTC(2010, 0, 1), pointInterval: 3600 * 1000 // one hour }]});",
"e": 31061,
"s": 30218,
"text": null
},
{
"code": null,
"e": 31070,
"s": 31061,
"text": "Output: "
},
{
"code": null,
"e": 31144,
"s": 31070,
"text": "The above chart now displays the dates along with the time on the x-axis."
},
{
"code": null,
"e": 31274,
"s": 31144,
"text": "References:https://api.highcharts.com/highcharts/xAxis.dateTimeLabelFormatshttps://www.highcharts.com/forum/viewtopic.php?t=13389"
},
{
"code": null,
"e": 31289,
"s": 31274,
"text": "amarjeet_singh"
},
{
"code": null,
"e": 31305,
"s": 31289,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 31312,
"s": 31305,
"text": "Picked"
},
{
"code": null,
"e": 31317,
"s": 31312,
"text": "HTML"
},
{
"code": null,
"e": 31328,
"s": 31317,
"text": "JavaScript"
},
{
"code": null,
"e": 31345,
"s": 31328,
"text": "Web Technologies"
},
{
"code": null,
"e": 31372,
"s": 31345,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 31377,
"s": 31372,
"text": "HTML"
},
{
"code": null,
"e": 31475,
"s": 31377,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31523,
"s": 31475,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31547,
"s": 31523,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 31597,
"s": 31547,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 31647,
"s": 31597,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 31684,
"s": 31647,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 31724,
"s": 31684,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31769,
"s": 31724,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31830,
"s": 31769,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31902,
"s": 31830,
"text": "Differences between Functional Components and Class Components in React"
}
] |
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks | 28 Jun, 2021
Consider the following policies for preventing deadlock in a system with mutually exclusive resources.
I. Processes should acquire all their resources at the
beginning of execution. If any resource is not
available, all resources acquired so far are released.
II. The resources are numbered uniquely, and processes are
allowed to request for resources only in increasing
resource numbers.
III. The resources are numbered uniquely, and processes are
allowed to request for resources only in decreasing
resource numbers.
IV. The resources are numbered uniquely. A process is allowed
to request only for a resource with resource number larger
than its currently held resources.
Which of the above policies can be used for preventing deadlock?(A) Any one of I and III but not II or IV(B) Any one of I, III and IV but not II(C) Any one of II and III but not I or IV(D) Any one of I, II, III and IVAnswer: (D)Explanation: If Ist is followed, then hold and wait will never happen.
II, III and IV are similar. If any of these is followed, cyclic wait will not be possible.Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
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-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25839,
"s": 25811,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25942,
"s": 25839,
"text": "Consider the following policies for preventing deadlock in a system with mutually exclusive resources."
},
{
"code": null,
"e": 26554,
"s": 25942,
"text": "I. Processes should acquire all their resources at the \n beginning of execution. If any resource is not \n available, all resources acquired so far are released.\nII. The resources are numbered uniquely, and processes are \n allowed to request for resources only in increasing \n resource numbers.\nIII. The resources are numbered uniquely, and processes are\n allowed to request for resources only in decreasing \n resource numbers.\nIV. The resources are numbered uniquely. A process is allowed\n to request only for a resource with resource number larger\n than its currently held resources."
},
{
"code": null,
"e": 26853,
"s": 26554,
"text": "Which of the above policies can be used for preventing deadlock?(A) Any one of I and III but not II or IV(B) Any one of I, III and IV but not II(C) Any one of II and III but not I or IV(D) Any one of I, II, III and IVAnswer: (D)Explanation: If Ist is followed, then hold and wait will never happen."
},
{
"code": null,
"e": 26965,
"s": 26853,
"text": "II, III and IV are similar. If any of these is followed, cyclic wait will not be possible.Quiz of this Question"
},
{
"code": null,
"e": 26986,
"s": 26965,
"text": "GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 27012,
"s": 26986,
"text": "GATE-GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 27017,
"s": 27012,
"text": "GATE"
},
{
"code": null,
"e": 27115,
"s": 27017,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27149,
"s": 27115,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 27183,
"s": 27149,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 27217,
"s": 27183,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 27250,
"s": 27217,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 27286,
"s": 27250,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 27320,
"s": 27286,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 27356,
"s": 27320,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 27390,
"s": 27356,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 27424,
"s": 27390,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Find the Number Occurring Odd Number of Times - GeeksforGeeks | 09 Dec, 2021
Given an array of positive integers. All numbers occur an even number of times except one number which occurs an odd number of times. Find the number in O(n) time & constant space.
Examples :
Input : arr = {1, 2, 3, 2, 3, 1, 3}
Output : 3
Input : arr = {5, 7, 2, 7, 5, 2, 5}
Output : 5
A Simple Solution is to run two nested loops. The outer loop picks all elements one by one and the inner loop counts the number of occurrences of the element picked by the outer loop. The time complexity of this solution is O(n2).
Below is the implementation of the brute force approach :
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the element// occurring odd number of times#include<bits/stdc++.h>using namespace std; // Function to find the element// occurring odd number of timesint getOddOccurrence(int arr[], int arr_size){ for (int i = 0; i < arr_size; i++) { int count = 0; for (int j = 0; j < arr_size; j++) { if (arr[i] == arr[j]) count++; } if (count % 2 != 0) return arr[i]; } return -1;} // driver codeint main() { int arr[] = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << getOddOccurrence(arr, n); return 0; }
// Java program to find the element occurring// odd number of timesclass OddOccurrence { // function to find the element occurring odd // number of times static int getOddOccurrence(int arr[], int arr_size) { int i; for (i = 0; i < arr_size; i++) { int count = 0; for (int j = 0; j < arr_size; j++) { if (arr[i] == arr[j]) count++; } if (count % 2 != 0) return arr[i]; } return -1; } // driver code public static void main(String[] args) { int arr[] = new int[]{ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = arr.length; System.out.println(getOddOccurrence(arr, n)); }}// This code has been contributed by Kamal Rawal
# Python program to find the element occurring# odd number of times # function to find the element occurring odd# number of timesdef getOddOccurrence(arr, arr_size): for i in range(0,arr_size): count = 0 for j in range(0, arr_size): if arr[i] == arr[j]: count+=1 if (count % 2 != 0): return arr[i] return -1 # driver codearr = [2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 ]n = len(arr)print(getOddOccurrence(arr, n)) # This code has been contributed by# Smitha Dinesh Semwal
// C# program to find the element// occurring odd number of timesusing System; class GFG{ // Function to find the element // occurring odd number of times static int getOddOccurrence(int []arr, int arr_size) { for (int i = 0; i < arr_size; i++) { int count = 0; for (int j = 0; j < arr_size; j++) { if (arr[i] == arr[j]) count++; } if (count % 2 != 0) return arr[i]; } return -1; } // Driver code public static void Main() { int []arr = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = arr.Length; Console.Write(getOddOccurrence(arr, n)); }} // This code is contributed by Sam007
<?php// PHP program to find the// element occurring odd// number of times // Function to find the element// occurring odd number of timesfunction getOddOccurrence(&$arr, $arr_size){ $count = 0; for ($i = 0; $i < $arr_size; $i++) { for ($j = 0; $j < $arr_size; $j++) { if ($arr[$i] == $arr[$j]) $count++; } if ($count % 2 != 0) return $arr[$i]; } return -1;} // Driver code$arr = array(2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2);$n = sizeof($arr); // Function callingecho(getOddOccurrence($arr, $n)); // This code is contributed// by Shivi_Aggarwal?>
<script> // Javascript program to find the element// occurring odd number of times // Function to find the element// occurring odd number of timesfunction getOddOccurrence(arr, arr_size){ for (let i = 0; i < arr_size; i++) { let count = 0; for (let j = 0; j < arr_size; j++) { if (arr[i] == arr[j]) count++; } if (count % 2 != 0) return arr[i]; } return -1;} // driver code let arr = [ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 ]; let n = arr.length; // Function calling document.write(getOddOccurrence(arr, n)); // This code is contributed by Mayank Tyagi </script>
Output :
5
Time Complexity: O(n^2)
Auxiliary Space: O(1)
A Better Solution is to use Hashing. Use array elements as a key and their counts as values. Create an empty hash table. One by one traverse the given array elements and store counts. The time complexity of this solution is O(n). But it requires extra space for hashing.
Program :
C++
Java
Python3
C#
Javascript
// C++ program to find the element // occurring odd number of times#include <bits/stdc++.h>using namespace std; // function to find the element// occurring odd number of timesint getOddOccurrence(int arr[],int size){ // Defining HashMap in C++ unordered_map<int, int> hash; // Putting all elements into the HashMap for(int i = 0; i < size; i++) { hash[arr[i]]++; } // Iterate through HashMap to check an element // occurring odd number of times and return it for(auto i : hash) { if(i.second % 2 != 0) { return i.first; } } return -1;} // Driver codeint main(){ int arr[] = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << getOddOccurrence(arr, n); return 0;} // This code is contributed by codeMan_d.
// Java program to find the element occurring odd// number of timesimport java.io.*;import java.util.HashMap; class OddOccurrence{ // function to find the element occurring odd // number of times static int getOddOccurrence(int arr[], int n) { HashMap<Integer,Integer> hmap = new HashMap<>(); // Putting all elements into the HashMap for(int i = 0; i < n; i++) { if(hmap.containsKey(arr[i])) { int val = hmap.get(arr[i]); // If array element is already present then // increase the count of that element. hmap.put(arr[i], val + 1); } else // if array element is not present then put // element into the HashMap and initialize // the count to one. hmap.put(arr[i], 1); } // Checking for odd occurrence of each element present // in the HashMap for(Integer a:hmap.keySet()) { if(hmap.get(a) % 2 != 0) return a; } return -1; } // driver code public static void main(String[] args) { int arr[] = new int[]{2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}; int n = arr.length; System.out.println(getOddOccurrence(arr, n)); }}// This code is contributed by Kamal Rawal
# Python3 program to find the element # occurring odd number of times # function to find the element# occurring odd number of timesdef getOddOccurrence(arr,size): # Defining HashMap in C++ Hash=dict() # Putting all elements into the HashMap for i in range(size): Hash[arr[i]]=Hash.get(arr[i],0) + 1; # Iterate through HashMap to check an element # occurring odd number of times and return it for i in Hash: if(Hash[i]% 2 != 0): return i return -1 # Driver codearr=[2, 3, 5, 4, 5, 2, 4,3, 5, 2, 4, 4, 2]n = len(arr) # Function callingprint(getOddOccurrence(arr, n)) # This code is contributed by mohit kumar
// C# program to find the element occurring odd// number of timesusing System;using System.Collections.Generic; public class OddOccurrence{ // function to find the element occurring odd // number of times static int getOddOccurrence(int []arr, int n) { Dictionary<int,int> hmap = new Dictionary<int,int>(); // Putting all elements into the HashMap for(int i = 0; i < n; i++) { if(hmap.ContainsKey(arr[i])) { int val = hmap[arr[i]]; // If array element is already present then // increase the count of that element. hmap.Remove(arr[i]); hmap.Add(arr[i], val + 1); } else // if array element is not present then put // element into the HashMap and initialize // the count to one. hmap.Add(arr[i], 1); } // Checking for odd occurrence of each element present // in the HashMap foreach(KeyValuePair<int, int> entry in hmap) { if(entry.Value % 2 != 0) { return entry.Key; } } return -1; } // Driver code public static void Main(String[] args) { int []arr = new int[]{2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}; int n = arr.Length; Console.WriteLine(getOddOccurrence(arr, n)); }} // This code is contributed by Princi Singh
<script>// Javascript program to find the element occurring odd// number of times // function to find the element occurring odd // number of times function getOddOccurrence(arr,n) { let hmap = new Map(); // Putting all elements into the HashMap for(let i = 0; i < n; i++) { if(hmap.has(arr[i])) { let val = hmap.get(arr[i]); // If array element is already present then // increase the count of that element. hmap.set(arr[i], val + 1); } else { // if array element is not present then put // element into the HashMap and initialize // the count to one. hmap.set(arr[i], 1); } } // Checking for odd occurrence of each element present // in the HashMap for(let [key, value] of hmap.entries()) { //document.write(hmap[a]+"<br>") if(hmap.get(key) % 2 != 0) return key; } return -1; } // driver code let arr=[2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2]; let n = arr.length; document.write(getOddOccurrence(arr, n)); // This code is contributed by unknown2108</script>
Output :
5
Time Complexity: O(n)
Auxiliary Space: O(n)
The Best Solution is to do bitwise XOR of all the elements. XOR of all elements gives us odd occurring elements. Please note that the XOR of two elements is 0 if both elements are the same and the XOR of a number x with 0 is x.
Below is the implementation of the above approach.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find the element// occurring odd number of times#include <bits/stdc++.h>using namespace std; // Function to find element occurring// odd number of timesint getOddOccurrence(int ar[], int ar_size){ int res = 0; for (int i = 0; i < ar_size; i++) res = res ^ ar[i]; return res;} /* Driver function to test above function */int main(){ int ar[] = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}; int n = sizeof(ar)/sizeof(ar[0]); // Function calling cout << getOddOccurrence(ar, n); return 0;}
// C program to find the element// occurring odd number of times#include <stdio.h> // Function to find element occurring// odd number of timesint getOddOccurrence(int ar[], int ar_size){ int res = 0; for (int i = 0; i < ar_size; i++) res = res ^ ar[i]; return res;} /* Driver function to test above function */int main(){ int ar[] = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}; int n = sizeof(ar) / sizeof(ar[0]); // Function calling printf("%d", getOddOccurrence(ar, n)); return 0;}
//Java program to find the element occurring odd number of times class OddOccurance{ int getOddOccurrence(int ar[], int ar_size) { int i; int res = 0; for (i = 0; i < ar_size; i++) { res = res ^ ar[i]; } return res; } public static void main(String[] args) { OddOccurance occur = new OddOccurance(); int ar[] = new int[]{2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}; int n = ar.length; System.out.println(occur.getOddOccurrence(ar, n)); }}// This code has been contributed by Mayank Jaiswal
# Python program to find the element occurring odd number of times def getOddOccurrence(arr): # Initialize result res = 0 # Traverse the array for element in arr: # XOR with the result res = res ^ element return res # Test arrayarr = [ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2] print("%d" % getOddOccurrence(arr))
// C# program to find the element// occurring odd number of timesusing System; class GFG{ // Function to find the element // occurring odd number of times static int getOddOccurrence(int []arr, int arr_size) { int res = 0; for (int i = 0; i < arr_size; i++) { res = res ^ arr[i]; } return res; } // Driver code public static void Main() { int []arr = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = arr.Length; Console.Write(getOddOccurrence(arr, n)); }} // This code is contributed by Sam007
<?php// PHP program to find the// element occurring odd// number of times // Function to find element// occurring odd number of timesfunction getOddOccurrence(&$ar, $ar_size){ $res = 0; for ($i = 0; $i < $ar_size; $i++) $res = $res ^ $ar[$i]; return $res;} // Driver Code$ar = array(2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2);$n = sizeof($ar); // Function callingecho(getOddOccurrence($ar, $n)); // This code is contributed// by Shivi_Aggarwal?>
<script> // JavaScript program to find the element// occurring odd number of times // Function to find the element// occurring odd number of timesfunction getOddOccurrence( ar, ar_size){ let res = 0; for (let i = 0; i < ar_size; i++) res = res ^ ar[i]; return res;} // driver code let arr = [ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 ]; let n = arr.length; // Function calling document.write(getOddOccurrence(arr, n)); </script>
Output :
5
Time Complexity: O(n)
Auxiliary Space: O(1)
Count the frequencies of every element using the Counter function
Traverse in frequency dictionary
Check which element has an odd frequency.
Print that element and break the loop
Below is the implementation:
Python3
# importing counter from collectionsfrom collections import Counter # Python3 implementation to find# odd frequency elementdef oddElement(arr, n): # Calculating frequencies using Counter count_map = Counter(arr) for i in range(0, n): # If count of element is odd we return if (count_map[arr[i]] % 2 != 0): return arr[i] # Driver Codeif __name__ == "__main__": arr = [1, 1, 3, 3, 5, 6, 6] n = len(arr) print(oddElement(arr, n)) # This code is contributed by vikkycirus
Output:
5
Time Complexity: O(N)
Auxiliary Space: O(1)
YouTubeGeeksforGeeks507K subscribersFind the Number Occurring Odd Number of Times | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:28•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=hySR1exD5PE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Shivi_Aggarwal
codeMan_d
mohit kumar 29
shubham_singh
princi singh
nidhi_biet
mayanktyagi1709
vikkycirus
jana_sayantan
unknown2108
simranarora5sos
rishavmahato348
souravmahato348
shrutigptt99
Amazon
Bitwise-XOR
Snapdeal
Arrays
Bit Magic
Hash
Amazon
Snapdeal
Arrays
Hash
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable? | [
{
"code": null,
"e": 26325,
"s": 26297,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 26506,
"s": 26325,
"text": "Given an array of positive integers. All numbers occur an even number of times except one number which occurs an odd number of times. Find the number in O(n) time & constant space."
},
{
"code": null,
"e": 26518,
"s": 26506,
"text": "Examples : "
},
{
"code": null,
"e": 26613,
"s": 26518,
"text": "Input : arr = {1, 2, 3, 2, 3, 1, 3}\nOutput : 3\n\nInput : arr = {5, 7, 2, 7, 5, 2, 5}\nOutput : 5"
},
{
"code": null,
"e": 26844,
"s": 26613,
"text": "A Simple Solution is to run two nested loops. The outer loop picks all elements one by one and the inner loop counts the number of occurrences of the element picked by the outer loop. The time complexity of this solution is O(n2)."
},
{
"code": null,
"e": 26903,
"s": 26844,
"text": "Below is the implementation of the brute force approach : "
},
{
"code": null,
"e": 26907,
"s": 26903,
"text": "C++"
},
{
"code": null,
"e": 26912,
"s": 26907,
"text": "Java"
},
{
"code": null,
"e": 26920,
"s": 26912,
"text": "Python3"
},
{
"code": null,
"e": 26923,
"s": 26920,
"text": "C#"
},
{
"code": null,
"e": 26927,
"s": 26923,
"text": "PHP"
},
{
"code": null,
"e": 26938,
"s": 26927,
"text": "Javascript"
},
{
"code": "// C++ program to find the element// occurring odd number of times#include<bits/stdc++.h>using namespace std; // Function to find the element// occurring odd number of timesint getOddOccurrence(int arr[], int arr_size){ for (int i = 0; i < arr_size; i++) { int count = 0; for (int j = 0; j < arr_size; j++) { if (arr[i] == arr[j]) count++; } if (count % 2 != 0) return arr[i]; } return -1;} // driver codeint main() { int arr[] = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << getOddOccurrence(arr, n); return 0; }",
"e": 27678,
"s": 26938,
"text": null
},
{
"code": "// Java program to find the element occurring// odd number of timesclass OddOccurrence { // function to find the element occurring odd // number of times static int getOddOccurrence(int arr[], int arr_size) { int i; for (i = 0; i < arr_size; i++) { int count = 0; for (int j = 0; j < arr_size; j++) { if (arr[i] == arr[j]) count++; } if (count % 2 != 0) return arr[i]; } return -1; } // driver code public static void main(String[] args) { int arr[] = new int[]{ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = arr.length; System.out.println(getOddOccurrence(arr, n)); }}// This code has been contributed by Kamal Rawal",
"e": 28478,
"s": 27678,
"text": null
},
{
"code": "# Python program to find the element occurring# odd number of times # function to find the element occurring odd# number of timesdef getOddOccurrence(arr, arr_size): for i in range(0,arr_size): count = 0 for j in range(0, arr_size): if arr[i] == arr[j]: count+=1 if (count % 2 != 0): return arr[i] return -1 # driver codearr = [2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 ]n = len(arr)print(getOddOccurrence(arr, n)) # This code has been contributed by# Smitha Dinesh Semwal",
"e": 29051,
"s": 28478,
"text": null
},
{
"code": "// C# program to find the element// occurring odd number of timesusing System; class GFG{ // Function to find the element // occurring odd number of times static int getOddOccurrence(int []arr, int arr_size) { for (int i = 0; i < arr_size; i++) { int count = 0; for (int j = 0; j < arr_size; j++) { if (arr[i] == arr[j]) count++; } if (count % 2 != 0) return arr[i]; } return -1; } // Driver code public static void Main() { int []arr = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = arr.Length; Console.Write(getOddOccurrence(arr, n)); }} // This code is contributed by Sam007",
"e": 29813,
"s": 29051,
"text": null
},
{
"code": "<?php// PHP program to find the// element occurring odd// number of times // Function to find the element// occurring odd number of timesfunction getOddOccurrence(&$arr, $arr_size){ $count = 0; for ($i = 0; $i < $arr_size; $i++) { for ($j = 0; $j < $arr_size; $j++) { if ($arr[$i] == $arr[$j]) $count++; } if ($count % 2 != 0) return $arr[$i]; } return -1;} // Driver code$arr = array(2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2);$n = sizeof($arr); // Function callingecho(getOddOccurrence($arr, $n)); // This code is contributed// by Shivi_Aggarwal?>",
"e": 30480,
"s": 29813,
"text": null
},
{
"code": "<script> // Javascript program to find the element// occurring odd number of times // Function to find the element// occurring odd number of timesfunction getOddOccurrence(arr, arr_size){ for (let i = 0; i < arr_size; i++) { let count = 0; for (let j = 0; j < arr_size; j++) { if (arr[i] == arr[j]) count++; } if (count % 2 != 0) return arr[i]; } return -1;} // driver code let arr = [ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 ]; let n = arr.length; // Function calling document.write(getOddOccurrence(arr, n)); // This code is contributed by Mayank Tyagi </script>",
"e": 31191,
"s": 30480,
"text": null
},
{
"code": null,
"e": 31202,
"s": 31191,
"text": "Output : "
},
{
"code": null,
"e": 31204,
"s": 31202,
"text": "5"
},
{
"code": null,
"e": 31228,
"s": 31204,
"text": "Time Complexity: O(n^2)"
},
{
"code": null,
"e": 31250,
"s": 31228,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31521,
"s": 31250,
"text": "A Better Solution is to use Hashing. Use array elements as a key and their counts as values. Create an empty hash table. One by one traverse the given array elements and store counts. The time complexity of this solution is O(n). But it requires extra space for hashing."
},
{
"code": null,
"e": 31532,
"s": 31521,
"text": "Program : "
},
{
"code": null,
"e": 31536,
"s": 31532,
"text": "C++"
},
{
"code": null,
"e": 31541,
"s": 31536,
"text": "Java"
},
{
"code": null,
"e": 31549,
"s": 31541,
"text": "Python3"
},
{
"code": null,
"e": 31552,
"s": 31549,
"text": "C#"
},
{
"code": null,
"e": 31563,
"s": 31552,
"text": "Javascript"
},
{
"code": "// C++ program to find the element // occurring odd number of times#include <bits/stdc++.h>using namespace std; // function to find the element// occurring odd number of timesint getOddOccurrence(int arr[],int size){ // Defining HashMap in C++ unordered_map<int, int> hash; // Putting all elements into the HashMap for(int i = 0; i < size; i++) { hash[arr[i]]++; } // Iterate through HashMap to check an element // occurring odd number of times and return it for(auto i : hash) { if(i.second % 2 != 0) { return i.first; } } return -1;} // Driver codeint main(){ int arr[] = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << getOddOccurrence(arr, n); return 0;} // This code is contributed by codeMan_d.",
"e": 32446,
"s": 31563,
"text": null
},
{
"code": "// Java program to find the element occurring odd// number of timesimport java.io.*;import java.util.HashMap; class OddOccurrence{ // function to find the element occurring odd // number of times static int getOddOccurrence(int arr[], int n) { HashMap<Integer,Integer> hmap = new HashMap<>(); // Putting all elements into the HashMap for(int i = 0; i < n; i++) { if(hmap.containsKey(arr[i])) { int val = hmap.get(arr[i]); // If array element is already present then // increase the count of that element. hmap.put(arr[i], val + 1); } else // if array element is not present then put // element into the HashMap and initialize // the count to one. hmap.put(arr[i], 1); } // Checking for odd occurrence of each element present // in the HashMap for(Integer a:hmap.keySet()) { if(hmap.get(a) % 2 != 0) return a; } return -1; } // driver code public static void main(String[] args) { int arr[] = new int[]{2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}; int n = arr.length; System.out.println(getOddOccurrence(arr, n)); }}// This code is contributed by Kamal Rawal",
"e": 33878,
"s": 32446,
"text": null
},
{
"code": "# Python3 program to find the element # occurring odd number of times # function to find the element# occurring odd number of timesdef getOddOccurrence(arr,size): # Defining HashMap in C++ Hash=dict() # Putting all elements into the HashMap for i in range(size): Hash[arr[i]]=Hash.get(arr[i],0) + 1; # Iterate through HashMap to check an element # occurring odd number of times and return it for i in Hash: if(Hash[i]% 2 != 0): return i return -1 # Driver codearr=[2, 3, 5, 4, 5, 2, 4,3, 5, 2, 4, 4, 2]n = len(arr) # Function callingprint(getOddOccurrence(arr, n)) # This code is contributed by mohit kumar",
"e": 34552,
"s": 33878,
"text": null
},
{
"code": "// C# program to find the element occurring odd// number of timesusing System;using System.Collections.Generic; public class OddOccurrence{ // function to find the element occurring odd // number of times static int getOddOccurrence(int []arr, int n) { Dictionary<int,int> hmap = new Dictionary<int,int>(); // Putting all elements into the HashMap for(int i = 0; i < n; i++) { if(hmap.ContainsKey(arr[i])) { int val = hmap[arr[i]]; // If array element is already present then // increase the count of that element. hmap.Remove(arr[i]); hmap.Add(arr[i], val + 1); } else // if array element is not present then put // element into the HashMap and initialize // the count to one. hmap.Add(arr[i], 1); } // Checking for odd occurrence of each element present // in the HashMap foreach(KeyValuePair<int, int> entry in hmap) { if(entry.Value % 2 != 0) { return entry.Key; } } return -1; } // Driver code public static void Main(String[] args) { int []arr = new int[]{2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}; int n = arr.Length; Console.WriteLine(getOddOccurrence(arr, n)); }} // This code is contributed by Princi Singh",
"e": 36079,
"s": 34552,
"text": null
},
{
"code": "<script>// Javascript program to find the element occurring odd// number of times // function to find the element occurring odd // number of times function getOddOccurrence(arr,n) { let hmap = new Map(); // Putting all elements into the HashMap for(let i = 0; i < n; i++) { if(hmap.has(arr[i])) { let val = hmap.get(arr[i]); // If array element is already present then // increase the count of that element. hmap.set(arr[i], val + 1); } else { // if array element is not present then put // element into the HashMap and initialize // the count to one. hmap.set(arr[i], 1); } } // Checking for odd occurrence of each element present // in the HashMap for(let [key, value] of hmap.entries()) { //document.write(hmap[a]+\"<br>\") if(hmap.get(key) % 2 != 0) return key; } return -1; } // driver code let arr=[2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2]; let n = arr.length; document.write(getOddOccurrence(arr, n)); // This code is contributed by unknown2108</script>",
"e": 37413,
"s": 36079,
"text": null
},
{
"code": null,
"e": 37423,
"s": 37413,
"text": "Output : "
},
{
"code": null,
"e": 37425,
"s": 37423,
"text": "5"
},
{
"code": null,
"e": 37447,
"s": 37425,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 37469,
"s": 37447,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 37697,
"s": 37469,
"text": "The Best Solution is to do bitwise XOR of all the elements. XOR of all elements gives us odd occurring elements. Please note that the XOR of two elements is 0 if both elements are the same and the XOR of a number x with 0 is x."
},
{
"code": null,
"e": 37750,
"s": 37697,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 37754,
"s": 37750,
"text": "C++"
},
{
"code": null,
"e": 37756,
"s": 37754,
"text": "C"
},
{
"code": null,
"e": 37761,
"s": 37756,
"text": "Java"
},
{
"code": null,
"e": 37769,
"s": 37761,
"text": "Python3"
},
{
"code": null,
"e": 37772,
"s": 37769,
"text": "C#"
},
{
"code": null,
"e": 37776,
"s": 37772,
"text": "PHP"
},
{
"code": null,
"e": 37787,
"s": 37776,
"text": "Javascript"
},
{
"code": "// C++ program to find the element// occurring odd number of times#include <bits/stdc++.h>using namespace std; // Function to find element occurring// odd number of timesint getOddOccurrence(int ar[], int ar_size){ int res = 0; for (int i = 0; i < ar_size; i++) res = res ^ ar[i]; return res;} /* Driver function to test above function */int main(){ int ar[] = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}; int n = sizeof(ar)/sizeof(ar[0]); // Function calling cout << getOddOccurrence(ar, n); return 0;}",
"e": 38337,
"s": 37787,
"text": null
},
{
"code": "// C program to find the element// occurring odd number of times#include <stdio.h> // Function to find element occurring// odd number of timesint getOddOccurrence(int ar[], int ar_size){ int res = 0; for (int i = 0; i < ar_size; i++) res = res ^ ar[i]; return res;} /* Driver function to test above function */int main(){ int ar[] = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}; int n = sizeof(ar) / sizeof(ar[0]); // Function calling printf(\"%d\", getOddOccurrence(ar, n)); return 0;}",
"e": 38862,
"s": 38337,
"text": null
},
{
"code": "//Java program to find the element occurring odd number of times class OddOccurance{ int getOddOccurrence(int ar[], int ar_size) { int i; int res = 0; for (i = 0; i < ar_size; i++) { res = res ^ ar[i]; } return res; } public static void main(String[] args) { OddOccurance occur = new OddOccurance(); int ar[] = new int[]{2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}; int n = ar.length; System.out.println(occur.getOddOccurrence(ar, n)); }}// This code has been contributed by Mayank Jaiswal",
"e": 39447,
"s": 38862,
"text": null
},
{
"code": "# Python program to find the element occurring odd number of times def getOddOccurrence(arr): # Initialize result res = 0 # Traverse the array for element in arr: # XOR with the result res = res ^ element return res # Test arrayarr = [ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2] print(\"%d\" % getOddOccurrence(arr))",
"e": 39794,
"s": 39447,
"text": null
},
{
"code": "// C# program to find the element// occurring odd number of timesusing System; class GFG{ // Function to find the element // occurring odd number of times static int getOddOccurrence(int []arr, int arr_size) { int res = 0; for (int i = 0; i < arr_size; i++) { res = res ^ arr[i]; } return res; } // Driver code public static void Main() { int []arr = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = arr.Length; Console.Write(getOddOccurrence(arr, n)); }} // This code is contributed by Sam007",
"e": 40389,
"s": 39794,
"text": null
},
{
"code": "<?php// PHP program to find the// element occurring odd// number of times // Function to find element// occurring odd number of timesfunction getOddOccurrence(&$ar, $ar_size){ $res = 0; for ($i = 0; $i < $ar_size; $i++) $res = $res ^ $ar[$i]; return $res;} // Driver Code$ar = array(2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2);$n = sizeof($ar); // Function callingecho(getOddOccurrence($ar, $n)); // This code is contributed// by Shivi_Aggarwal?>",
"e": 40871,
"s": 40389,
"text": null
},
{
"code": "<script> // JavaScript program to find the element// occurring odd number of times // Function to find the element// occurring odd number of timesfunction getOddOccurrence( ar, ar_size){ let res = 0; for (let i = 0; i < ar_size; i++) res = res ^ ar[i]; return res;} // driver code let arr = [ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 ]; let n = arr.length; // Function calling document.write(getOddOccurrence(arr, n)); </script>",
"e": 41361,
"s": 40871,
"text": null
},
{
"code": null,
"e": 41370,
"s": 41361,
"text": "Output :"
},
{
"code": null,
"e": 41372,
"s": 41370,
"text": "5"
},
{
"code": null,
"e": 41394,
"s": 41372,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 41416,
"s": 41394,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 41482,
"s": 41416,
"text": "Count the frequencies of every element using the Counter function"
},
{
"code": null,
"e": 41515,
"s": 41482,
"text": "Traverse in frequency dictionary"
},
{
"code": null,
"e": 41557,
"s": 41515,
"text": "Check which element has an odd frequency."
},
{
"code": null,
"e": 41595,
"s": 41557,
"text": "Print that element and break the loop"
},
{
"code": null,
"e": 41624,
"s": 41595,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 41632,
"s": 41624,
"text": "Python3"
},
{
"code": "# importing counter from collectionsfrom collections import Counter # Python3 implementation to find# odd frequency elementdef oddElement(arr, n): # Calculating frequencies using Counter count_map = Counter(arr) for i in range(0, n): # If count of element is odd we return if (count_map[arr[i]] % 2 != 0): return arr[i] # Driver Codeif __name__ == \"__main__\": arr = [1, 1, 3, 3, 5, 6, 6] n = len(arr) print(oddElement(arr, n)) # This code is contributed by vikkycirus",
"e": 42148,
"s": 41632,
"text": null
},
{
"code": null,
"e": 42156,
"s": 42148,
"text": "Output:"
},
{
"code": null,
"e": 42158,
"s": 42156,
"text": "5"
},
{
"code": null,
"e": 42180,
"s": 42158,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 42202,
"s": 42180,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 43046,
"s": 42202,
"text": "YouTubeGeeksforGeeks507K subscribersFind the Number Occurring Odd Number of Times | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:28•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=hySR1exD5PE\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 43171,
"s": 43046,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 43186,
"s": 43171,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 43196,
"s": 43186,
"text": "codeMan_d"
},
{
"code": null,
"e": 43211,
"s": 43196,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 43225,
"s": 43211,
"text": "shubham_singh"
},
{
"code": null,
"e": 43238,
"s": 43225,
"text": "princi singh"
},
{
"code": null,
"e": 43249,
"s": 43238,
"text": "nidhi_biet"
},
{
"code": null,
"e": 43265,
"s": 43249,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 43276,
"s": 43265,
"text": "vikkycirus"
},
{
"code": null,
"e": 43290,
"s": 43276,
"text": "jana_sayantan"
},
{
"code": null,
"e": 43302,
"s": 43290,
"text": "unknown2108"
},
{
"code": null,
"e": 43318,
"s": 43302,
"text": "simranarora5sos"
},
{
"code": null,
"e": 43334,
"s": 43318,
"text": "rishavmahato348"
},
{
"code": null,
"e": 43350,
"s": 43334,
"text": "souravmahato348"
},
{
"code": null,
"e": 43363,
"s": 43350,
"text": "shrutigptt99"
},
{
"code": null,
"e": 43370,
"s": 43363,
"text": "Amazon"
},
{
"code": null,
"e": 43382,
"s": 43370,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 43391,
"s": 43382,
"text": "Snapdeal"
},
{
"code": null,
"e": 43398,
"s": 43391,
"text": "Arrays"
},
{
"code": null,
"e": 43408,
"s": 43398,
"text": "Bit Magic"
},
{
"code": null,
"e": 43413,
"s": 43408,
"text": "Hash"
},
{
"code": null,
"e": 43420,
"s": 43413,
"text": "Amazon"
},
{
"code": null,
"e": 43429,
"s": 43420,
"text": "Snapdeal"
},
{
"code": null,
"e": 43436,
"s": 43429,
"text": "Arrays"
},
{
"code": null,
"e": 43441,
"s": 43436,
"text": "Hash"
},
{
"code": null,
"e": 43451,
"s": 43441,
"text": "Bit Magic"
},
{
"code": null,
"e": 43549,
"s": 43451,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43617,
"s": 43549,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 43661,
"s": 43617,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 43709,
"s": 43661,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 43732,
"s": 43709,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 43764,
"s": 43732,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 43791,
"s": 43764,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 43837,
"s": 43791,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 43905,
"s": 43837,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 43934,
"s": 43905,
"text": "Count set bits in an integer"
}
] |
Scopes in Kotlin Coroutines - GeeksforGeeks | 15 Oct, 2021
Prerequisites:
Kotlin Coroutines on Android
Suspend Function In Kotlin Coroutines
Scope in Kotlin’s coroutines can be defined as the restrictions within which the Kotlin coroutines are being executed. Scopes help to predict the lifecycle of the coroutines. There are basically 3 scopes in Kotlin coroutines:
Global ScopeLifeCycle ScopeViewModel Scope
Global Scope
LifeCycle Scope
ViewModel Scope
Import following dependencies to build.gradle (app) level file.
implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.5’
implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.5’
def arch_version = ‘2.2.0-alpha01’
implementation “androidx.lifecycle:lifecycle-viewmodel-ktx:$arch_version”
implementation “androidx.lifecycle:lifecycle-runtime-ktx:$arch_version”
Global Scope is one of the ways by which coroutines are launched. When Coroutines are launched within the global scope, they live long as the application does. If the coroutines finish it’s a job, it will be destroyed and will not keep alive until the application dies, but let’s imagine a situation when the coroutines has some work or instruction left to do, and suddenly we end the application, then the coroutines will also die, as the maximum lifetime of the coroutine is equal to the lifetime of the application. Coroutines launched in the global scope will be launched in a separate thread. Below is the example which shows that the in global scope coroutines are launched in a separate thread.
Kotlin
import android.os.Bundleimport android.util.Logimport androidx.appcompat.app.AppCompatActivityimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { val TAG = "Main Activity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) GlobalScope.launch { Log.d(TAG, Thread.currentThread().name.toString()) } Log.d("Outside Global Scope", Thread.currentThread().name.toString()) }}
Below is the Log-Output for the above program:
As it is known that coroutines launched in global scope live as long as the application does, but there are very rare chances when the developer needs the coroutines to be live as long as the application does. The main problem with the coroutines launched in the global scope is that when the activity in which coroutines is launched dies, the coroutines will not die with the activity, since the lifetime of coroutines is decided on the basis of application lifetime, not the activity lifetime. Since the coroutine is using the resources of the activity in which it is launched, and now since that activity has died, the resources will not be garbage collected as a coroutine is still referring to that resources. This problem can lead to a memory leak. So using global scope all the time is not always a good idea. Let’s try to launch a coroutine and run an infinite loop with a delay of 1 sec and launch another coroutine within the global scope after the delay of 5sec from the starting by terminating the first activity and intent to another activity. we can see in the output that even after the first activity is being terminated programmatically, the coroutine associated with the first activity does not die. Let’s try to understand what written in the above paragraph programmatically. Below is the code for both the activity_main.xml and the MainActivity.kt file.
XML
Kotlin
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/btnStartActivity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="167dp" android:layout_marginTop="320dp" android:layout_marginEnd="156dp" android:layout_marginBottom="363dp" android:text="Start Activity" android:textSize="22sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
// program for main activity which intent to another activity// it uses global scope to launch the coroutine import android.content.Intentimport android.os.Bundleimport android.util.Logimport androidx.appcompat.app.AppCompatActivityimport kotlinx.android.synthetic.main.activity_main.*import kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch const val TAG = "Main Activity" class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnStartActivity.setOnClickListener { // coroutine will launch when button got pressed GlobalScope.launch { // infinite loop while (true) { delay(1000L) Log.d(TAG, "Still Running..") } } GlobalScope.launch { delay(5000L) // new activity will get intended after 5 sec val intent = Intent(this@MainActivity, SecondActivity::class.java) startActivity(intent) // calling finish() method,so that first activity will not be alive // after being intended to second activity finish() } } }}
Go to app > java > 1st package name > right-click > New > Activity > Empty Activity to create a new activity and named it as SecondActivity. Below is the code for both the activity_second.xml and SecondActivity.kt file.
XML
Kotlin
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".SecondActivity"> <!--Various attributes for button--> <Button android:id="@+id/btnSecondActivity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="166dp" android:layout_marginTop="331dp" android:layout_marginEnd="130dp" android:layout_marginBottom="352dp" android:gravity="center" android:text="Second Activity" android:textSize="22sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
// program for second activity import android.os.Bundleimport android.util.Logimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class SecondActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) Log.i("Second Activity", "Second Activity Running ....") Toast.makeText(this, "Second Activity", Toast.LENGTH_SHORT).show() }}
Output:
It can be seen in the log out below that even after the second activity is being launched, the coroutine of the main activity is still running. The oval circle is used to show the timestamps.
The lifecycle scope is the same as the global scope, but the only difference is that when we use the lifecycle scope, all the coroutines launched within the activity also dies when the activity dies. It is beneficial as our coroutines will not keep running even after our activity dies. In order to implement the lifecycle scope within our project just launch the coroutine in lifecycle scope instead of global scope, ie just change the global scope to lifecycle scope in the main activity within which the infinite loop is running. All the code will remain the same except for some changes in the code of the main activity as mentioned above.
Kotlin
// program to show how lifecycle scope works import android.content.Intentimport android.os.Bundleimport android.util.Logimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.lifecycleScopeimport kotlinx.android.synthetic.main.activity_main.*import kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch const val TAG = "Main Activity" class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnStartActivity.setOnClickListener { // launching the coroutine in the lifecycle scope lifecycleScope.launch { while (true) { delay(1000L) Log.d(TAG, "Still Running..") } } GlobalScope.launch { delay(5000L) val intent = Intent(this@MainActivity, SecondActivity::class.java) startActivity(intent) finish() } } }}
Log Output:
The oval circle is used to show the timestamps.
It can be seen in the above log output that the main activity stops get printing after the launch of the second activity.
It is also the same as the lifecycle scope, only difference is that the coroutine in this scope will live as long the view model is alive. ViewModel is a class that manages and stores the UI-related data by following the principles of the lifecycle system in android. If one wants to dig deeper into what basically view model class is can refer to this link of android official docs.
kashishsoda
android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
Android RecyclerView in Kotlin
CardView in Android With Example
Broadcast Receiver in Android With Example
Android UI Layouts
Android RecyclerView in Kotlin
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android | [
{
"code": null,
"e": 25347,
"s": 25319,
"text": "\n15 Oct, 2021"
},
{
"code": null,
"e": 25362,
"s": 25347,
"text": "Prerequisites:"
},
{
"code": null,
"e": 25391,
"s": 25362,
"text": "Kotlin Coroutines on Android"
},
{
"code": null,
"e": 25429,
"s": 25391,
"text": "Suspend Function In Kotlin Coroutines"
},
{
"code": null,
"e": 25655,
"s": 25429,
"text": "Scope in Kotlin’s coroutines can be defined as the restrictions within which the Kotlin coroutines are being executed. Scopes help to predict the lifecycle of the coroutines. There are basically 3 scopes in Kotlin coroutines:"
},
{
"code": null,
"e": 25698,
"s": 25655,
"text": "Global ScopeLifeCycle ScopeViewModel Scope"
},
{
"code": null,
"e": 25711,
"s": 25698,
"text": "Global Scope"
},
{
"code": null,
"e": 25727,
"s": 25711,
"text": "LifeCycle Scope"
},
{
"code": null,
"e": 25743,
"s": 25727,
"text": "ViewModel Scope"
},
{
"code": null,
"e": 25807,
"s": 25743,
"text": "Import following dependencies to build.gradle (app) level file."
},
{
"code": null,
"e": 25876,
"s": 25807,
"text": "implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.5’"
},
{
"code": null,
"e": 25948,
"s": 25876,
"text": "implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.5’"
},
{
"code": null,
"e": 25983,
"s": 25948,
"text": "def arch_version = ‘2.2.0-alpha01’"
},
{
"code": null,
"e": 26057,
"s": 25983,
"text": "implementation “androidx.lifecycle:lifecycle-viewmodel-ktx:$arch_version”"
},
{
"code": null,
"e": 26131,
"s": 26057,
"text": "implementation “androidx.lifecycle:lifecycle-runtime-ktx:$arch_version” "
},
{
"code": null,
"e": 26833,
"s": 26131,
"text": "Global Scope is one of the ways by which coroutines are launched. When Coroutines are launched within the global scope, they live long as the application does. If the coroutines finish it’s a job, it will be destroyed and will not keep alive until the application dies, but let’s imagine a situation when the coroutines has some work or instruction left to do, and suddenly we end the application, then the coroutines will also die, as the maximum lifetime of the coroutine is equal to the lifetime of the application. Coroutines launched in the global scope will be launched in a separate thread. Below is the example which shows that the in global scope coroutines are launched in a separate thread."
},
{
"code": null,
"e": 26840,
"s": 26833,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport android.util.Logimport androidx.appcompat.app.AppCompatActivityimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { val TAG = \"Main Activity\" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) GlobalScope.launch { Log.d(TAG, Thread.currentThread().name.toString()) } Log.d(\"Outside Global Scope\", Thread.currentThread().name.toString()) }}",
"e": 27402,
"s": 26840,
"text": null
},
{
"code": null,
"e": 27453,
"s": 27406,
"text": "Below is the Log-Output for the above program:"
},
{
"code": null,
"e": 28832,
"s": 27457,
"text": "As it is known that coroutines launched in global scope live as long as the application does, but there are very rare chances when the developer needs the coroutines to be live as long as the application does. The main problem with the coroutines launched in the global scope is that when the activity in which coroutines is launched dies, the coroutines will not die with the activity, since the lifetime of coroutines is decided on the basis of application lifetime, not the activity lifetime. Since the coroutine is using the resources of the activity in which it is launched, and now since that activity has died, the resources will not be garbage collected as a coroutine is still referring to that resources. This problem can lead to a memory leak. So using global scope all the time is not always a good idea. Let’s try to launch a coroutine and run an infinite loop with a delay of 1 sec and launch another coroutine within the global scope after the delay of 5sec from the starting by terminating the first activity and intent to another activity. we can see in the output that even after the first activity is being terminated programmatically, the coroutine associated with the first activity does not die. Let’s try to understand what written in the above paragraph programmatically. Below is the code for both the activity_main.xml and the MainActivity.kt file."
},
{
"code": null,
"e": 28838,
"s": 28834,
"text": "XML"
},
{
"code": null,
"e": 28845,
"s": 28838,
"text": "Kotlin"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/btnStartActivity\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"167dp\" android:layout_marginTop=\"320dp\" android:layout_marginEnd=\"156dp\" android:layout_marginBottom=\"363dp\" android:text=\"Start Activity\" android:textSize=\"22sp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 29850,
"s": 28845,
"text": null
},
{
"code": "// program for main activity which intent to another activity// it uses global scope to launch the coroutine import android.content.Intentimport android.os.Bundleimport android.util.Logimport androidx.appcompat.app.AppCompatActivityimport kotlinx.android.synthetic.main.activity_main.*import kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch const val TAG = \"Main Activity\" class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnStartActivity.setOnClickListener { // coroutine will launch when button got pressed GlobalScope.launch { // infinite loop while (true) { delay(1000L) Log.d(TAG, \"Still Running..\") } } GlobalScope.launch { delay(5000L) // new activity will get intended after 5 sec val intent = Intent(this@MainActivity, SecondActivity::class.java) startActivity(intent) // calling finish() method,so that first activity will not be alive // after being intended to second activity finish() } } }}",
"e": 31200,
"s": 29850,
"text": null
},
{
"code": null,
"e": 31424,
"s": 31204,
"text": "Go to app > java > 1st package name > right-click > New > Activity > Empty Activity to create a new activity and named it as SecondActivity. Below is the code for both the activity_second.xml and SecondActivity.kt file."
},
{
"code": null,
"e": 31430,
"s": 31426,
"text": "XML"
},
{
"code": null,
"e": 31437,
"s": 31430,
"text": "Kotlin"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".SecondActivity\"> <!--Various attributes for button--> <Button android:id=\"@+id/btnSecondActivity\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"166dp\" android:layout_marginTop=\"331dp\" android:layout_marginEnd=\"130dp\" android:layout_marginBottom=\"352dp\" android:gravity=\"center\" android:text=\"Second Activity\" android:textSize=\"22sp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 32518,
"s": 31437,
"text": null
},
{
"code": "// program for second activity import android.os.Bundleimport android.util.Logimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class SecondActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) Log.i(\"Second Activity\", \"Second Activity Running ....\") Toast.makeText(this, \"Second Activity\", Toast.LENGTH_SHORT).show() }}",
"e": 33006,
"s": 32518,
"text": null
},
{
"code": null,
"e": 33019,
"s": 33010,
"text": "Output: "
},
{
"code": null,
"e": 33215,
"s": 33023,
"text": "It can be seen in the log out below that even after the second activity is being launched, the coroutine of the main activity is still running. The oval circle is used to show the timestamps."
},
{
"code": null,
"e": 33863,
"s": 33219,
"text": "The lifecycle scope is the same as the global scope, but the only difference is that when we use the lifecycle scope, all the coroutines launched within the activity also dies when the activity dies. It is beneficial as our coroutines will not keep running even after our activity dies. In order to implement the lifecycle scope within our project just launch the coroutine in lifecycle scope instead of global scope, ie just change the global scope to lifecycle scope in the main activity within which the infinite loop is running. All the code will remain the same except for some changes in the code of the main activity as mentioned above."
},
{
"code": null,
"e": 33872,
"s": 33865,
"text": "Kotlin"
},
{
"code": "// program to show how lifecycle scope works import android.content.Intentimport android.os.Bundleimport android.util.Logimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.lifecycleScopeimport kotlinx.android.synthetic.main.activity_main.*import kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch const val TAG = \"Main Activity\" class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnStartActivity.setOnClickListener { // launching the coroutine in the lifecycle scope lifecycleScope.launch { while (true) { delay(1000L) Log.d(TAG, \"Still Running..\") } } GlobalScope.launch { delay(5000L) val intent = Intent(this@MainActivity, SecondActivity::class.java) startActivity(intent) finish() } } }}",
"e": 34968,
"s": 33872,
"text": null
},
{
"code": null,
"e": 34985,
"s": 34972,
"text": "Log Output: "
},
{
"code": null,
"e": 35035,
"s": 34987,
"text": "The oval circle is used to show the timestamps."
},
{
"code": null,
"e": 35161,
"s": 35039,
"text": "It can be seen in the above log output that the main activity stops get printing after the launch of the second activity."
},
{
"code": null,
"e": 35550,
"s": 35165,
"text": "It is also the same as the lifecycle scope, only difference is that the coroutine in this scope will live as long the view model is alive. ViewModel is a class that manages and stores the UI-related data by following the principles of the lifecycle system in android. If one wants to dig deeper into what basically view model class is can refer to this link of android official docs. "
},
{
"code": null,
"e": 35564,
"s": 35552,
"text": "kashishsoda"
},
{
"code": null,
"e": 35572,
"s": 35564,
"text": "android"
},
{
"code": null,
"e": 35580,
"s": 35572,
"text": "Android"
},
{
"code": null,
"e": 35587,
"s": 35580,
"text": "Kotlin"
},
{
"code": null,
"e": 35595,
"s": 35587,
"text": "Android"
},
{
"code": null,
"e": 35693,
"s": 35595,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35751,
"s": 35693,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 35794,
"s": 35751,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 35832,
"s": 35794,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 35863,
"s": 35832,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 35896,
"s": 35863,
"text": "CardView in Android With Example"
},
{
"code": null,
"e": 35939,
"s": 35896,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 35958,
"s": 35939,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 35989,
"s": 35958,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 36031,
"s": 35989,
"text": "Content Providers in Android with Example"
}
] |
Difference between Latency and Jitter in OS - GeeksforGeeks | 23 Jun, 2021
What is latency ?The literal meaning of latency is “delay”.
In an operating system , latency is the time between when an interrupt occurs, and when the processor starts to run code to process the interrupt. It is considered as the combined delay between an input or command and therefore the desired output and measured in milliseconds.
A few examples of latencies are –
1. Latency of Networks :The latency of a network is the time delay while reaching some data such as a “knowledge packet” from its source to the destination. It is usually measured in milliseconds. These types of latency tools measure the quantity of time a packet takes as it’s transmitted, processed and then finally reaches its destination after being decoded by the receiving machine.
An allowable range of latency depends upon the network and the bandwidth of the applications used on it. These applications have a varied range of bandwidths. Among them, such as the video calling applications, require more bandwidth and a lower range of latencies to function proficiently. Whereas, some other applications ( for example -Gmail) which allows higher latency range. These factors are taken under consideration by the Network Admins to allocate sufficient resources and bandwidth and guarantee critical operations of the organization run efficiently.
2. Latency of Disks :The time delay between any single input output (I/O) operation on a block device. It looks very simple thing, but is very critical for the performance of the system. These latencies are determined by a few specific calculations such as rotational latency , seek time and transfer time . These factors directly affect the RPMs(rotation per minute) of disks.
Many other sorts of latency exist, like –
RAM latency
CPU latency
Audio latency
Video latency
Within the computing world, these delays are usually only a couple of milliseconds, but they will add up to make noticeable slowdowns in performance.
What are jitters?Operating system jitter (or OS jitter) refers to the interference experienced by an application thanks to scheduling of background daemon processes and handling of asynchronous events like interrupts. It’s been seen that similar applications on mass numbers suffer substantial degradation in performance thanks to OS jitter.Talking in terms of networking , we can say that packets transmitted continuously on the network will have differing delays, albeit they choose an equivalent route. This is often inherent during a packet-switched network for 2 key reasons. First, packets are routed individually. Second, network devices receive packets during a queue, so constant delay pacing can’t be guaranteed.This delay inconsistency between each packet is understood as jitter. It is often a substantial issue for real-time communications, including IP telephony, video conferencing, and virtual desktop infrastructure. Jitter is often caused by many factors on the network, and each network has delay-time variation.
What Effects Does Jitter Have?Packet Loss – When packets don’t arrive consistently, the receiving endpoint has got to be structured for it and plan to correct. In some cases, it cannot make the right corrections, and packets are lost. As far because the end-user experience cares , this will take many forms. For instance , if a user is watching a video and therefore the video becomes pixelated, this is often a sign of potential jitter.
Network Congestion – As the name suggests, these congestions occur on the network. Network devices are unable to send the equivalent amount of traffic they receive, so their packet buffer fills up and they start dropping packets. If there’s no disturbance on the network at an endpoint, every packet arrives. However, if the endpoint buffer becomes full, packets arrive later and later, leading to jitter. This is often referred to as incipient congestion. By monitoring the jitter, it’s possible to watch incipient congestion. Similarly, if incipient network congestion is happening , the jitter is rapidly changing.
Congestion occurs when network devices begin to drop packets and therefore, the endpoint doesn’t receive them. Endpoints may then request the missing packets be retransmitted, which ends up in congestion collapse.With congestion, it’s important to notice that the receiving endpoint doesn’t directly cause it, and it doesn’t drop the packets.
How does one should catch up on Jitter?In order to form up for jitter, a jitter buffer is employed at the receiving endpoint of the connection. The jitter buffer collects and stores incoming packets, in order that it’s going to determine when to send them in consistent intervals.
Static Jitter Buffer – These buffers are implemented within the hardware of the system and are mostly configured by the manufacturer.
Dynamic Jitter Buffer – These buffers are implemented within the software of the system which are configured by the network administrator and can easily suit network change.
Difference between Latency and Jitters?
Interrupt-Latency is the Delay from occurrence of an Interrupt until the Interrupt-Service-Routine (ISR) is entered.
On the contrary, Jitter is that the time the instant of entering the ISR differs over time.
In terms of COMPUTER NETWORKS, Jitter and latency are the characteristics attributed to the flow within the application layer. The jitter and latency are used because the metrics to live the performance of the network. The ultimate difference between the jitter and latency in terms of a theoretical point of view is such that the latency is just a delay through the networks whereas the jitter is variation within all the latencies present.
This increase in latency and jitter occurs when the speed of the 2 devices doesn’t match; Congestion causes the buffers to overflow and traffic bursts.
Latency and jitter are innately linked, but they’re not an equivalent . Latency is the time it takes for data to maneuver from one endpoint on the network to a different . It’s a posh measurement suffering from multiple factors. Jitter, on the opposite hand, is the difference in delay between two packets. Similarly, it’s going to even be caused by several factors on the network. Though jitter and latency share similarities, jitter is simply based off of the delay, but it isn’t like that.
In a Nutshell , Latency = Delay between an occasion happening within the world and code responding to the event.Jitter = It is considered as minor differences in latencies between two or more events.
THEY BOTH ARE LINKED BUT ARE NOT SAME
Picked
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Memory Management in Operating System
File Allocation Methods
Logical and Physical Address in Operating System
Difference between Internal and External fragmentation
Process Table and Process Control Block (PCB)
File Access Methods in Operating System
Memory Hierarchy Design and its Characteristics
File Systems in Operating System
States of a Process in Operating Systems
Introduction of Process Management | [
{
"code": null,
"e": 25762,
"s": 25734,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 25822,
"s": 25762,
"text": "What is latency ?The literal meaning of latency is “delay”."
},
{
"code": null,
"e": 26099,
"s": 25822,
"text": "In an operating system , latency is the time between when an interrupt occurs, and when the processor starts to run code to process the interrupt. It is considered as the combined delay between an input or command and therefore the desired output and measured in milliseconds."
},
{
"code": null,
"e": 26133,
"s": 26099,
"text": "A few examples of latencies are –"
},
{
"code": null,
"e": 26521,
"s": 26133,
"text": "1. Latency of Networks :The latency of a network is the time delay while reaching some data such as a “knowledge packet” from its source to the destination. It is usually measured in milliseconds. These types of latency tools measure the quantity of time a packet takes as it’s transmitted, processed and then finally reaches its destination after being decoded by the receiving machine."
},
{
"code": null,
"e": 27087,
"s": 26521,
"text": "An allowable range of latency depends upon the network and the bandwidth of the applications used on it. These applications have a varied range of bandwidths. Among them, such as the video calling applications, require more bandwidth and a lower range of latencies to function proficiently. Whereas, some other applications ( for example -Gmail) which allows higher latency range. These factors are taken under consideration by the Network Admins to allocate sufficient resources and bandwidth and guarantee critical operations of the organization run efficiently."
},
{
"code": null,
"e": 27468,
"s": 27087,
"text": "2. Latency of Disks :The time delay between any single input output (I/O) operation on a block device. It looks very simple thing, but is very critical for the performance of the system. These latencies are determined by a few specific calculations such as rotational latency , seek time and transfer time . These factors directly affect the RPMs(rotation per minute) of disks. "
},
{
"code": null,
"e": 27510,
"s": 27468,
"text": "Many other sorts of latency exist, like –"
},
{
"code": null,
"e": 27565,
"s": 27510,
"text": "RAM latency\nCPU latency \nAudio latency \nVideo latency "
},
{
"code": null,
"e": 27715,
"s": 27565,
"text": "Within the computing world, these delays are usually only a couple of milliseconds, but they will add up to make noticeable slowdowns in performance."
},
{
"code": null,
"e": 28747,
"s": 27715,
"text": "What are jitters?Operating system jitter (or OS jitter) refers to the interference experienced by an application thanks to scheduling of background daemon processes and handling of asynchronous events like interrupts. It’s been seen that similar applications on mass numbers suffer substantial degradation in performance thanks to OS jitter.Talking in terms of networking , we can say that packets transmitted continuously on the network will have differing delays, albeit they choose an equivalent route. This is often inherent during a packet-switched network for 2 key reasons. First, packets are routed individually. Second, network devices receive packets during a queue, so constant delay pacing can’t be guaranteed.This delay inconsistency between each packet is understood as jitter. It is often a substantial issue for real-time communications, including IP telephony, video conferencing, and virtual desktop infrastructure. Jitter is often caused by many factors on the network, and each network has delay-time variation."
},
{
"code": null,
"e": 29186,
"s": 28747,
"text": "What Effects Does Jitter Have?Packet Loss – When packets don’t arrive consistently, the receiving endpoint has got to be structured for it and plan to correct. In some cases, it cannot make the right corrections, and packets are lost. As far because the end-user experience cares , this will take many forms. For instance , if a user is watching a video and therefore the video becomes pixelated, this is often a sign of potential jitter."
},
{
"code": null,
"e": 29804,
"s": 29186,
"text": "Network Congestion – As the name suggests, these congestions occur on the network. Network devices are unable to send the equivalent amount of traffic they receive, so their packet buffer fills up and they start dropping packets. If there’s no disturbance on the network at an endpoint, every packet arrives. However, if the endpoint buffer becomes full, packets arrive later and later, leading to jitter. This is often referred to as incipient congestion. By monitoring the jitter, it’s possible to watch incipient congestion. Similarly, if incipient network congestion is happening , the jitter is rapidly changing."
},
{
"code": null,
"e": 30149,
"s": 29804,
"text": "Congestion occurs when network devices begin to drop packets and therefore, the endpoint doesn’t receive them. Endpoints may then request the missing packets be retransmitted, which ends up in congestion collapse.With congestion, it’s important to notice that the receiving endpoint doesn’t directly cause it, and it doesn’t drop the packets. "
},
{
"code": null,
"e": 30430,
"s": 30149,
"text": "How does one should catch up on Jitter?In order to form up for jitter, a jitter buffer is employed at the receiving endpoint of the connection. The jitter buffer collects and stores incoming packets, in order that it’s going to determine when to send them in consistent intervals."
},
{
"code": null,
"e": 30564,
"s": 30430,
"text": "Static Jitter Buffer – These buffers are implemented within the hardware of the system and are mostly configured by the manufacturer."
},
{
"code": null,
"e": 30738,
"s": 30564,
"text": "Dynamic Jitter Buffer – These buffers are implemented within the software of the system which are configured by the network administrator and can easily suit network change."
},
{
"code": null,
"e": 30778,
"s": 30738,
"text": "Difference between Latency and Jitters?"
},
{
"code": null,
"e": 30895,
"s": 30778,
"text": "Interrupt-Latency is the Delay from occurrence of an Interrupt until the Interrupt-Service-Routine (ISR) is entered."
},
{
"code": null,
"e": 30987,
"s": 30895,
"text": "On the contrary, Jitter is that the time the instant of entering the ISR differs over time."
},
{
"code": null,
"e": 31429,
"s": 30987,
"text": "In terms of COMPUTER NETWORKS, Jitter and latency are the characteristics attributed to the flow within the application layer. The jitter and latency are used because the metrics to live the performance of the network. The ultimate difference between the jitter and latency in terms of a theoretical point of view is such that the latency is just a delay through the networks whereas the jitter is variation within all the latencies present."
},
{
"code": null,
"e": 31581,
"s": 31429,
"text": "This increase in latency and jitter occurs when the speed of the 2 devices doesn’t match; Congestion causes the buffers to overflow and traffic bursts."
},
{
"code": null,
"e": 32074,
"s": 31581,
"text": "Latency and jitter are innately linked, but they’re not an equivalent . Latency is the time it takes for data to maneuver from one endpoint on the network to a different . It’s a posh measurement suffering from multiple factors. Jitter, on the opposite hand, is the difference in delay between two packets. Similarly, it’s going to even be caused by several factors on the network. Though jitter and latency share similarities, jitter is simply based off of the delay, but it isn’t like that."
},
{
"code": null,
"e": 32275,
"s": 32074,
"text": "In a Nutshell , Latency = Delay between an occasion happening within the world and code responding to the event.Jitter = It is considered as minor differences in latencies between two or more events."
},
{
"code": null,
"e": 32314,
"s": 32275,
"text": "THEY BOTH ARE LINKED BUT ARE NOT SAME "
},
{
"code": null,
"e": 32321,
"s": 32314,
"text": "Picked"
},
{
"code": null,
"e": 32339,
"s": 32321,
"text": "Operating Systems"
},
{
"code": null,
"e": 32357,
"s": 32339,
"text": "Operating Systems"
},
{
"code": null,
"e": 32455,
"s": 32357,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32493,
"s": 32455,
"text": "Memory Management in Operating System"
},
{
"code": null,
"e": 32517,
"s": 32493,
"text": "File Allocation Methods"
},
{
"code": null,
"e": 32566,
"s": 32517,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 32621,
"s": 32566,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 32667,
"s": 32621,
"text": "Process Table and Process Control Block (PCB)"
},
{
"code": null,
"e": 32707,
"s": 32667,
"text": "File Access Methods in Operating System"
},
{
"code": null,
"e": 32755,
"s": 32707,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 32788,
"s": 32755,
"text": "File Systems in Operating System"
},
{
"code": null,
"e": 32829,
"s": 32788,
"text": "States of a Process in Operating Systems"
}
] |
Map of Vectors in C++ STL with Examples - GeeksforGeeks | 16 Jan, 2020
Map in STL Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.
Vector in STL Vector is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators.
Map of Vectors in STL: Map of Vectors can be very efficient in designing complex data structures.
Syntax:
map<key, vector<datatype>> map_of_vector;
OR
map<vector<datatype>, key> map_of_vector;
For example: Consider a simple problem where we have to check if a vector is visited or not.
// C++ program to demonstrate// use of map for vectors #include <bits/stdc++.h>using namespace std; map<vector<int>, int> vis; // Print True if vector is visited// or False if not visitedvoid CheckVisited(vector<int> data){ if (vis.find(data) != vis.end()) { cout << "True" << endl; } else { cout << "False" << endl; }} // Driver codeint main(){ // Initializing some vectors vector<int> data_1{ 10, 20, 30, 40 }; vector<int> data_2{ 5, 10, 15 }; vector<int> data_3{ 1, 3, 5, 7, 9, 11, 13 }; // Making some vectors as visited vis[data_1] = 1; vis[data_2] = 1; vis[data_3] = 1; // checking if these vectors are // visited or not vector<int> check_1 = { 5, 10, 15 }; vector<int> check_2 = { 2, 4, 6, 8, 10, 12 }; CheckVisited(check_1); CheckVisited(check_2); return 0;}
True
False
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++
Bitwise Operators in C/C++
Constructors in C++
Templates in C++ with Examples
Operator Overloading in C++
Socket Programming in C/C++
Object Oriented Programming in C++
Copy Constructor in C++ | [
{
"code": null,
"e": 25801,
"s": 25773,
"text": "\n16 Jan, 2020"
},
{
"code": null,
"e": 25981,
"s": 25801,
"text": "Map in STL Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values."
},
{
"code": null,
"e": 26290,
"s": 25981,
"text": "Vector in STL Vector is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators."
},
{
"code": null,
"e": 26388,
"s": 26290,
"text": "Map of Vectors in STL: Map of Vectors can be very efficient in designing complex data structures."
},
{
"code": null,
"e": 26396,
"s": 26388,
"text": "Syntax:"
},
{
"code": null,
"e": 26484,
"s": 26396,
"text": "map<key, vector<datatype>> map_of_vector;\nOR\nmap<vector<datatype>, key> map_of_vector;\n"
},
{
"code": null,
"e": 26577,
"s": 26484,
"text": "For example: Consider a simple problem where we have to check if a vector is visited or not."
},
{
"code": "// C++ program to demonstrate// use of map for vectors #include <bits/stdc++.h>using namespace std; map<vector<int>, int> vis; // Print True if vector is visited// or False if not visitedvoid CheckVisited(vector<int> data){ if (vis.find(data) != vis.end()) { cout << \"True\" << endl; } else { cout << \"False\" << endl; }} // Driver codeint main(){ // Initializing some vectors vector<int> data_1{ 10, 20, 30, 40 }; vector<int> data_2{ 5, 10, 15 }; vector<int> data_3{ 1, 3, 5, 7, 9, 11, 13 }; // Making some vectors as visited vis[data_1] = 1; vis[data_2] = 1; vis[data_3] = 1; // checking if these vectors are // visited or not vector<int> check_1 = { 5, 10, 15 }; vector<int> check_2 = { 2, 4, 6, 8, 10, 12 }; CheckVisited(check_1); CheckVisited(check_2); return 0;}",
"e": 27427,
"s": 26577,
"text": null
},
{
"code": null,
"e": 27439,
"s": 27427,
"text": "True\nFalse\n"
},
{
"code": null,
"e": 27443,
"s": 27439,
"text": "STL"
},
{
"code": null,
"e": 27447,
"s": 27443,
"text": "C++"
},
{
"code": null,
"e": 27451,
"s": 27447,
"text": "STL"
},
{
"code": null,
"e": 27455,
"s": 27451,
"text": "CPP"
},
{
"code": null,
"e": 27553,
"s": 27455,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27572,
"s": 27553,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27596,
"s": 27572,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 27620,
"s": 27596,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 27647,
"s": 27620,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 27667,
"s": 27647,
"text": "Constructors in C++"
},
{
"code": null,
"e": 27698,
"s": 27667,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 27726,
"s": 27698,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27754,
"s": 27726,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 27789,
"s": 27754,
"text": "Object Oriented Programming in C++"
}
] |
Why You Should Be Using Pandas Dataframes for Keras Trainings on Image Classification Problems | Towards Data Science | As seen in my previous article, research projects can be arduous with a lack of organization. So many resources around, that sometimes slow down the process of researching.
In this article, I am going to focused on datasets that are composed of images, especially those for Image Classification problems. We are going to see how launching Keras trainings on this kind of datasets has some advantages when using Pandas dataframes.
Keras provides a way to use large datasets when working with neural networks: either in the training or evaluation stage. This is the Keras preprocessing module, which has several methods to load data from disk and dynamically pre-process it. The most common method is flow_from_directory(), which is a very simple workflow since you just have to separate your image files into folders for each class. The generator will take each folder as the classes to be trained. This is pretty simple, yes, but it involves having to develop time-consuming scripts to copy or move images from one side to another for each training dataset version.
But, what if you decide to make some modifications for a specific experiment such as dividing one class into two? — Dataset versioning
What if you want to compose a dataset with images that come from two or more datasets? — Combination of multiple datasets
What if you want to train two labels at the same time because your network model has two outputs? — Multi-task problems
We will see how using Pandas library will help relieve these problems.
Keras has a generator function that is meant to use a Pandas dataframe to load data from disk: flow_from_dataframe(). This dataframe must have a column where you specify the image filename for each item. With this and the directory parameter, Keras will compose the path for each image file in the following way:os.path.join(directory, <filename_column>)At this point, you can forget the idea of having the files organized in folders of classes, and instead, you can just have them all in the same folder.
Each of the following sections attempts to answer one of the three previous questions by using thisflow_from_dataframe() method.
My workflow when working with datasets is that I manually create a versioning control system: each version is the result of any modification I make for a particular experiment: adding additional data, modifications to the labels, corrections, etc.
This results in having different dataset versions that are more clearly represented by dataframes, instead of having to create a separate folder where the images are copied to with a new class-structure. The most powerful thing about this is that the large-size files (the images) are still in the same directory. Therefore, you can have several dataset versions (csv files) composed of different combinations of the same images.
As I mentioned before, Keras composes the path of the images to be read by using the directory parameter and filename column. The latest must have the file name but it may contain sub-paths too. Keras will perform the join without asking if there is only a filename. This is very powerful for datasets that you download online and have a particular structure in which images are located in different subdirectories. Furthermore, with this, we can easily compose a dataset version where there are images that come from different sources, without having to move them to the same folder.
Let’s see an example:
Suppose you have dataset 1 and dataset 2 with the following image paths:
/media/datasets/dataset_1/train/image_1.png/media/datasets/dataset_1/train/image_2.png/media/datasets/dataset_2/train/0289323/image_1.png/media/datasets/dataset_2/train/3453453/image_1.png
Dataset 1 has a structure where all images are under the same directory: dataset_1/train/*. However, dataset 2 is different, it has subfolders and the image filename itself is repeated (“image_1.png”), so we need to add this subfolder to the filename column. These would be the two dataframes and their corresponding Keras method calls:
To create a merged version (dataset 3) we just need to add the path from where both paths become different: “dataset_1/” and “dataset_2/”.
For this example, we have to set the directory parameter in flow_from_dataframe() to the common path, in order for Keras to be able to compose paths that work for both datasets.
One thing I suggest here is to create a folder, for instance, dataset_3, with symlinks to both datasets:
~/datasets $ mkdir dataset_3~/datasets $ cd dataset_3~/datasets/dataset_3 $ ln -s ~/datasets/dataset_1/train dataset_1~/datasets/dataset_3 $ ln -s ~/datasets/dataset_2/train dataset_2~/datasets/dataset_3 $ ls -ldataset_1 -> /home/sruiz/datasets/dataset_1/traindataset_2 -> /home/sruiz/datasets/dataset_2/train
This is just for organization purposes since the base path where both datasets differ would be: /home/datasets/dataset_3 instead of the more general one: /home/datasets. But, it could also be very useful if datasets are located in different places and they don’t share any base path — and you don’t want to move them.
In one task using dataframes is unnegotiable is when training a multi-task problem. This refers to networks models that can predict multiple outputs for one input: for instance, if an image has a cat or a dog and the color of its skin.
For this kind of problems, we need two labels for each input in the training step. So the approach of separating the files into folders for each label, though it is possible, involves having one folder for each label combination. Something it could result in creating a great number of folders.
The good thing of a dataframe is that you can have a column for label cat/dog and another one for the skin color. When using the flow_from_dataframe() method with your two-output network, you just need to specify in the y_col parameter in which columns are the labels:
Thanks for reading.
Sergio Ruiz (@serchu) | [
{
"code": null,
"e": 345,
"s": 172,
"text": "As seen in my previous article, research projects can be arduous with a lack of organization. So many resources around, that sometimes slow down the process of researching."
},
{
"code": null,
"e": 602,
"s": 345,
"text": "In this article, I am going to focused on datasets that are composed of images, especially those for Image Classification problems. We are going to see how launching Keras trainings on this kind of datasets has some advantages when using Pandas dataframes."
},
{
"code": null,
"e": 1238,
"s": 602,
"text": "Keras provides a way to use large datasets when working with neural networks: either in the training or evaluation stage. This is the Keras preprocessing module, which has several methods to load data from disk and dynamically pre-process it. The most common method is flow_from_directory(), which is a very simple workflow since you just have to separate your image files into folders for each class. The generator will take each folder as the classes to be trained. This is pretty simple, yes, but it involves having to develop time-consuming scripts to copy or move images from one side to another for each training dataset version."
},
{
"code": null,
"e": 1373,
"s": 1238,
"text": "But, what if you decide to make some modifications for a specific experiment such as dividing one class into two? — Dataset versioning"
},
{
"code": null,
"e": 1495,
"s": 1373,
"text": "What if you want to compose a dataset with images that come from two or more datasets? — Combination of multiple datasets"
},
{
"code": null,
"e": 1615,
"s": 1495,
"text": "What if you want to train two labels at the same time because your network model has two outputs? — Multi-task problems"
},
{
"code": null,
"e": 1686,
"s": 1615,
"text": "We will see how using Pandas library will help relieve these problems."
},
{
"code": null,
"e": 2192,
"s": 1686,
"text": "Keras has a generator function that is meant to use a Pandas dataframe to load data from disk: flow_from_dataframe(). This dataframe must have a column where you specify the image filename for each item. With this and the directory parameter, Keras will compose the path for each image file in the following way:os.path.join(directory, <filename_column>)At this point, you can forget the idea of having the files organized in folders of classes, and instead, you can just have them all in the same folder."
},
{
"code": null,
"e": 2321,
"s": 2192,
"text": "Each of the following sections attempts to answer one of the three previous questions by using thisflow_from_dataframe() method."
},
{
"code": null,
"e": 2569,
"s": 2321,
"text": "My workflow when working with datasets is that I manually create a versioning control system: each version is the result of any modification I make for a particular experiment: adding additional data, modifications to the labels, corrections, etc."
},
{
"code": null,
"e": 2999,
"s": 2569,
"text": "This results in having different dataset versions that are more clearly represented by dataframes, instead of having to create a separate folder where the images are copied to with a new class-structure. The most powerful thing about this is that the large-size files (the images) are still in the same directory. Therefore, you can have several dataset versions (csv files) composed of different combinations of the same images."
},
{
"code": null,
"e": 3584,
"s": 2999,
"text": "As I mentioned before, Keras composes the path of the images to be read by using the directory parameter and filename column. The latest must have the file name but it may contain sub-paths too. Keras will perform the join without asking if there is only a filename. This is very powerful for datasets that you download online and have a particular structure in which images are located in different subdirectories. Furthermore, with this, we can easily compose a dataset version where there are images that come from different sources, without having to move them to the same folder."
},
{
"code": null,
"e": 3606,
"s": 3584,
"text": "Let’s see an example:"
},
{
"code": null,
"e": 3679,
"s": 3606,
"text": "Suppose you have dataset 1 and dataset 2 with the following image paths:"
},
{
"code": null,
"e": 3868,
"s": 3679,
"text": "/media/datasets/dataset_1/train/image_1.png/media/datasets/dataset_1/train/image_2.png/media/datasets/dataset_2/train/0289323/image_1.png/media/datasets/dataset_2/train/3453453/image_1.png"
},
{
"code": null,
"e": 4205,
"s": 3868,
"text": "Dataset 1 has a structure where all images are under the same directory: dataset_1/train/*. However, dataset 2 is different, it has subfolders and the image filename itself is repeated (“image_1.png”), so we need to add this subfolder to the filename column. These would be the two dataframes and their corresponding Keras method calls:"
},
{
"code": null,
"e": 4344,
"s": 4205,
"text": "To create a merged version (dataset 3) we just need to add the path from where both paths become different: “dataset_1/” and “dataset_2/”."
},
{
"code": null,
"e": 4522,
"s": 4344,
"text": "For this example, we have to set the directory parameter in flow_from_dataframe() to the common path, in order for Keras to be able to compose paths that work for both datasets."
},
{
"code": null,
"e": 4627,
"s": 4522,
"text": "One thing I suggest here is to create a folder, for instance, dataset_3, with symlinks to both datasets:"
},
{
"code": null,
"e": 4937,
"s": 4627,
"text": "~/datasets $ mkdir dataset_3~/datasets $ cd dataset_3~/datasets/dataset_3 $ ln -s ~/datasets/dataset_1/train dataset_1~/datasets/dataset_3 $ ln -s ~/datasets/dataset_2/train dataset_2~/datasets/dataset_3 $ ls -ldataset_1 -> /home/sruiz/datasets/dataset_1/traindataset_2 -> /home/sruiz/datasets/dataset_2/train"
},
{
"code": null,
"e": 5255,
"s": 4937,
"text": "This is just for organization purposes since the base path where both datasets differ would be: /home/datasets/dataset_3 instead of the more general one: /home/datasets. But, it could also be very useful if datasets are located in different places and they don’t share any base path — and you don’t want to move them."
},
{
"code": null,
"e": 5491,
"s": 5255,
"text": "In one task using dataframes is unnegotiable is when training a multi-task problem. This refers to networks models that can predict multiple outputs for one input: for instance, if an image has a cat or a dog and the color of its skin."
},
{
"code": null,
"e": 5786,
"s": 5491,
"text": "For this kind of problems, we need two labels for each input in the training step. So the approach of separating the files into folders for each label, though it is possible, involves having one folder for each label combination. Something it could result in creating a great number of folders."
},
{
"code": null,
"e": 6055,
"s": 5786,
"text": "The good thing of a dataframe is that you can have a column for label cat/dog and another one for the skin color. When using the flow_from_dataframe() method with your two-output network, you just need to specify in the y_col parameter in which columns are the labels:"
},
{
"code": null,
"e": 6075,
"s": 6055,
"text": "Thanks for reading."
}
] |
Sort the words in lexicographical order in Python | Sorting words in lexicographical order mean that we want to arrange them first by the first letter of the word. Then for the words whose first letter is the same, we arrange them within that group by the second letter and so on just like in a language's dictionary(not the data structure).
Python has 2 functions, sort and sorted for this type of order, let us look at how and when to use each of these methods.
In place sorting: when we want to sort the array/list in place, ie, changing the order in the current structure itself, we can use the sort method directly. For example,
my_arr = [
"hello",
"apple",
"actor",
"people",
"dog"
]
print(my_arr)
my_arr.sort()
print(my_arr)
This will give the output −
['hello', 'apple', 'actor', 'people', 'dog']
['actor', 'apple', 'dog', 'hello', 'people']
As you can see here, the original array, my_arr has been modified. If you want to keep this array as it is and created a new array when sorting, you can use the sorted method. For example,
Live Demo
my_arr = [
"hello",
"apple",
"actor",
"people",
"dog"
]
print(my_arr)
# Create a new array using the sorted method
new_arr = sorted(my_arr)
print(new_arr)
# This time, my_arr won't change in place, rather, it'll be sorted
# and a new instance will be assigned to new_arr
print(my_arr)
This will give the output −
['hello', 'apple', 'actor', 'people', 'dog']
['actor', 'apple', 'dog', 'hello', 'people']
['hello', 'apple', 'actor', 'people', 'dog']
As you can see here, the original array did not change. | [
{
"code": null,
"e": 1352,
"s": 1062,
"text": "Sorting words in lexicographical order mean that we want to arrange them first by the first letter of the word. Then for the words whose first letter is the same, we arrange them within that group by the second letter and so on just like in a language's dictionary(not the data structure)."
},
{
"code": null,
"e": 1474,
"s": 1352,
"text": "Python has 2 functions, sort and sorted for this type of order, let us look at how and when to use each of these methods."
},
{
"code": null,
"e": 1644,
"s": 1474,
"text": "In place sorting: when we want to sort the array/list in place, ie, changing the order in the current structure itself, we can use the sort method directly. For example,"
},
{
"code": null,
"e": 1743,
"s": 1644,
"text": "my_arr = [\n\"hello\",\n\"apple\",\n\"actor\",\n\"people\",\n\"dog\"\n]\n\nprint(my_arr)\nmy_arr.sort()\nprint(my_arr)"
},
{
"code": null,
"e": 1771,
"s": 1743,
"text": "This will give the output −"
},
{
"code": null,
"e": 1861,
"s": 1771,
"text": "['hello', 'apple', 'actor', 'people', 'dog']\n['actor', 'apple', 'dog', 'hello', 'people']"
},
{
"code": null,
"e": 2050,
"s": 1861,
"text": "As you can see here, the original array, my_arr has been modified. If you want to keep this array as it is and created a new array when sorting, you can use the sorted method. For example,"
},
{
"code": null,
"e": 2061,
"s": 2050,
"text": " Live Demo"
},
{
"code": null,
"e": 2348,
"s": 2061,
"text": "my_arr = [\n\"hello\",\n\"apple\",\n\"actor\",\n\"people\",\n\"dog\"\n]\n\nprint(my_arr)\n# Create a new array using the sorted method\nnew_arr = sorted(my_arr)\n\nprint(new_arr)\n# This time, my_arr won't change in place, rather, it'll be sorted\n# and a new instance will be assigned to new_arr\nprint(my_arr)"
},
{
"code": null,
"e": 2376,
"s": 2348,
"text": "This will give the output −"
},
{
"code": null,
"e": 2511,
"s": 2376,
"text": "['hello', 'apple', 'actor', 'people', 'dog']\n['actor', 'apple', 'dog', 'hello', 'people']\n['hello', 'apple', 'actor', 'people', 'dog']"
},
{
"code": null,
"e": 2567,
"s": 2511,
"text": "As you can see here, the original array did not change."
}
] |
Spring JDBC - Configure Data Source | Let us create a database table Student in our database TEST. I assume you are working with MySQL database, if you work with any other database then you can change your DDL and SQL queries accordingly.
CREATE TABLE Student(
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY (ID)
);
Now we need to supply a DataSource to the JDBC Template so it can configure itself to get database access. You can configure the DataSource in the XML file with a piece of code shown as follows −
<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.cj.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
<property name = "username" value = "root"/>
<property name = "password" value = "admin"/>
</bean>
In the next chapter, we'll write the first application using the database configured.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2597,
"s": 2396,
"text": "Let us create a database table Student in our database TEST. I assume you are working with MySQL database, if you work with any other database then you can change your DDL and SQL queries accordingly."
},
{
"code": null,
"e": 2731,
"s": 2597,
"text": "CREATE TABLE Student(\n ID INT NOT NULL AUTO_INCREMENT,\n NAME VARCHAR(20) NOT NULL,\n AGE INT NOT NULL,\n PRIMARY KEY (ID)\n);"
},
{
"code": null,
"e": 2927,
"s": 2731,
"text": "Now we need to supply a DataSource to the JDBC Template so it can configure itself to get database access. You can configure the DataSource in the XML file with a piece of code shown as follows −"
},
{
"code": null,
"e": 3273,
"s": 2927,
"text": "<bean id = \"dataSource\"\nclass = \"org.springframework.jdbc.datasource.DriverManagerDataSource\">\n <property name = \"driverClassName\" value = \"com.mysql.cj.jdbc.Driver\"/>\n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/TEST\"/>\n <property name = \"username\" value = \"root\"/>\n <property name = \"password\" value = \"admin\"/>\n</bean>"
},
{
"code": null,
"e": 3359,
"s": 3273,
"text": "In the next chapter, we'll write the first application using the database configured."
},
{
"code": null,
"e": 3366,
"s": 3359,
"text": " Print"
},
{
"code": null,
"e": 3377,
"s": 3366,
"text": " Add Notes"
}
] |
How to sample from language models | by Ben Mann | Towards Data Science | Causal language models like GPT-2 are trained to predict the probability of the next word given some context. For example, given “I ate a delicious hot ___”, the model may predict “dog” with 80% probability, “pancake” 5% probability, etc. The cool thing about this structure is they can be used to generate sequences of arbitrary length. I can give the model “I ate,” sample a token from the resulting distribution to get “I ate a”, then put that through the model again to get another distribution and resulting token. Repeat as long as we like. It turns out that this generation often either gets stuck in repetitive loops or forgets the subject and goes off topic. Why is this happening, and how might we better sample to generate more human-like text?
This post is a summary and exploration of The Curious Case of Neural Text Degeneration by Holtzman et al 2019. I found it one of the most thorough and readable papers I’ve read in recent memory, so please check it out if this post piques your interest!
If we always sample the the most likely word, the standard language model training objective causes us to get stuck in loops like “I don’t know. I don’t know. I don’t know.” This is unnatural, but most of the model’s attention in modern language models is only on the most recent few tokens. Instead, popular sampling methods for generation are based on sampling from the distribution. But sampling also runs into a problem: if we have 50K possible choices, even if the bottom 25K tokens are each extremely unlikely, in aggregate they might have for example 30% of the probability mass. This means with each sample, we have a 1 in 3 chance of completely derailing our “train of thought.” Because of the short context mentioned earlier, this will cause an unrecoverable error cascade as each next word depends heavily on this recent wrong word.
To combat sampling from the tail, the most popular methods are temperature and top k sampling.
Temperature sampling is inspired by statistical thermodynamics, where high temperature means low energy states are more likely encountered. In probability models, logits play the role of energy and we can implement temperature sampling by dividing logits by the temperature before feeding them into softmax and obtaining our sampling probabilities. For example:
>>> import torch>>> import torch.nn.functional as F>>> a = torch.tensor([1,2,3,4.])>>> F.softmax(a, dim=0)tensor([0.0321, 0.0871, 0.2369, 0.6439])>>> F.softmax(a/.5, dim=0)tensor([0.0021, 0.0158, 0.1171, 0.8650])>>> F.softmax(a/1.5, dim=0)tensor([0.0708, 0.1378, 0.2685, 0.5229])>>> F.softmax(a/1e-6, dim=0)tensor([0., 0., 0., 1.])
Or visually
Lower temperatures make the model increasingly confident in its top choices, while temperatures greater than 1 decrease confidence. 0 temperature is equivalent to argmax/max likelihood, while infinite temperature corresponds to a uniform sampling.
Top k sampling means sorting by probability and zero-ing out the probabilities for anything below the k’th token. It appears to improve quality by removing the tail and making it less likely to go off topic. But in some cases, there really are many words we could sample from reasonably (broad distribution below), and in some cases there aren’t (narrow distribution below).
To address this problem, the authors propose top p sampling, aka nucleus sampling, in which we compute the cumulative distribution and cut off as soon as the CDF exceeds P. In the broad distribution example above, it may take the top 100 tokens to exceed top_p = .9. In the narrow distribution, we may already exceed top_p = .9 with just “hot” and “warm” in our sample distribution. In this way, we still avoid sampling egregiously wrong tokens, but preserve variety when the highest scoring tokens have low confidence.
Why doesn’t maximum likelihood sampling work? In the training process, there’s never a chance to see compounding errors. The model is trained to predict the next token based on a human-generated context. If it gets one token wrong by generating a bad distribution, the next token uses the “correct” human generated context independent of the last prediction. During generation it is forced to complete its own automatically-generated context, a setting it has not considered during training.
Here are samples using top_k=40 and context “I ate a delicious”
And here are samples using top_p=0.9 and same “I ate a delicious” context:
Try it yourself here! You can enable GPU in Runtime > Change runtime type and get big batches for no additional runtime.
I found it challenging to determine which of these samples is more human-like. For this reason I designed an experiment to determine top_k and top_p empirically.
Our goal is to use top_k and top_p to maximize the probability of choosing the actual next word we’ve held out. When searching for the optimal k and p values, it’s actually easy to determine analytically for a given sample. For k, we find the sorted index where the “golden” token occurred. For p, we find the CDF of the golden token. For example, if the context is “I ate a delicious hot” and the actual word is “dog”, but the model’s predicted distribution had “pancake” as most likely, we’d search down the probabilities until we found “dog” at index 3. At index 1, the CDF might be 62%. At index 3, the CDF might be something like 86%, so we’ll record that as our optimal p.
Across many examples, we can compute a histogram of optimal p and k values and compute summary statistics on them. I tested on a random section of Wikipedia with a context length of 15. This is much shorter than what the model was trained on (1024), but common for settings like https://duet.li or chat bots.
===== ks =====max 29094.00mean 233.69median 3.00len 13376.00===== ps =====max 1.00mean 0.59median 0.60len 13376.00
Feel free to try it yourself in my colab notebook.
If the model were being evaluated on its training set, it would be optimal to choose top_k = 1. But since the model is slightly out of domain, the most likely token sometimes appears further down the list. In addition, we have a 50K token vocabulary. In many datasets, we’ll never see all the tokens, but the model isn’t sure of that. By zero-ing out much of the probability mass using top_p or top_k, we incorporate our prior to never choose these never-seen-even-in-training tokens.
That said, this search for k and p is still in the context of the model’s view of the world and as such it’s only a bandaid. What we really want is to fix training.
I’ve also started to think about changing the training objective to better match the generation task. For example, could we train some kind of discriminator to punish the model when it generates whole sequences that don’t look human? It’s not straightforward how to apply a GAN architecture to non-continuous domains. I came upon Adversarial Text Generation without Reinforcement Learning and an RL-based idea, but it seems these have not yet become mainstream. I think it’d be interesting to apply these ideas to the big transformers that have swept state of the art in the last few months.
Thanks to Yaroslav Bulatov for feedback and edits | [
{
"code": null,
"e": 928,
"s": 172,
"text": "Causal language models like GPT-2 are trained to predict the probability of the next word given some context. For example, given “I ate a delicious hot ___”, the model may predict “dog” with 80% probability, “pancake” 5% probability, etc. The cool thing about this structure is they can be used to generate sequences of arbitrary length. I can give the model “I ate,” sample a token from the resulting distribution to get “I ate a”, then put that through the model again to get another distribution and resulting token. Repeat as long as we like. It turns out that this generation often either gets stuck in repetitive loops or forgets the subject and goes off topic. Why is this happening, and how might we better sample to generate more human-like text?"
},
{
"code": null,
"e": 1181,
"s": 928,
"text": "This post is a summary and exploration of The Curious Case of Neural Text Degeneration by Holtzman et al 2019. I found it one of the most thorough and readable papers I’ve read in recent memory, so please check it out if this post piques your interest!"
},
{
"code": null,
"e": 2025,
"s": 1181,
"text": "If we always sample the the most likely word, the standard language model training objective causes us to get stuck in loops like “I don’t know. I don’t know. I don’t know.” This is unnatural, but most of the model’s attention in modern language models is only on the most recent few tokens. Instead, popular sampling methods for generation are based on sampling from the distribution. But sampling also runs into a problem: if we have 50K possible choices, even if the bottom 25K tokens are each extremely unlikely, in aggregate they might have for example 30% of the probability mass. This means with each sample, we have a 1 in 3 chance of completely derailing our “train of thought.” Because of the short context mentioned earlier, this will cause an unrecoverable error cascade as each next word depends heavily on this recent wrong word."
},
{
"code": null,
"e": 2120,
"s": 2025,
"text": "To combat sampling from the tail, the most popular methods are temperature and top k sampling."
},
{
"code": null,
"e": 2482,
"s": 2120,
"text": "Temperature sampling is inspired by statistical thermodynamics, where high temperature means low energy states are more likely encountered. In probability models, logits play the role of energy and we can implement temperature sampling by dividing logits by the temperature before feeding them into softmax and obtaining our sampling probabilities. For example:"
},
{
"code": null,
"e": 2814,
"s": 2482,
"text": ">>> import torch>>> import torch.nn.functional as F>>> a = torch.tensor([1,2,3,4.])>>> F.softmax(a, dim=0)tensor([0.0321, 0.0871, 0.2369, 0.6439])>>> F.softmax(a/.5, dim=0)tensor([0.0021, 0.0158, 0.1171, 0.8650])>>> F.softmax(a/1.5, dim=0)tensor([0.0708, 0.1378, 0.2685, 0.5229])>>> F.softmax(a/1e-6, dim=0)tensor([0., 0., 0., 1.])"
},
{
"code": null,
"e": 2826,
"s": 2814,
"text": "Or visually"
},
{
"code": null,
"e": 3074,
"s": 2826,
"text": "Lower temperatures make the model increasingly confident in its top choices, while temperatures greater than 1 decrease confidence. 0 temperature is equivalent to argmax/max likelihood, while infinite temperature corresponds to a uniform sampling."
},
{
"code": null,
"e": 3449,
"s": 3074,
"text": "Top k sampling means sorting by probability and zero-ing out the probabilities for anything below the k’th token. It appears to improve quality by removing the tail and making it less likely to go off topic. But in some cases, there really are many words we could sample from reasonably (broad distribution below), and in some cases there aren’t (narrow distribution below)."
},
{
"code": null,
"e": 3969,
"s": 3449,
"text": "To address this problem, the authors propose top p sampling, aka nucleus sampling, in which we compute the cumulative distribution and cut off as soon as the CDF exceeds P. In the broad distribution example above, it may take the top 100 tokens to exceed top_p = .9. In the narrow distribution, we may already exceed top_p = .9 with just “hot” and “warm” in our sample distribution. In this way, we still avoid sampling egregiously wrong tokens, but preserve variety when the highest scoring tokens have low confidence."
},
{
"code": null,
"e": 4461,
"s": 3969,
"text": "Why doesn’t maximum likelihood sampling work? In the training process, there’s never a chance to see compounding errors. The model is trained to predict the next token based on a human-generated context. If it gets one token wrong by generating a bad distribution, the next token uses the “correct” human generated context independent of the last prediction. During generation it is forced to complete its own automatically-generated context, a setting it has not considered during training."
},
{
"code": null,
"e": 4525,
"s": 4461,
"text": "Here are samples using top_k=40 and context “I ate a delicious”"
},
{
"code": null,
"e": 4600,
"s": 4525,
"text": "And here are samples using top_p=0.9 and same “I ate a delicious” context:"
},
{
"code": null,
"e": 4721,
"s": 4600,
"text": "Try it yourself here! You can enable GPU in Runtime > Change runtime type and get big batches for no additional runtime."
},
{
"code": null,
"e": 4883,
"s": 4721,
"text": "I found it challenging to determine which of these samples is more human-like. For this reason I designed an experiment to determine top_k and top_p empirically."
},
{
"code": null,
"e": 5562,
"s": 4883,
"text": "Our goal is to use top_k and top_p to maximize the probability of choosing the actual next word we’ve held out. When searching for the optimal k and p values, it’s actually easy to determine analytically for a given sample. For k, we find the sorted index where the “golden” token occurred. For p, we find the CDF of the golden token. For example, if the context is “I ate a delicious hot” and the actual word is “dog”, but the model’s predicted distribution had “pancake” as most likely, we’d search down the probabilities until we found “dog” at index 3. At index 1, the CDF might be 62%. At index 3, the CDF might be something like 86%, so we’ll record that as our optimal p."
},
{
"code": null,
"e": 5871,
"s": 5562,
"text": "Across many examples, we can compute a histogram of optimal p and k values and compute summary statistics on them. I tested on a random section of Wikipedia with a context length of 15. This is much shorter than what the model was trained on (1024), but common for settings like https://duet.li or chat bots."
},
{
"code": null,
"e": 5986,
"s": 5871,
"text": "===== ks =====max 29094.00mean 233.69median 3.00len 13376.00===== ps =====max 1.00mean 0.59median 0.60len 13376.00"
},
{
"code": null,
"e": 6037,
"s": 5986,
"text": "Feel free to try it yourself in my colab notebook."
},
{
"code": null,
"e": 6522,
"s": 6037,
"text": "If the model were being evaluated on its training set, it would be optimal to choose top_k = 1. But since the model is slightly out of domain, the most likely token sometimes appears further down the list. In addition, we have a 50K token vocabulary. In many datasets, we’ll never see all the tokens, but the model isn’t sure of that. By zero-ing out much of the probability mass using top_p or top_k, we incorporate our prior to never choose these never-seen-even-in-training tokens."
},
{
"code": null,
"e": 6687,
"s": 6522,
"text": "That said, this search for k and p is still in the context of the model’s view of the world and as such it’s only a bandaid. What we really want is to fix training."
},
{
"code": null,
"e": 7279,
"s": 6687,
"text": "I’ve also started to think about changing the training objective to better match the generation task. For example, could we train some kind of discriminator to punish the model when it generates whole sequences that don’t look human? It’s not straightforward how to apply a GAN architecture to non-continuous domains. I came upon Adversarial Text Generation without Reinforcement Learning and an RL-based idea, but it seems these have not yet become mainstream. I think it’d be interesting to apply these ideas to the big transformers that have swept state of the art in the last few months."
}
] |
Node.js crypto.generateKeyPairSync() Method - GeeksforGeeks | 11 Oct, 2021
The crypto.generateKeyPairSync() method is an inbuilt application programming interface of crypto module which is used to generate a new asymmetric key pair of the specified type. For example, the currently supported key types are RSA, DSA, EC, Ed25519, Ed448, X25519, X448, and DH. Moreover, if option’s publicKeyEncoding or privateKeyEncoding is stated here, then this function acts as if keyObject.export() had been called on its output. Else, the particular part of the key is returned as a KeyObject.However, it is suggested to encode the public keys as ‘spki’ and private keys as ‘pkcs8’ with a strong passphrase, in order to keep the passphrase secret.
Syntax:
crypto.generateKeyPairSync( type, options )
Parameters: This method accept two parameters as mentioned above and described below:
type: It holds a string and it must include one or more of the following algorithms: ‘rsa’, ‘dsa’, ‘ec’, ‘ed25519’, ‘ed448’, ‘x25519’, ‘x448’, or ‘dh’.
options: It is of type object. It can hold the following parameters:modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.prime: It holds a buffer. It is the prime parameter of DH algorithm.primeLength: It holds a number. It is the prime length of DH algorithm in bits.generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.publicKeyEncoding: It holds a string.privateKeyEncoding: It holds an Object.
modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.prime: It holds a buffer. It is the prime parameter of DH algorithm.primeLength: It holds a number. It is the prime length of DH algorithm in bits.generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.publicKeyEncoding: It holds a string.privateKeyEncoding: It holds an Object.
modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.
publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.
divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.
namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.
prime: It holds a buffer. It is the prime parameter of DH algorithm.
primeLength: It holds a number. It is the prime length of DH algorithm in bits.
generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.
groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.
publicKeyEncoding: It holds a string.
privateKeyEncoding: It holds an Object.
Return Value: It returns a new asymmetric key pair of the given type i.e, It returns an object that includes a private key and a public key that holds the string, buffer, and KeyObject.
Below examples illustrate the use of crypto.generateKeyPairSync() method in Node.js:
Example 1:
// Node.js program to demonstrate the// crypto.generateKeyPairSync() method // Including generateKeyPairSync from crypto moduleconst { generateKeyPairSync } = require('crypto'); // Including publicKey and privateKey from // generateKeyPairSync() method with its // parametersconst { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'secp256k1', // Options publicKeyEncoding: { type: 'spki', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der' }}); // Prints asymmetric key pairconsole.log("The public key is: ", publicKey);console.log();console.log("The private key is: ", privateKey);
Output:
The public key is: <Buffer 30 56 30 10 06 07
2a 86 48 ce 3d 02 01 06 052b 81 04 00 0a 03 42
00 04 d9 88 53 5b 21 84 f8 73 14 c8 0b 31 e2 2a
28 a5 4c 8f 68 23 65 84 d9 fe 20 3f ... >
The private key is: Buffer 30 81 84 02 01 00 30
10 06 07 2a 86 48 ce 3d 02 01 06 05 2b 81 04 00
0a 04 6d 30 6b 02 01 01 04 20 50 4a 87 c3 8c
968f 2b 41 f8 66 99 8a 95 ae 45 75 ... >
Example 2:
// Node.js program to demonstrate the// crypto.generateKeyPairSync() method // Including generateKeyPairSync from crypto moduleconst { generateKeyPairSync } = require('crypto'); // Including publicKey and privateKey from // generateKeyPairSync() method with its // parametersconst { publicKey, privateKey } = generateKeyPairSync('dsa', { modulusLength: 570, publicKeyEncoding: { type: 'spki', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der' }}); // Prints asymmetric key pair after encodingconsole.log("The public key is: ", publicKey.toString('base64'));console.log();console.log("The private key is: ", privateKey.toString('base64'));
Output:
The public key is: MIIBETCBwAYHKoZIzjgEATCBtAJJAM6084jk1Y6s/0sWQCs3k59AjV1GgAHb8gmB+Lxd/YVid+GySyss8tqhVQl49xho1DHoeJMNsVO6mcRqaSlSCPgmzqGaOvn2mQIdAKL5nGKJjDZF8Pb1SVvwWivhPShJiiHC2JjgrN8CSAqhzmg26/kEHYTZ3yNEGuguDhLvMAPdVG9pjTahLBytn8JQa3yQwLuPB4MzKfJ4d0pvKVZVnkMsatUe2ZkjnKoCjGlzwggd+QNMAAJJAMvsOBUjUKLhpkw4FZP7LIz0yYyOV1yYy84t8qSO42Yf6sNUfK6INnkFbpLHjFLcaDkFPqE5oRCIUqIVOhH0I7jNcGCN2m+ZWg==
The private key is: MIHnAgEAMIHABgcqhkjOOAQBMIG0AkkAzrTziOTVjqz/SxZAKzeTn0CNXUaAAdvyCYH4vF39hWJ34bJLKyzy2qFVCXj3GGjUMeh4kw2xU7qZxGppKVII+CbOoZo6+faZAh0AovmcYomMNkXw9vVJW/BaK+E9KEmKIcLYmOCs3wJICqHOaDbr+QQdhNnfI0Qa6C4OEu8wA91Ub2mNNqEsHK2fwlBrfJDAu48HgzMp8nh3Sm8pVlWeQyxq1R7ZmSOcqgKMaXPCCB35BB8CHQChh8yXsr/3dx3OdV6JmIWPcHe6dTHh6IOEIHer
Here, ‘dsa’ key type is used.
Reference: https://nodejs.org/api/crypto.html#crypto_crypto_generatekeypairsync_type_options
Node.js-crypto-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js path.resolve() Method
Node.js CRUD Operations Using Mongoose and MongoDB Atlas
Node.js fs.readdir() Method
Express.js res.render() Function
Node.js First Application
Express.js express.Router() Function
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
Top 10 Angular Libraries For Web Developers
How to create footer to stay at the bottom of a Web page? | [
{
"code": null,
"e": 24521,
"s": 24493,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 25181,
"s": 24521,
"text": "The crypto.generateKeyPairSync() method is an inbuilt application programming interface of crypto module which is used to generate a new asymmetric key pair of the specified type. For example, the currently supported key types are RSA, DSA, EC, Ed25519, Ed448, X25519, X448, and DH. Moreover, if option’s publicKeyEncoding or privateKeyEncoding is stated here, then this function acts as if keyObject.export() had been called on its output. Else, the particular part of the key is returned as a KeyObject.However, it is suggested to encode the public keys as ‘spki’ and private keys as ‘pkcs8’ with a strong passphrase, in order to keep the passphrase secret."
},
{
"code": null,
"e": 25189,
"s": 25181,
"text": "Syntax:"
},
{
"code": null,
"e": 25233,
"s": 25189,
"text": "crypto.generateKeyPairSync( type, options )"
},
{
"code": null,
"e": 25319,
"s": 25233,
"text": "Parameters: This method accept two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25471,
"s": 25319,
"text": "type: It holds a string and it must include one or more of the following algorithms: ‘rsa’, ‘dsa’, ‘ec’, ‘ed25519’, ‘ed448’, ‘x25519’, ‘x448’, or ‘dh’."
},
{
"code": null,
"e": 26330,
"s": 25471,
"text": "options: It is of type object. It can hold the following parameters:modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.prime: It holds a buffer. It is the prime parameter of DH algorithm.primeLength: It holds a number. It is the prime length of DH algorithm in bits.generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.publicKeyEncoding: It holds a string.privateKeyEncoding: It holds an Object."
},
{
"code": null,
"e": 27121,
"s": 26330,
"text": "modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.prime: It holds a buffer. It is the prime parameter of DH algorithm.primeLength: It holds a number. It is the prime length of DH algorithm in bits.generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.publicKeyEncoding: It holds a string.privateKeyEncoding: It holds an Object."
},
{
"code": null,
"e": 27233,
"s": 27121,
"text": "modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only."
},
{
"code": null,
"e": 27345,
"s": 27233,
"text": "publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001."
},
{
"code": null,
"e": 27425,
"s": 27345,
"text": "divisorLength: It holds a number. It is the size of q in bits of DSA algorithm."
},
{
"code": null,
"e": 27512,
"s": 27425,
"text": "namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm."
},
{
"code": null,
"e": 27581,
"s": 27512,
"text": "prime: It holds a buffer. It is the prime parameter of DH algorithm."
},
{
"code": null,
"e": 27661,
"s": 27581,
"text": "primeLength: It holds a number. It is the prime length of DH algorithm in bits."
},
{
"code": null,
"e": 27762,
"s": 27661,
"text": "generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2."
},
{
"code": null,
"e": 27843,
"s": 27762,
"text": "groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm."
},
{
"code": null,
"e": 27881,
"s": 27843,
"text": "publicKeyEncoding: It holds a string."
},
{
"code": null,
"e": 27921,
"s": 27881,
"text": "privateKeyEncoding: It holds an Object."
},
{
"code": null,
"e": 28107,
"s": 27921,
"text": "Return Value: It returns a new asymmetric key pair of the given type i.e, It returns an object that includes a private key and a public key that holds the string, buffer, and KeyObject."
},
{
"code": null,
"e": 28192,
"s": 28107,
"text": "Below examples illustrate the use of crypto.generateKeyPairSync() method in Node.js:"
},
{
"code": null,
"e": 28203,
"s": 28192,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the// crypto.generateKeyPairSync() method // Including generateKeyPairSync from crypto moduleconst { generateKeyPairSync } = require('crypto'); // Including publicKey and privateKey from // generateKeyPairSync() method with its // parametersconst { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'secp256k1', // Options publicKeyEncoding: { type: 'spki', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der' }}); // Prints asymmetric key pairconsole.log(\"The public key is: \", publicKey);console.log();console.log(\"The private key is: \", privateKey);",
"e": 28846,
"s": 28203,
"text": null
},
{
"code": null,
"e": 28854,
"s": 28846,
"text": "Output:"
},
{
"code": null,
"e": 29221,
"s": 28854,
"text": "The public key is: <Buffer 30 56 30 10 06 07\n2a 86 48 ce 3d 02 01 06 052b 81 04 00 0a 03 42\n00 04 d9 88 53 5b 21 84 f8 73 14 c8 0b 31 e2 2a\n28 a5 4c 8f 68 23 65 84 d9 fe 20 3f ... >\n\nThe private key is: Buffer 30 81 84 02 01 00 30\n10 06 07 2a 86 48 ce 3d 02 01 06 05 2b 81 04 00\n0a 04 6d 30 6b 02 01 01 04 20 50 4a 87 c3 8c\n968f 2b 41 f8 66 99 8a 95 ae 45 75 ... >\n"
},
{
"code": null,
"e": 29232,
"s": 29221,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the// crypto.generateKeyPairSync() method // Including generateKeyPairSync from crypto moduleconst { generateKeyPairSync } = require('crypto'); // Including publicKey and privateKey from // generateKeyPairSync() method with its // parametersconst { publicKey, privateKey } = generateKeyPairSync('dsa', { modulusLength: 570, publicKeyEncoding: { type: 'spki', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der' }}); // Prints asymmetric key pair after encodingconsole.log(\"The public key is: \", publicKey.toString('base64'));console.log();console.log(\"The private key is: \", privateKey.toString('base64'));",
"e": 29927,
"s": 29232,
"text": null
},
{
"code": null,
"e": 29935,
"s": 29927,
"text": "Output:"
},
{
"code": null,
"e": 30663,
"s": 29935,
"text": "The public key is: MIIBETCBwAYHKoZIzjgEATCBtAJJAM6084jk1Y6s/0sWQCs3k59AjV1GgAHb8gmB+Lxd/YVid+GySyss8tqhVQl49xho1DHoeJMNsVO6mcRqaSlSCPgmzqGaOvn2mQIdAKL5nGKJjDZF8Pb1SVvwWivhPShJiiHC2JjgrN8CSAqhzmg26/kEHYTZ3yNEGuguDhLvMAPdVG9pjTahLBytn8JQa3yQwLuPB4MzKfJ4d0pvKVZVnkMsatUe2ZkjnKoCjGlzwggd+QNMAAJJAMvsOBUjUKLhpkw4FZP7LIz0yYyOV1yYy84t8qSO42Yf6sNUfK6INnkFbpLHjFLcaDkFPqE5oRCIUqIVOhH0I7jNcGCN2m+ZWg==\n\nThe private key is: MIHnAgEAMIHABgcqhkjOOAQBMIG0AkkAzrTziOTVjqz/SxZAKzeTn0CNXUaAAdvyCYH4vF39hWJ34bJLKyzy2qFVCXj3GGjUMeh4kw2xU7qZxGppKVII+CbOoZo6+faZAh0AovmcYomMNkXw9vVJW/BaK+E9KEmKIcLYmOCs3wJICqHOaDbr+QQdhNnfI0Qa6C4OEu8wA91Ub2mNNqEsHK2fwlBrfJDAu48HgzMp8nh3Sm8pVlWeQyxq1R7ZmSOcqgKMaXPCCB35BB8CHQChh8yXsr/3dx3OdV6JmIWPcHe6dTHh6IOEIHer"
},
{
"code": null,
"e": 30693,
"s": 30663,
"text": "Here, ‘dsa’ key type is used."
},
{
"code": null,
"e": 30786,
"s": 30693,
"text": "Reference: https://nodejs.org/api/crypto.html#crypto_crypto_generatekeypairsync_type_options"
},
{
"code": null,
"e": 30808,
"s": 30786,
"text": "Node.js-crypto-module"
},
{
"code": null,
"e": 30816,
"s": 30808,
"text": "Node.js"
},
{
"code": null,
"e": 30833,
"s": 30816,
"text": "Web Technologies"
},
{
"code": null,
"e": 30931,
"s": 30833,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30940,
"s": 30931,
"text": "Comments"
},
{
"code": null,
"e": 30953,
"s": 30940,
"text": "Old Comments"
},
{
"code": null,
"e": 30983,
"s": 30953,
"text": "Node.js path.resolve() Method"
},
{
"code": null,
"e": 31040,
"s": 30983,
"text": "Node.js CRUD Operations Using Mongoose and MongoDB Atlas"
},
{
"code": null,
"e": 31068,
"s": 31040,
"text": "Node.js fs.readdir() Method"
},
{
"code": null,
"e": 31101,
"s": 31068,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 31127,
"s": 31101,
"text": "Node.js First Application"
},
{
"code": null,
"e": 31164,
"s": 31127,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 31209,
"s": 31164,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31269,
"s": 31209,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 31313,
"s": 31269,
"text": "Top 10 Angular Libraries For Web Developers"
}
] |
How to get sequence number in loops with JavaScript? | To get sequence number in loops, use the forEach() loop. Following is the code −
let studentDetails =
[
{
id: 101, details: [{name: 'John'}, {name: 'David'},{name: 'Bob'}]},
{id:102, details: [{name:'Carol'},{name:'David'},
{name:'Mike'}]
}
];
var counter = 1;
studentDetails.forEach(function(k){
k.details.forEach(function(f) {
console.log(counter++);
}
);
});
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo159.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo159.js
1
2
3
4
5
6 | [
{
"code": null,
"e": 1143,
"s": 1062,
"text": "To get sequence number in loops, use the forEach() loop. Following is the code −"
},
{
"code": null,
"e": 1469,
"s": 1143,
"text": "let studentDetails =\n[\n {\n id: 101, details: [{name: 'John'}, {name: 'David'},{name: 'Bob'}]},\n {id:102, details: [{name:'Carol'},{name:'David'},\n {name:'Mike'}]\n }\n];\nvar counter = 1;\nstudentDetails.forEach(function(k){\n k.details.forEach(function(f) {\n console.log(counter++);\n }\n );\n});"
},
{
"code": null,
"e": 1535,
"s": 1469,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1553,
"s": 1535,
"text": "node fileName.js."
},
{
"code": null,
"e": 1628,
"s": 1553,
"text": "Here, my file name is demo159.js. This will produce the following output −"
},
{
"code": null,
"e": 1690,
"s": 1628,
"text": "PS C:\\Users\\Amit\\JavaScript-code> node demo159.js\n1\n2\n3\n4\n5\n6"
}
] |
How to implement MongoDB $or query? | The syntax is as follows for the $or query in MongoDB −
db.yourCollectionName.find({ $or : [ { "yourFieldName" : "yourValue1" }, {"yourFieldName":"yourValue2"},...........N ] } ).pretty();
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.orDemo.insertOne({"UserName":"Larry","UserAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9491fd4cf1f7a64fa4df4c")
}
> db.orDemo.insertOne({"UserName":"David","UserAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9492074cf1f7a64fa4df4d")
}
> db.orDemo.insertOne({"UserName":"Mike","UserAge":25});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c94920e4cf1f7a64fa4df4e")
}
> db.orDemo.insertOne({"UserName":"Sam","UserAge":20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9492144cf1f7a64fa4df4f")
}
> db.orDemo.insertOne({"UserName":"Carol","UserAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c94921d4cf1f7a64fa4df50")
}
> db.orDemo.insertOne({"UserName":"Bob","UserAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c94922c4cf1f7a64fa4df51")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.orDemo.find().pretty();
The following is the output:
{
"_id" : ObjectId("5c9491fd4cf1f7a64fa4df4c"),
"UserName" : "Larry",
"UserAge" : 23
}
{
"_id" : ObjectId("5c9492074cf1f7a64fa4df4d"),
"UserName" : "David",
"UserAge" : 21
}
{
"_id" : ObjectId("5c94920e4cf1f7a64fa4df4e"),
"UserName" : "Mike",
"UserAge" : 25
}
{
"_id" : ObjectId("5c9492144cf1f7a64fa4df4f"),
"UserName" : "Sam",
"UserAge" : 20
}
{
"_id" : ObjectId("5c94921d4cf1f7a64fa4df50"),
"UserName" : "Carol",
"UserAge" : 24
}
{
"_id" : ObjectId("5c94922c4cf1f7a64fa4df51"),
"UserName" : "Bob",
"UserAge" : 22
}
Here is the query for $or −
> db.orDemo.find({ $or : [ { "UserName" : "Carol" }, {"UserName":"Larry"} ] } ).pretty();
The following is the output:
{
"_id" : ObjectId("5c9491fd4cf1f7a64fa4df4c"),
"UserName" : "Larry",
"UserAge" : 23
}
{
"_id" : ObjectId("5c94921d4cf1f7a64fa4df50"),
"UserName" : "Carol",
"UserAge" : 24
} | [
{
"code": null,
"e": 1118,
"s": 1062,
"text": "The syntax is as follows for the $or query in MongoDB −"
},
{
"code": null,
"e": 1251,
"s": 1118,
"text": "db.yourCollectionName.find({ $or : [ { \"yourFieldName\" : \"yourValue1\" }, {\"yourFieldName\":\"yourValue2\"},...........N ] } ).pretty();"
},
{
"code": null,
"e": 1389,
"s": 1251,
"text": "To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −"
},
{
"code": null,
"e": 2242,
"s": 1389,
"text": "> db.orDemo.insertOne({\"UserName\":\"Larry\",\"UserAge\":23});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9491fd4cf1f7a64fa4df4c\")\n}\n> db.orDemo.insertOne({\"UserName\":\"David\",\"UserAge\":21});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9492074cf1f7a64fa4df4d\")\n}\n> db.orDemo.insertOne({\"UserName\":\"Mike\",\"UserAge\":25});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c94920e4cf1f7a64fa4df4e\")\n}\n> db.orDemo.insertOne({\"UserName\":\"Sam\",\"UserAge\":20});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9492144cf1f7a64fa4df4f\")\n}\n> db.orDemo.insertOne({\"UserName\":\"Carol\",\"UserAge\":24});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c94921d4cf1f7a64fa4df50\")\n}\n> db.orDemo.insertOne({\"UserName\":\"Bob\",\"UserAge\":22});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c94922c4cf1f7a64fa4df51\")\n}"
},
{
"code": null,
"e": 2340,
"s": 2242,
"text": "Display all documents from a collection with the help of find() method. The query is as follows −"
},
{
"code": null,
"e": 2369,
"s": 2340,
"text": "> db.orDemo.find().pretty();"
},
{
"code": null,
"e": 2398,
"s": 2369,
"text": "The following is the output:"
},
{
"code": null,
"e": 2969,
"s": 2398,
"text": "{\n \"_id\" : ObjectId(\"5c9491fd4cf1f7a64fa4df4c\"),\n \"UserName\" : \"Larry\",\n \"UserAge\" : 23\n}\n{\n \"_id\" : ObjectId(\"5c9492074cf1f7a64fa4df4d\"),\n \"UserName\" : \"David\",\n \"UserAge\" : 21\n}\n{\n \"_id\" : ObjectId(\"5c94920e4cf1f7a64fa4df4e\"),\n \"UserName\" : \"Mike\",\n \"UserAge\" : 25\n}\n{\n \"_id\" : ObjectId(\"5c9492144cf1f7a64fa4df4f\"),\n \"UserName\" : \"Sam\",\n \"UserAge\" : 20\n}\n{\n \"_id\" : ObjectId(\"5c94921d4cf1f7a64fa4df50\"),\n \"UserName\" : \"Carol\",\n \"UserAge\" : 24\n}\n{\n \"_id\" : ObjectId(\"5c94922c4cf1f7a64fa4df51\"),\n \"UserName\" : \"Bob\",\n \"UserAge\" : 22\n}"
},
{
"code": null,
"e": 2997,
"s": 2969,
"text": "Here is the query for $or −"
},
{
"code": null,
"e": 3087,
"s": 2997,
"text": "> db.orDemo.find({ $or : [ { \"UserName\" : \"Carol\" }, {\"UserName\":\"Larry\"} ] } ).pretty();"
},
{
"code": null,
"e": 3116,
"s": 3087,
"text": "The following is the output:"
},
{
"code": null,
"e": 3308,
"s": 3116,
"text": "{\n \"_id\" : ObjectId(\"5c9491fd4cf1f7a64fa4df4c\"),\n \"UserName\" : \"Larry\",\n \"UserAge\" : 23\n}\n{\n \"_id\" : ObjectId(\"5c94921d4cf1f7a64fa4df50\"),\n \"UserName\" : \"Carol\",\n \"UserAge\" : 24\n}"
}
] |
How to link jQuery in HTML page? | jQuery is a fast and concise JavaScript library primarily designed with a nice motto − Write less, do more. The main purpose of this library is to make it easier to use JavaScript on our website. jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery wraps many lines of JavaScript code into methods that we can call with a single line of code.
There are two ways to link jQuery in an HTML page -
By downloading the jQuery library locally - you can download the jQuery file on your local machine and include it in the HTML page.
By downloading the jQuery library locally - you can download the jQuery file on your local machine and include it in the HTML page.
By including the jQuery from a CDN - you can add the jQuery library into your HTML page directly from a Content Delivery Network (CDN).
By including the jQuery from a CDN - you can add the jQuery library into your HTML page directly from a Content Delivery Network (CDN).
Download the latest version of jQuery library from the official website https://jquery.com/download/. You can download any of the four types of available jQuery versions- uncompressed, minified, slim and slim & minified.
Download the latest version of jQuery library from the official website https://jquery.com/download/. You can download any of the four types of available jQuery versions- uncompressed, minified, slim and slim & minified.
Now put the downloaded jquery-3.6.0.min.js file in a directory of your website, e.g. /jquery.
Now put the downloaded jquery-3.6.0.min.js file in a directory of your website, e.g. /jquery.
We can link jQuery in an HTML page by using a script tag and providing the downloaded jQuery library file address as the src attribute. The jquery-3.6.0.min.js can be added like below.
We can link jQuery in an HTML page by using a script tag and providing the downloaded jQuery library file address as the src attribute. The jquery-3.6.0.min.js can be added like below.
<head>
<script type="text/javascript" src="/jquery/jquery-3.6.0.min.js"></script>
</head>
Let’s understand with the help of a complete example.
In the example below we include jQuery library in our HTML page as follows –
Live Demo
<html>
<head>
<title>The jQuery Local Example</title>
<script type="text/javascript" src="/jquery/jquery-3.6.0.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
document.write("Hello, World! We are using jQuery from local machine");
});
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
This will produce the following result -
Hello, World! We are using jQuery from local machine
We can link the jQuery library in our HTML page directly from a Content Delivery Network. There are different CDNs that provide the latest version of the jQuery library. For Example, Google, Microsoft, Cloudflare CDNs, and jQuery’s own CDN.
Let’s understand how to link jQuery from these CDNs each with help of examples.
We can link jQuery in an HTML page by using a script tag and providing a jQuery Google CDN address as the src attribute. The jquery.min.js can be added like below.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Here, in the example below we link the jQuery library in our HTML page as follows −
<!DOCTYPE html>
<html>
<head>
<style>
div {
height: 100px;
width: 100px;
background-color: red;
border-radius: 5px;
border: 2px solid blue;
margin-left: 50px;
margin-top: 50px;
display: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>$(document).ready(function() {
$('div').fadeIn('slow');
});
</script>
</head>
<body>
<div></div>
</body>
</html>
Here the fadeIn() method changes the opacity, for selected elements, from hidden to visible. It is to specify the speed of the fading effect, which can be slow or fast.
We can link jQuery in an HTML page by using a script tag and providing a jQuery Microsoft CDN address as the src attribute. The jquery-3.6.0.js can be added like below.
<script src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.0.js'></script>
Here, in the example below we link the jQuery library from Microsoft CDN in our HTML page −
Live Demo
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery from Microsoft AJAX CDN</title>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.6.0.min.js"></script>
<script>
function domReady() {
$('#btn').click( showMessage );
}
function showMessage() {
$('#message').fadeIn('slow');
}
$( domReady );
</script>
</head>
<body>
<button id="btn">Show Message</button>
<div id="message" style="display:none">
<p> Hello, World! We are using jQuery from Microsoft CDN. </p>
</div>
</body>
</html>
When you click on the “Show Message” button, the message will be displayed.
We can also use Cloudflare CDN to link the jQuery library to our HTML page. To link jQuery in an HTML page we add jQuery Cloudflare CDN address to the src attribute of the script tag. The jquery.min.js can be added like below.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" ></script>
Here, in the example below we link the jQuery library from Cloudflare CDN in your HTML page −
<html>
<head>
<title>jQuery Google CDN</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" ></script>
<script>
$(document).ready(function() {
document.write("Hello, World! We are using jQuery from Cloudflare CDN.");
});
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
This will produce the following result -
Hello, World! We are using jQuery from Cloudflare CDN.
We can also use jQuery CDN to link the jQuery library in our HTML page. To link jQuery in an HTML page we add the jQuery CDN address to the src attribute of the script tag. We also have to add integrity and crossorigin to the script. We can directly copy the script code from the jQuery website. jquery-3.6.0.min.js can be added like below-
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
Here, in the example below we link the jQuery library from jQuery CDN in your HTML page −
<html>
<head>
<title>jQuery Google CDN</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
document.write("Hello, World! We are using jQuery from jQuery CDN.");
});
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
This will produce the following result -
Hello, World! We are using jQuery from jQuery CDN. | [
{
"code": null,
"e": 1479,
"s": 1062,
"text": "jQuery is a fast and concise JavaScript library primarily designed with a nice motto − Write less, do more. The main purpose of this library is to make it easier to use JavaScript on our website. jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery wraps many lines of JavaScript code into methods that we can call with a single line of code."
},
{
"code": null,
"e": 1531,
"s": 1479,
"text": "There are two ways to link jQuery in an HTML page -"
},
{
"code": null,
"e": 1664,
"s": 1531,
"text": "By downloading the jQuery library locally - you can download the jQuery file on your local machine and include it in the HTML page."
},
{
"code": null,
"e": 1797,
"s": 1664,
"text": "By downloading the jQuery library locally - you can download the jQuery file on your local machine and include it in the HTML page."
},
{
"code": null,
"e": 1933,
"s": 1797,
"text": "By including the jQuery from a CDN - you can add the jQuery library into your HTML page directly from a Content Delivery Network (CDN)."
},
{
"code": null,
"e": 2069,
"s": 1933,
"text": "By including the jQuery from a CDN - you can add the jQuery library into your HTML page directly from a Content Delivery Network (CDN)."
},
{
"code": null,
"e": 2290,
"s": 2069,
"text": "Download the latest version of jQuery library from the official website https://jquery.com/download/. You can download any of the four types of available jQuery versions- uncompressed, minified, slim and slim & minified."
},
{
"code": null,
"e": 2511,
"s": 2290,
"text": "Download the latest version of jQuery library from the official website https://jquery.com/download/. You can download any of the four types of available jQuery versions- uncompressed, minified, slim and slim & minified."
},
{
"code": null,
"e": 2605,
"s": 2511,
"text": "Now put the downloaded jquery-3.6.0.min.js file in a directory of your website, e.g. /jquery."
},
{
"code": null,
"e": 2699,
"s": 2605,
"text": "Now put the downloaded jquery-3.6.0.min.js file in a directory of your website, e.g. /jquery."
},
{
"code": null,
"e": 2884,
"s": 2699,
"text": "We can link jQuery in an HTML page by using a script tag and providing the downloaded jQuery library file address as the src attribute. The jquery-3.6.0.min.js can be added like below."
},
{
"code": null,
"e": 3069,
"s": 2884,
"text": "We can link jQuery in an HTML page by using a script tag and providing the downloaded jQuery library file address as the src attribute. The jquery-3.6.0.min.js can be added like below."
},
{
"code": null,
"e": 3159,
"s": 3069,
"text": "<head>\n<script type=\"text/javascript\" src=\"/jquery/jquery-3.6.0.min.js\"></script>\n</head>"
},
{
"code": null,
"e": 3213,
"s": 3159,
"text": "Let’s understand with the help of a complete example."
},
{
"code": null,
"e": 3290,
"s": 3213,
"text": "In the example below we include jQuery library in our HTML page as follows –"
},
{
"code": null,
"e": 3301,
"s": 3290,
"text": " Live Demo"
},
{
"code": null,
"e": 3704,
"s": 3301,
"text": "<html>\n <head>\n <title>The jQuery Local Example</title>\n <script type=\"text/javascript\" src=\"/jquery/jquery-3.6.0.min.js\">\n </script>\n <script type=\"text/javascript\">\n $(document).ready(function() {\n document.write(\"Hello, World! We are using jQuery from local machine\");\n });\n </script>\n </head>\n <body>\n <h1>Hello</h1>\n </body>\n</html>"
},
{
"code": null,
"e": 3745,
"s": 3704,
"text": "This will produce the following result -"
},
{
"code": null,
"e": 3798,
"s": 3745,
"text": "Hello, World! We are using jQuery from local machine"
},
{
"code": null,
"e": 4039,
"s": 3798,
"text": "We can link the jQuery library in our HTML page directly from a Content Delivery Network. There are different CDNs that provide the latest version of the jQuery library. For Example, Google, Microsoft, Cloudflare CDNs, and jQuery’s own CDN."
},
{
"code": null,
"e": 4119,
"s": 4039,
"text": "Let’s understand how to link jQuery from these CDNs each with help of examples."
},
{
"code": null,
"e": 4283,
"s": 4119,
"text": "We can link jQuery in an HTML page by using a script tag and providing a jQuery Google CDN address as the src attribute. The jquery.min.js can be added like below."
},
{
"code": null,
"e": 4372,
"s": 4283,
"text": "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"></script>"
},
{
"code": null,
"e": 4456,
"s": 4372,
"text": "Here, in the example below we link the jQuery library in our HTML page as follows −"
},
{
"code": null,
"e": 5052,
"s": 4456,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n div {\n height: 100px;\n width: 100px;\n background-color: red;\n border-radius: 5px;\n border: 2px solid blue;\n margin-left: 50px;\n margin-top: 50px;\n display: none;\n }\n </style>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"></script>\n <script>$(document).ready(function() {\n $('div').fadeIn('slow');\n });\n </script>\n </head>\n <body>\n <div></div>\n </body>\n</html>"
},
{
"code": null,
"e": 5221,
"s": 5052,
"text": "Here the fadeIn() method changes the opacity, for selected elements, from hidden to visible. It is to specify the speed of the fading effect, which can be slow or fast."
},
{
"code": null,
"e": 5390,
"s": 5221,
"text": "We can link jQuery in an HTML page by using a script tag and providing a jQuery Microsoft CDN address as the src attribute. The jquery-3.6.0.js can be added like below."
},
{
"code": null,
"e": 5468,
"s": 5390,
"text": "<script src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.0.js'></script>"
},
{
"code": null,
"e": 5560,
"s": 5468,
"text": "Here, in the example below we link the jQuery library from Microsoft CDN in our HTML page −"
},
{
"code": null,
"e": 5571,
"s": 5560,
"text": " Live Demo"
},
{
"code": null,
"e": 6169,
"s": 5571,
"text": "<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n <title>jQuery from Microsoft AJAX CDN</title>\n <script src=\"https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.6.0.min.js\"></script>\n <script>\n function domReady() {\n $('#btn').click( showMessage );\n }\n function showMessage() {\n $('#message').fadeIn('slow');\n }\n $( domReady );\n </script>\n</head>\n<body>\n <button id=\"btn\">Show Message</button>\n <div id=\"message\" style=\"display:none\">\n <p> Hello, World! We are using jQuery from Microsoft CDN. </p>\n </div>\n</body>\n</html>"
},
{
"code": null,
"e": 6245,
"s": 6169,
"text": "When you click on the “Show Message” button, the message will be displayed."
},
{
"code": null,
"e": 6472,
"s": 6245,
"text": "We can also use Cloudflare CDN to link the jQuery library to our HTML page. To link jQuery in an HTML page we add jQuery Cloudflare CDN address to the src attribute of the script tag. The jquery.min.js can be added like below."
},
{
"code": null,
"e": 6563,
"s": 6472,
"text": "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js\" ></script>"
},
{
"code": null,
"e": 6657,
"s": 6563,
"text": "Here, in the example below we link the jQuery library from Cloudflare CDN in your HTML page −"
},
{
"code": null,
"e": 7041,
"s": 6657,
"text": "<html>\n <head>\n <title>jQuery Google CDN</title>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js\" ></script>\n <script>\n $(document).ready(function() {\n document.write(\"Hello, World! We are using jQuery from Cloudflare CDN.\");\n });\n </script>\n </head>\n <body>\n <h1>Hello</h1>\n </body>\n</html>"
},
{
"code": null,
"e": 7082,
"s": 7041,
"text": "This will produce the following result -"
},
{
"code": null,
"e": 7137,
"s": 7082,
"text": "Hello, World! We are using jQuery from Cloudflare CDN."
},
{
"code": null,
"e": 7478,
"s": 7137,
"text": "We can also use jQuery CDN to link the jQuery library in our HTML page. To link jQuery in an HTML page we add the jQuery CDN address to the src attribute of the script tag. We also have to add integrity and crossorigin to the script. We can directly copy the script code from the jQuery website. jquery-3.6.0.min.js can be added like below-"
},
{
"code": null,
"e": 7634,
"s": 7478,
"text": "<script src=\"https://code.jquery.com/jquery-3.6.0.min.js\" integrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\" crossorigin=\"anonymous\"></script>"
},
{
"code": null,
"e": 7724,
"s": 7634,
"text": "Here, in the example below we link the jQuery library from jQuery CDN in your HTML page −"
},
{
"code": null,
"e": 8168,
"s": 7724,
"text": "<html>\n <head>\n <title>jQuery Google CDN</title>\n <script src=\"https://code.jquery.com/jquery-3.6.0.min.js\" integrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\"crossorigin=\"anonymous\"></script>\n <script>\n $(document).ready(function() {\n document.write(\"Hello, World! We are using jQuery from jQuery CDN.\");\n });\n </script>\n </head>\n <body>\n <h1>Hello</h1>\n </body>\n</html>"
},
{
"code": null,
"e": 8209,
"s": 8168,
"text": "This will produce the following result -"
},
{
"code": null,
"e": 8260,
"s": 8209,
"text": "Hello, World! We are using jQuery from jQuery CDN."
}
] |
How to display mean in a histogram using ggplot2 in R? | To display mean in a histogram using ggplot2, we can use geom_vline function where we need to define the x-intercept value as the mean of the column for which we want to create the histogram. Also, we can change the size of the line for mean in the histogram by using size argument inside geom_vline function.
Consider the below data frame −
x<-rnorm(20000)
df<-data.frame(x)
Loading ggplot2 package and creating histogram of x −
library(ggplot2)
ggplot(df,aes(x))+geom_histogram(bins=20)
Creating histogram of x with mean displayed on the plot −
ggplot(df,aes(x))+geom_histogram(bins=20)+geom_vline(aes(xintercept=mean(x),size=1)) | [
{
"code": null,
"e": 1372,
"s": 1062,
"text": "To display mean in a histogram using ggplot2, we can use geom_vline function where we need to define the x-intercept value as the mean of the column for which we want to create the histogram. Also, we can change the size of the line for mean in the histogram by using size argument inside geom_vline function."
},
{
"code": null,
"e": 1404,
"s": 1372,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1438,
"s": 1404,
"text": "x<-rnorm(20000)\ndf<-data.frame(x)"
},
{
"code": null,
"e": 1492,
"s": 1438,
"text": "Loading ggplot2 package and creating histogram of x −"
},
{
"code": null,
"e": 1551,
"s": 1492,
"text": "library(ggplot2)\nggplot(df,aes(x))+geom_histogram(bins=20)"
},
{
"code": null,
"e": 1609,
"s": 1551,
"text": "Creating histogram of x with mean displayed on the plot −"
},
{
"code": null,
"e": 1694,
"s": 1609,
"text": "ggplot(df,aes(x))+geom_histogram(bins=20)+geom_vline(aes(xintercept=mean(x),size=1))"
}
] |
How to Run a Command with Time Limit (Timeout) In Linux | Sometimes a Unix command may run for a very long time without giving the final output or it make a processing giving partial output from time to time. In such scenario we will like to put a time frame within which either the command mast complete for the process should abort. This is achieved by using below options.
The Timeout tool forces a command tour abort if it cannot complete within a given time frame. Below is the syntax and example.
timeout DURATION COMMAND [ARG]...
Where Duration is the number seconds you want the command to run
Before aborting if the execution is not complete. In duration flag we have,
s - seconds
m - minutes
h - hours
d - days
In the below example we use the ping command to ping our website and the process remains on only for 5 seconds after which the command stops running automatically.
$ timeout 5s ping tutorialspoint.com
Running the above code gives us the following result −
PING tutorialspoint.com (94.130.82.52) 56(84) bytes of data.
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=1 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=2 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=3 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=4 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=5 ttl=128 time=127 ms
The timelimit program needs to be installed, to get this feature for killing the command after a certain time. It will pass the warning signal and then after timeout, it will send the kill signal. You can also pass argumnets like - arguments like, killtime, warntime etc. So this command gives us a finer control to warn and kill the commands.
First we install the program using below command.
sudo apt-get install timelimit
Next we see the below example to use timelimit. Here –t specifies the maximum execution time of the process in seconds before sending warnsig and T is the maximum execution time of the process before sending killsig after warnsig has been sent.
timelimit -t6 -T12 ping tutorialspoint.com
Running the above code gives us the following result −
PING tutorialspoint.com (94.130.82.52) 56(84) bytes of data.
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=1 ttl=128 time=127 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=2 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=3 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=4 ttl=128 time=127 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=5 ttl=128 time=128 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=6 ttl=128 time=126 ms
timelimit: sending warning signal 15 | [
{
"code": null,
"e": 1380,
"s": 1062,
"text": "Sometimes a Unix command may run for a very long time without giving the final output or it make a processing giving partial output from time to time. In such scenario we will like to put a time frame within which either the command mast complete for the process should abort. This is achieved by using below options."
},
{
"code": null,
"e": 1507,
"s": 1380,
"text": "The Timeout tool forces a command tour abort if it cannot complete within a given time frame. Below is the syntax and example."
},
{
"code": null,
"e": 1726,
"s": 1507,
"text": "timeout DURATION COMMAND [ARG]...\n\nWhere Duration is the number seconds you want the command to run\nBefore aborting if the execution is not complete. In duration flag we have,\ns - seconds\nm - minutes\nh - hours\nd - days"
},
{
"code": null,
"e": 1890,
"s": 1726,
"text": "In the below example we use the ping command to ping our website and the process remains on only for 5 seconds after which the command stops running automatically."
},
{
"code": null,
"e": 1927,
"s": 1890,
"text": "$ timeout 5s ping tutorialspoint.com"
},
{
"code": null,
"e": 1982,
"s": 1927,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2443,
"s": 1982,
"text": "PING tutorialspoint.com (94.130.82.52) 56(84) bytes of data.\n64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=1 ttl=128 time=126 ms\n64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=2 ttl=128 time=126 ms\n64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=3 ttl=128 time=126 ms\n64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=4 ttl=128 time=126 ms\n64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=5 ttl=128 time=127 ms"
},
{
"code": null,
"e": 2787,
"s": 2443,
"text": "The timelimit program needs to be installed, to get this feature for killing the command after a certain time. It will pass the warning signal and then after timeout, it will send the kill signal. You can also pass argumnets like - arguments like, killtime, warntime etc. So this command gives us a finer control to warn and kill the commands."
},
{
"code": null,
"e": 2837,
"s": 2787,
"text": "First we install the program using below command."
},
{
"code": null,
"e": 2868,
"s": 2837,
"text": "sudo apt-get install timelimit"
},
{
"code": null,
"e": 3113,
"s": 2868,
"text": "Next we see the below example to use timelimit. Here –t specifies the maximum execution time of the process in seconds before sending warnsig and T is the maximum execution time of the process before sending killsig after warnsig has been sent."
},
{
"code": null,
"e": 3156,
"s": 3113,
"text": "timelimit -t6 -T12 ping tutorialspoint.com"
},
{
"code": null,
"e": 3211,
"s": 3156,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3789,
"s": 3211,
"text": "PING tutorialspoint.com (94.130.82.52) 56(84) bytes of data.\n64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=1 ttl=128 time=127 ms\n64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=2 ttl=128 time=126 ms\n64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=3 ttl=128 time=126 ms\n64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=4 ttl=128 time=127 ms\n64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=5 ttl=128 time=128 ms\n64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=6 ttl=128 time=126 ms\ntimelimit: sending warning signal 15"
}
] |
Predicting Used Car Prices with Machine Learning Techniques | by Enes Gokce | Towards Data Science | You can reach all Python scripts of this study on my github page. If you are interested, you can also find the scripts used for data cleaning for this study in the same repository.
If you are interested in learning about a building a Machine Learning system from scratch including:
Justifications during data cleaning
Exploratory Data Analysis (EDA)
Performing machine learning models: Random Forest, Linear Regression, Ridge Regression, Lasso, KNN, XGBoost
Comparison of the performance of the models
Reporting the findings of the study in a professional manner
The prices of new cars in the industry is fixed by the manufacturer with some additional costs incurred by the Government in the form of taxes. So, customers buying a new car can be assured of the money they invest to be worthy. But due to the increased price of new cars and the incapability of customers to buy new cars due to the lack of funds, used cars sales are on a global increase (Pal, Arora and Palakurthy, 2018). There is a need for a used car price prediction system to effectively determine the worthiness of the car using a variety of features. Even though there are websites that offers this service, their prediction method may not be the best. Besides, different models and systems may contribute on predicting power for a used car’s actual market value. It is important to know their actual market value while both buying and selling.
To be able to predict used cars market value can help both buyers and sellers.
Used car sellers (dealers): They are one of the biggest target group that can be interested in results of this study. If used car sellers better understand what makes a car desirable, what the important features are for a used car, then they may consider this knowledge and offer a better service.
Online pricing services: There are websites that offers an estimate value of a car. They may have a good prediction model. However, having a second model may help them to give a better prediction to their users. Therefore, the model developed in this study may help online web services that tells a used car’s market value.
Individuals: There are lots of individuals who are interested in the used car market at some points in their life because they wanted to sell their car or buy a used car. In this process, it’s a big corner to pay too much or sell less then it’s market value.
The data used in this project was downloaded from Kaggle. It was uploaded on Kaggle by Austin Reese who Kaggle.com user. Austin Reese scraped this data from craigslist with non-profit purpose. It contains most all relevant information that Craigslist provides on car sales including columns like price, condition, manufacturer, latitude/longitude, and 22 other categories.
Data Wrangling
In this section, it will be discussed about how data cleaning and wrangling methods are applied on the craigslist used cars data file.
Before making data cleaning, some explorations and data visualizations were applied on data set. This gave some idea and guide about how to deal with missing values and extreme values. After data cleaning, data exploration was applied again in order to understand cleaned version of the data.
Data cleaning: First step for data cleaning was to remove unnecessary features. For this purpose, ‘url’,’image_url’, ‘lat’, ‘long’, ‘city_url’, ‘desc’, ‘city’, ‘VIN’ features were dropped totally. As a next step, it was investigated number of null points and percentage of null data points for that feature (Table 1).
As a next step, extreme values were dropped because they inhibit prediction power of the model. Firstly, cars that had listed as more than $100.000 were dropped. There were only 580 out of 550313 data points that has over 100k price value. It addresses only small percentage of buyers. In addition, there were 61726 cars that has a price lower than $750. These values were also dropped from data-set because these prices are noise for the data. Secondly, cars that have odometer value over 300.000 miles and lower than 10 miles were dropped. And lastly, cars from earlier than 1985 were dropped. For our analysis, these data points can be considered as outliers.
As the second step, some missing values were filled with appropriate values. For the missing ‘condition’ values, it was paid attention to fill depending on category. Average odometer of all ‘condition’ sub-categories were calculated. Then, missing values were filled by considering this average odometer values for each condition sub-category. In addition, cars that have model value higher than 2019 were filled as ‘new’, and between 2017–2019 were filled as ‘like new’. At the end of this process, all missing values in ‘condition’ feature were cleaned.
Others were filled as by using ‘ffill’ method. This method propagates last valid observation forward to next valid. Thus, the last known value is available at every time point. Up to now, all missing values at odometer, condition, condition and price features were clear. After this step, all data became clean. After this operation, there were 380,962 observations in the data that will be studies and analyzed.
While exploring the data, we will look at the different combinations of features with the help of visuals. This will help us to understand our data better and give us some clue about pattern in data.
An examination of price trend
Price is the feature that we are predicting in this study. Before applying any models, taking a look at price data may give us some ideas.
By looking at Figure 1, it can be observed that most of the used cars are less than $20,000. In addition, we see that there are still considerable number of cars that is over $20k price. We can guess that all type of cars can be cheap or expensive. But, still excellent, like new, and good condition cars are the most popular cars in used car market (Figure 2). Salvage cars are following these three categories in popularity. Therefore, it is hard to make a strong estimate of a price of a car just by considering the type or condition of a car. But we can tell it certain condition cars are popular and higher chance to be sold.
Popular features of used cars
When buying a used car, people pay serious attention to the odometer value on the car. We can see that odometer changes the price of a car significantly (Figure 3). On the other hand, this does not mean that only low odometer cars are sold. Depending on the price, high odometer cars also have buyers (Figure 4). Furthermore, most popular used cars are the ones that has odometer around 100k. Until 150k odometer, there are many cars on the market.
Manufacturer of a car is another important variable on used car market. Ford and Chevrolet are one dominant manufacturer in North America (Figure 5). Toyota and Nissan follow the order as big manufacturers. It can be concluded that Japanese cars have a considerable share in used car market. However, American cars are still on demand and dominant.
Transmission: Transmission is another feature that has a dominant sub category in the used car market. According to Figure 6, automatic transmission has a strong effect on people’s preference on car. In Figure 6, it can be seen that after 2000, automatic transmission cars are in the increase. In 2009, it decreases. Global economic recession might have an impact on used car market and affect market. Another interesting trend is that after 2009, other transmission is on the increase. Its market share is still so low compared to automatic transmission, but it is still considerable. The increase in other transmission type can be caused by a couple reason. First possibility is that increase in continuously variable transmission (CVT). CVT is more environmentally friendly and fuel efficient. There might be a promotion for this kind of technology. Another possibility is that some seller on Craigslist website did not fill transmission section of the car information. The website might directly put them in the ‘other’ category. This also explains the increase in the ‘other’ category of transmission.
Drivetrain type: While evaluating a car, it’s important to understand what affects it’s condition. Figure 7 tells that 4wd drive cars more durable and reliable. It can be seen that 4wd cars are the most popular in terms of numbers. In the long run, they can keep their ability to run better compared to rwd and fwd drive train. 4wd has highest numbers of ‘excellent’, ‘like new’, and ‘good’ condition’ of cars. On the other hand, we need to keep in mind that compared to total number, it’s hard to say that 4wd cars higher rate of “excellent” and “like new” cars (Fig.7). In addition, by looking at table 4,
we can see that average odometers for all drivetrain types are so close to each other for all quantiles. This also tells that in the used car market, drive type may not affect with odometer of cars. But their popularity is different among drivers (Table 3 and Fig 8).
Test & Hypothesis
In order to understand what affects change in price of a used car, the relation between features available in the data sat will be examined by using inferential statistic methods. The primary assumption based on figures and tables is price must be affected by odometer and condition. There must be other features that affects price significantly. It will be investigated in the later phase of the study.
The first hypothesis:
Null Hypothesis: There is no significant relation between price and odometer of a car
Alt-Hypothesis: There is a significant relation between price and odometer.
The second hypothesis:
Null Hypothesis: There is no significant relation between price and condition of a car
Alt-Hypothesis: There is a significant relation between price and condition.
Odometer vs Price
Firstly, examine first hypothesis. Independent t-test is an appropriate method while examining the relation between two numerical variables. On the other hand, this test has some presumptions. Homogeneity of variances is one of the assumptions. In order to check whether homogeneity of variance assumption is violated or not, Levene test is applied.
Checking homogeneity of variance: The result of the Levene test:
Levene Result (statistic=335641.8310266318, p-value=0.0)
This means that homogeneity of variance is violated. In this case, we need to use Welch’s test. Welch’s t-test is a non-parametric univariate test that tests for a significant difference between the mean of two unrelated groups. It is an alternative to the independent t-test when there is a violation in the assumption of equality of variances. Therefore, it’s appropriate for this case. Here is the result of the Welch’s test:
Welch's t-test= 740.70p-value = 0.00Welch-Satterthwaite Degrees of Freedom= 276855.87
Here, p-value is significant. This tells that there is a significant relation between odometer and price of a car. For a reference, there is no harm to conduct an independent t-test. It can provide some ideas even though it’s not a robust method for odometer and price features.
Checking normality: For checking normality, q-q plot helps us. Figure 9 tells that there is a violation of normality. This means that the data points that are used are not distributed normally. In addition, Shapiro-Wilk test was performed for checking normality.
Result:(0.9586305022239685, 0.0)
Here, the first value is W-test statistic and the second value is the p-value. For N > 5000, the W test statistic is accurate but the p-value may not be. By considering p-value of Shapiro-Wilk test, it can be concluded that the data is not normally distributed.
In this situation, we have problem with initial data points. May be, filtering data can solve this issue. For this purpose, the values of odometer and price that are two standard deviation away from mean were dropped and independent t-test applied.
As it was stated earlier, t-test is not appropriate here because of violation of equality of variances assumption and normality assumption. On the other hand, we can still interpret the result while keeping in mind that it is not reliable. According to table 5, the correlation is 0.90. This indicates a strong relation between price and odometer. In addition, p-value is low and statistically significant. Effect size (Cohen’s d) is 4.17 which is a large value. A d of 4 indicates they differ by 4 standard deviations. This means that two groups’ means differ by 4 standard deviations or more, thus the difference is significant.
By considering these results of Welch’s test and table 5, it can be concluded that odometer and price have a significant relation. Therefore, first hypothesis’s null hypothesis is rejected. Rejecting null has some possible meanings:
Alternative hypothesis is true.
There can be type 2 error which implies that null hypothesis is rejected mistakenly
Yes, there is a statistical significance. But it does not imply practical significance.
Condition vs Price
The second hypothesis of this study focuses on effect of a car’s condition on its price. In order to understand this relation, Table 6 and Figure 6 can be useful. By looking at Figure 10, it can be said that ‘condition’ effects median price of cars seriously. On the other hand, there are a lot of outliers in the condition values which is an expected result for such a lar dataset. We do not see outliers at the bottom of the Figure 10. This is mostly because during data cleaning, cars that lower than $750 price were dropped.
Now, it is time to check the relation between condition and price. Before applying any linear relation test, diagnostic tests must be applied. Hence, it can be checked whether the relation satisfies the four assumptions: Linearity of residuals, Independence of residuals, Normal distribution of residuals, Equal variance of residuals. In order to test normality Jarque-Bera were conducted, for checking equal variance of residuals Omnibus test were applied. In addition, for checking multicollinearity Condition Number (condno) test were used, and to detect the presence of autocorrelation The Durban-Watson test were applied (Table 7).
By considering Table 7, Jarque-Bera p-value and Omni p-value are significant. This indicates that there is a violation of normality and homogeneity of variance. In addition, The Durbin Watson (DW) statistic is a test for autocorrelation in the residuals from a statistical regression analysis. The Durbin-Watson statistic will always have a value between 0 and 4. A value of 2.0 means that there is no autocorrelation detected in the sample. Values from 0 to less than 2 indicate positive autocorrelation and values from from 2 to 4 indicate negative autocorrelation. The Durbin Watson score of ‘condition’ and ‘price’ is 1,49 which indicates that it’s a weak but positive correlation.
Inference of the results for ‘condition’
The hypothesis was:
H0: There is no significant relation between price and condition of a car
By considering test result, we fail to reject null hypothesis. However, the hypothesis is based on a linear relation. Therefore, there are some possible interpretations for this situation:
· There can be a relation between ‘condition’ and ‘price’ but it is not a linear relation. It can be a non-linear relation.
· There can be a linear relation but our data may not be representative and failed us to see the relation.
· The null hypothesis is correct and there is no a significant relation between ‘condition’ and ‘price’.
Challenges of Inferential Statistics
In this data set, one of the biggest challenges is that the distribution of the predictor variables was violation normality. That’s why, classical statistical methods were not much helpful for analyzing this data. Besides, in the dataset there are only 3 numerical variables among 14 variables. This limits our opportunity to use Pearson-r correlation.
Therefore, we will move on the next section. In the next section, machine learning models will be applied and performance of the models will be tested by using mean absolute error (MAE), mean squared error (MSE) and root mean squared error (RMSE).
Machine Learning Models
This section used applied machine learning models as a framework for the data analysis. The data set is a supervised data which refers to fitting a model of dependent variables to the independent variables, with the goal of accurately predicting the dependent variable for future observations or understanding the relationship between the variables (Gareth, Daniela, Trevor, & Tibshirani, 2013). In relation to the data set, literature suggests below listed methods can be appropriate.
In this section, these machine learning models will be applied in order:
· Random Forest
· Ridge Regression
· Lasso
· K-Nearest Neighbor
· XGBoost
In addition, before ridge regression, simple linear model will be applied and results will be considered.
Pre-processing the data
Label Encoding. In the dataset, there are 13 predictors. 2 of them are numerical variables while rest of them are categorical. In order to apply machine learning models, we need numeric representation of the features. Therefore, all non-numeric features were transformed into numerical form.
Train the data. In this process, 20% of the data was split for the test data and 80% of the data was taken as train data.
Scaling the Data. While exploring the data in the previous sections, it was seen that the data is not normally distributed. Without scaling, the machine learning models will try to disregard coefficients of features that has low values because their impact will be so small compared to the big value features.
While scaling, it’s also important to scale with correct method because inappropriate scaling causes inappropriate target quantification and inappropriate measures of performance (Hurwitz, E., & Marwala, 2012). Min-max scaler is appropriate especially when the data is not normal distribution and want outliers to have reduced influence. Besides, both ridge and lasso get influenced by magnitude of the features to perform regularization. Therefore, Min-Max Scaler was used on the dataset.
Random Forest
Random forest is a set of multiple decision trees. Deep decision trees may suffer from overfitting, but random forest prevents overfitting by creating trees on random subsets. That’s why, it’s a good model to in the analysis.
In the analysis, 200 trees were created. In general, the more trees give the better results. As a result, 4001.8 RMSE and 2122.92 mean absolute error (MAE) obtained (Table 8).
If we look at Figure 11, we see that there are seven leaf nodes. This tree uses only three variables: year, drive and fuel. The leaf nodes do not have a question because these are where the final predictions are made. To classify a new point, simply move down the tree, using the features of the point to answer the questions until you arrive at a leaf node where the class is the prediction.
Variable Importance: In order to quantify the usefulness of all the variables in the entire random forest, we can look at the relative importance of the variables. Figure 12 is a simple bar plot of the feature importance to illustrate the disparities in the relative significance of the variables. For this study, reaching 90% of the cumulative importance is considered as a success.
Model with only important features: Number of features for 90% cumulative importance is 7 (Fig. 13). The features are: year, odometer, make, drive, fuel, manufacturer, cylinders. The ultimate purpose of the modelling is to get a smaller number of features that can give us a strong prediction. At this point, the model was run with only these seven important features. The new RMSE is 3960.11 (Table 9). This score is slightly better than the full model (4001.80 % vs 3960.11). In addition, this performance was obtained just by using 7 features instead of 13. Therefore, it can be considered as an improvement in both prediction power and computational cost.
Linear Regression
Before applying ridge and lasso, examining linear regression results can be useful (Table 10).
As we can see in the Table 10, the performance of the linear regression is not much good compared to random forest. The difference between actual values and predicted values is worthy of notice (Fig. 14). That’s why, we need different models that may give better predictions results.
Ridge Regression
Ordinary least square (OLS) gives unbiased regression coefficients (maximum likelihood estimates “as observed in the data-set”). Ridge regression and lasso allow to regularize (“shrink”) coefficients. In Figure 15, it can be seen how coefficients are shringking with increasing value of alpha.
In order to find best alpha value in ridge regression, cross validation was applied. The results are presented at table 11.
Compared to OLS, the performance of ridge is almost same. Considering figure 16, ridge regression suggest that these six variables are the most important ones: year, odometer, fuel, cylinders, title status and drive.
Lasso
Ridge shrinks the coefficients of the variables but does not make them zero. This may be good for certain cases, but it can create a challenge in model interpretation in settings in which the number of variables is quite large (Gareth, Daniela, Trevor, & Tibshirani, 2013). For this dataset, number of variables is not large, so there is no a serious need for lasso model. However, taking a look at lasso can give us another perspective. And, there is no harm to applying lasso to the dataset other than investing time and effort.
In order to find best lambda value from Fig. 17, cross-validation was applied. In this evaluation, obtained RMSE is 7578.82 (table 12).
Similar to the ridge results, lasso also gave six significant features: year, odometer, fuel, cylinders, title status, drive. While making final interpretation, this can be taken into consideration.
K-nearest Neighbors (KNN)
KNN-classifier can be used when your data set is small enough, so that KNN-Classifier completes running in a shorter time. The KNN algorithm can compete with the most accurate models because it makes highly accurate predictions. Therefore, we can use the KNN algorithm for applications that require a good prediction but do not require a human-readable model. The quality of the predictions depends on the distance measure. Therefore, the KNN algorithm is suitable for applications for which sufficient domain knowledge is available (IBM Knowledge Center, n.d.) Because we have 13 features for prediction, KNN is an appropriate method to apply for this study. For evaluation of the RMSE values, we can take a look at table 12.
At table 13 and fig. 19, it can be observed that RMSE value is at lowest when k is seven. On the other hand, there is no significant difference between RMSE values for k are two and seven. The rationale here is that if a set of K values appear to be more or less equally good, then we might as well choose the simplest model — that is, the model with the smallest number of predictors. For our case, we can justify to choose 2 predictors because it has lowest RMSE value (Table 13). However, considering previous models, six or seven predictors still have a strong reason to choose and more consistent with them.
XGBoost
XGBoost is a specific implementation of the Gradient Boosting method which uses more accurate approximations to find the best tree model. It employs a number of nifty tricks that make it exceptionally successful, particularly with structured data. XGBoost has additional advantages: training is very fast and can be parallelized / distributed across clusters. Therefore, XGBoost was another model that is used in this study. Performance of XGBoost is as shown in Table (table 14).
Fitting the model: As a first step, the objective parameter is set to be linear.
For the next step, 3-fold cross validation was performed. Max depth was chosen as 3. So that the model was kept simple. Finally, the number of times is set to perform boosting as 50.
Figure 20 provides a different perspective to the model. The final prediction for a given value (leaf) is the sum of predictions from each branch. On the other hand, decision tree may not be a robustness way for making prediction for our data set because it tries to make a regression but the dataset has many categorical variables. In addition to decision tree, feature importance figure (fig. 21) can give another perspective for evaluation. By considering figure 21, it can be said that odometer, manufacturer, year, and make are important features to include the model.
Conclusion
By performing different models, it was aimed to get different perspectives and eventually compared their performance. With this study, it purpose was to predict prices of used cars by using a dataset that has 13 predictors and 380962 observations. With the help of the data visualizations and exploratory data analysis, the dataset was uncovered and features were explored deeply. The relation between features were examined. At the last stage, predictive models were applied to predict price of cars in an order: random forest, linear regression, ridge regression, lasso, KNN, XGBoost.
By considering all four metrics from table 15, it can be concluded that random forest the best model for the prediction for used car prices. Random Forest as a regression model gave the best MAE, MSE and RMSE values (Table 14). According to random forest, here are the most important features: year, odometer, make, drive, fuel, manufacturer, cylinders. These features provide 3960.11 RMSE just by using seven listed features.
This study used different models in order to predict used car prices. However, there was a relatively small dataset for making a strong inference because number of observations was only 380962. Gathering more data can yield more robust predictions. Secondly, there could be more features that can be good predictors. For example, here are some variables that might improve the model: number of doors, gas/mile (per gallon), color, mechanical and cosmetic reconditioning time, used-to-new ratio, appraisal-to-trade ratio.
Another point that that has room to improvement is that data cleaning process can be dome more rigorously with the help of more technical information. For example, instead of using ‘ffill’ method, there might be indicators that helps to fill missing values more meaningfully.
As suggestion for further studies, while pre-processing data, instead of using label encoder, one hot encoder method can be used. Thus, all non-numeric features can be converted to nominal data instead of ordinal data (Raschka & Mirjalili, 2017). This may cause a serious change in performance of predictive models. Also, after training the data, instead of min-max scaler, standard scaler can be performned and results can be compared. Different scalers can be checked whether there is an improvement in prediction power of models or not.
IBM Knowledge Center. (n.d). Use of KNN. Retrieved from: https://www.ibm.com/support/knowledgecenter/SSHRBY/com.ibm.swg.im.dashdb.analytics.doc/doc/r_knn_usage.html
Gareth, J., Daniela, W., Trevor, H., & Tibshirani, R. (2013). An Introduction to Statistical
Learning (Vol. 8). https://doi.org/10.1016/j.peva.2007.06.006
Hurwitz, E., & Marwala, T. (2012). Common mistakes when applying computational intelligence and machine learning to stock market modelling. arXiv preprint arXiv:1208.4429.
Pal, N., Arora, P., Kohli, P., Sundararaman, D., & Palakurthy, S. S. (2018, April). How Much Is My Car Worth? A Methodology for Predicting Used Cars’ Prices Using Random Forest. In Future of Information and Communication Conference (pp. 413–422). Springer, Cham.
Raschka, S., & Mirjalili, V. (2017). Python machine learning. Packt Publishing Ltd. | [
{
"code": null,
"e": 353,
"s": 172,
"text": "You can reach all Python scripts of this study on my github page. If you are interested, you can also find the scripts used for data cleaning for this study in the same repository."
},
{
"code": null,
"e": 454,
"s": 353,
"text": "If you are interested in learning about a building a Machine Learning system from scratch including:"
},
{
"code": null,
"e": 490,
"s": 454,
"text": "Justifications during data cleaning"
},
{
"code": null,
"e": 522,
"s": 490,
"text": "Exploratory Data Analysis (EDA)"
},
{
"code": null,
"e": 630,
"s": 522,
"text": "Performing machine learning models: Random Forest, Linear Regression, Ridge Regression, Lasso, KNN, XGBoost"
},
{
"code": null,
"e": 674,
"s": 630,
"text": "Comparison of the performance of the models"
},
{
"code": null,
"e": 735,
"s": 674,
"text": "Reporting the findings of the study in a professional manner"
},
{
"code": null,
"e": 1588,
"s": 735,
"text": "The prices of new cars in the industry is fixed by the manufacturer with some additional costs incurred by the Government in the form of taxes. So, customers buying a new car can be assured of the money they invest to be worthy. But due to the increased price of new cars and the incapability of customers to buy new cars due to the lack of funds, used cars sales are on a global increase (Pal, Arora and Palakurthy, 2018). There is a need for a used car price prediction system to effectively determine the worthiness of the car using a variety of features. Even though there are websites that offers this service, their prediction method may not be the best. Besides, different models and systems may contribute on predicting power for a used car’s actual market value. It is important to know their actual market value while both buying and selling."
},
{
"code": null,
"e": 1667,
"s": 1588,
"text": "To be able to predict used cars market value can help both buyers and sellers."
},
{
"code": null,
"e": 1965,
"s": 1667,
"text": "Used car sellers (dealers): They are one of the biggest target group that can be interested in results of this study. If used car sellers better understand what makes a car desirable, what the important features are for a used car, then they may consider this knowledge and offer a better service."
},
{
"code": null,
"e": 2289,
"s": 1965,
"text": "Online pricing services: There are websites that offers an estimate value of a car. They may have a good prediction model. However, having a second model may help them to give a better prediction to their users. Therefore, the model developed in this study may help online web services that tells a used car’s market value."
},
{
"code": null,
"e": 2548,
"s": 2289,
"text": "Individuals: There are lots of individuals who are interested in the used car market at some points in their life because they wanted to sell their car or buy a used car. In this process, it’s a big corner to pay too much or sell less then it’s market value."
},
{
"code": null,
"e": 2921,
"s": 2548,
"text": "The data used in this project was downloaded from Kaggle. It was uploaded on Kaggle by Austin Reese who Kaggle.com user. Austin Reese scraped this data from craigslist with non-profit purpose. It contains most all relevant information that Craigslist provides on car sales including columns like price, condition, manufacturer, latitude/longitude, and 22 other categories."
},
{
"code": null,
"e": 2936,
"s": 2921,
"text": "Data Wrangling"
},
{
"code": null,
"e": 3071,
"s": 2936,
"text": "In this section, it will be discussed about how data cleaning and wrangling methods are applied on the craigslist used cars data file."
},
{
"code": null,
"e": 3364,
"s": 3071,
"text": "Before making data cleaning, some explorations and data visualizations were applied on data set. This gave some idea and guide about how to deal with missing values and extreme values. After data cleaning, data exploration was applied again in order to understand cleaned version of the data."
},
{
"code": null,
"e": 3682,
"s": 3364,
"text": "Data cleaning: First step for data cleaning was to remove unnecessary features. For this purpose, ‘url’,’image_url’, ‘lat’, ‘long’, ‘city_url’, ‘desc’, ‘city’, ‘VIN’ features were dropped totally. As a next step, it was investigated number of null points and percentage of null data points for that feature (Table 1)."
},
{
"code": null,
"e": 4345,
"s": 3682,
"text": "As a next step, extreme values were dropped because they inhibit prediction power of the model. Firstly, cars that had listed as more than $100.000 were dropped. There were only 580 out of 550313 data points that has over 100k price value. It addresses only small percentage of buyers. In addition, there were 61726 cars that has a price lower than $750. These values were also dropped from data-set because these prices are noise for the data. Secondly, cars that have odometer value over 300.000 miles and lower than 10 miles were dropped. And lastly, cars from earlier than 1985 were dropped. For our analysis, these data points can be considered as outliers."
},
{
"code": null,
"e": 4901,
"s": 4345,
"text": "As the second step, some missing values were filled with appropriate values. For the missing ‘condition’ values, it was paid attention to fill depending on category. Average odometer of all ‘condition’ sub-categories were calculated. Then, missing values were filled by considering this average odometer values for each condition sub-category. In addition, cars that have model value higher than 2019 were filled as ‘new’, and between 2017–2019 were filled as ‘like new’. At the end of this process, all missing values in ‘condition’ feature were cleaned."
},
{
"code": null,
"e": 5314,
"s": 4901,
"text": "Others were filled as by using ‘ffill’ method. This method propagates last valid observation forward to next valid. Thus, the last known value is available at every time point. Up to now, all missing values at odometer, condition, condition and price features were clear. After this step, all data became clean. After this operation, there were 380,962 observations in the data that will be studies and analyzed."
},
{
"code": null,
"e": 5514,
"s": 5314,
"text": "While exploring the data, we will look at the different combinations of features with the help of visuals. This will help us to understand our data better and give us some clue about pattern in data."
},
{
"code": null,
"e": 5544,
"s": 5514,
"text": "An examination of price trend"
},
{
"code": null,
"e": 5683,
"s": 5544,
"text": "Price is the feature that we are predicting in this study. Before applying any models, taking a look at price data may give us some ideas."
},
{
"code": null,
"e": 6314,
"s": 5683,
"text": "By looking at Figure 1, it can be observed that most of the used cars are less than $20,000. In addition, we see that there are still considerable number of cars that is over $20k price. We can guess that all type of cars can be cheap or expensive. But, still excellent, like new, and good condition cars are the most popular cars in used car market (Figure 2). Salvage cars are following these three categories in popularity. Therefore, it is hard to make a strong estimate of a price of a car just by considering the type or condition of a car. But we can tell it certain condition cars are popular and higher chance to be sold."
},
{
"code": null,
"e": 6344,
"s": 6314,
"text": "Popular features of used cars"
},
{
"code": null,
"e": 6793,
"s": 6344,
"text": "When buying a used car, people pay serious attention to the odometer value on the car. We can see that odometer changes the price of a car significantly (Figure 3). On the other hand, this does not mean that only low odometer cars are sold. Depending on the price, high odometer cars also have buyers (Figure 4). Furthermore, most popular used cars are the ones that has odometer around 100k. Until 150k odometer, there are many cars on the market."
},
{
"code": null,
"e": 7142,
"s": 6793,
"text": "Manufacturer of a car is another important variable on used car market. Ford and Chevrolet are one dominant manufacturer in North America (Figure 5). Toyota and Nissan follow the order as big manufacturers. It can be concluded that Japanese cars have a considerable share in used car market. However, American cars are still on demand and dominant."
},
{
"code": null,
"e": 8249,
"s": 7142,
"text": "Transmission: Transmission is another feature that has a dominant sub category in the used car market. According to Figure 6, automatic transmission has a strong effect on people’s preference on car. In Figure 6, it can be seen that after 2000, automatic transmission cars are in the increase. In 2009, it decreases. Global economic recession might have an impact on used car market and affect market. Another interesting trend is that after 2009, other transmission is on the increase. Its market share is still so low compared to automatic transmission, but it is still considerable. The increase in other transmission type can be caused by a couple reason. First possibility is that increase in continuously variable transmission (CVT). CVT is more environmentally friendly and fuel efficient. There might be a promotion for this kind of technology. Another possibility is that some seller on Craigslist website did not fill transmission section of the car information. The website might directly put them in the ‘other’ category. This also explains the increase in the ‘other’ category of transmission."
},
{
"code": null,
"e": 8857,
"s": 8249,
"text": "Drivetrain type: While evaluating a car, it’s important to understand what affects it’s condition. Figure 7 tells that 4wd drive cars more durable and reliable. It can be seen that 4wd cars are the most popular in terms of numbers. In the long run, they can keep their ability to run better compared to rwd and fwd drive train. 4wd has highest numbers of ‘excellent’, ‘like new’, and ‘good’ condition’ of cars. On the other hand, we need to keep in mind that compared to total number, it’s hard to say that 4wd cars higher rate of “excellent” and “like new” cars (Fig.7). In addition, by looking at table 4,"
},
{
"code": null,
"e": 9125,
"s": 8857,
"text": "we can see that average odometers for all drivetrain types are so close to each other for all quantiles. This also tells that in the used car market, drive type may not affect with odometer of cars. But their popularity is different among drivers (Table 3 and Fig 8)."
},
{
"code": null,
"e": 9143,
"s": 9125,
"text": "Test & Hypothesis"
},
{
"code": null,
"e": 9547,
"s": 9143,
"text": "In order to understand what affects change in price of a used car, the relation between features available in the data sat will be examined by using inferential statistic methods. The primary assumption based on figures and tables is price must be affected by odometer and condition. There must be other features that affects price significantly. It will be investigated in the later phase of the study."
},
{
"code": null,
"e": 9569,
"s": 9547,
"text": "The first hypothesis:"
},
{
"code": null,
"e": 9655,
"s": 9569,
"text": "Null Hypothesis: There is no significant relation between price and odometer of a car"
},
{
"code": null,
"e": 9731,
"s": 9655,
"text": "Alt-Hypothesis: There is a significant relation between price and odometer."
},
{
"code": null,
"e": 9754,
"s": 9731,
"text": "The second hypothesis:"
},
{
"code": null,
"e": 9841,
"s": 9754,
"text": "Null Hypothesis: There is no significant relation between price and condition of a car"
},
{
"code": null,
"e": 9918,
"s": 9841,
"text": "Alt-Hypothesis: There is a significant relation between price and condition."
},
{
"code": null,
"e": 9936,
"s": 9918,
"text": "Odometer vs Price"
},
{
"code": null,
"e": 10286,
"s": 9936,
"text": "Firstly, examine first hypothesis. Independent t-test is an appropriate method while examining the relation between two numerical variables. On the other hand, this test has some presumptions. Homogeneity of variances is one of the assumptions. In order to check whether homogeneity of variance assumption is violated or not, Levene test is applied."
},
{
"code": null,
"e": 10351,
"s": 10286,
"text": "Checking homogeneity of variance: The result of the Levene test:"
},
{
"code": null,
"e": 10408,
"s": 10351,
"text": "Levene Result (statistic=335641.8310266318, p-value=0.0)"
},
{
"code": null,
"e": 10837,
"s": 10408,
"text": "This means that homogeneity of variance is violated. In this case, we need to use Welch’s test. Welch’s t-test is a non-parametric univariate test that tests for a significant difference between the mean of two unrelated groups. It is an alternative to the independent t-test when there is a violation in the assumption of equality of variances. Therefore, it’s appropriate for this case. Here is the result of the Welch’s test:"
},
{
"code": null,
"e": 10923,
"s": 10837,
"text": "Welch's t-test= 740.70p-value = 0.00Welch-Satterthwaite Degrees of Freedom= 276855.87"
},
{
"code": null,
"e": 11202,
"s": 10923,
"text": "Here, p-value is significant. This tells that there is a significant relation between odometer and price of a car. For a reference, there is no harm to conduct an independent t-test. It can provide some ideas even though it’s not a robust method for odometer and price features."
},
{
"code": null,
"e": 11465,
"s": 11202,
"text": "Checking normality: For checking normality, q-q plot helps us. Figure 9 tells that there is a violation of normality. This means that the data points that are used are not distributed normally. In addition, Shapiro-Wilk test was performed for checking normality."
},
{
"code": null,
"e": 11498,
"s": 11465,
"text": "Result:(0.9586305022239685, 0.0)"
},
{
"code": null,
"e": 11760,
"s": 11498,
"text": "Here, the first value is W-test statistic and the second value is the p-value. For N > 5000, the W test statistic is accurate but the p-value may not be. By considering p-value of Shapiro-Wilk test, it can be concluded that the data is not normally distributed."
},
{
"code": null,
"e": 12009,
"s": 11760,
"text": "In this situation, we have problem with initial data points. May be, filtering data can solve this issue. For this purpose, the values of odometer and price that are two standard deviation away from mean were dropped and independent t-test applied."
},
{
"code": null,
"e": 12640,
"s": 12009,
"text": "As it was stated earlier, t-test is not appropriate here because of violation of equality of variances assumption and normality assumption. On the other hand, we can still interpret the result while keeping in mind that it is not reliable. According to table 5, the correlation is 0.90. This indicates a strong relation between price and odometer. In addition, p-value is low and statistically significant. Effect size (Cohen’s d) is 4.17 which is a large value. A d of 4 indicates they differ by 4 standard deviations. This means that two groups’ means differ by 4 standard deviations or more, thus the difference is significant."
},
{
"code": null,
"e": 12873,
"s": 12640,
"text": "By considering these results of Welch’s test and table 5, it can be concluded that odometer and price have a significant relation. Therefore, first hypothesis’s null hypothesis is rejected. Rejecting null has some possible meanings:"
},
{
"code": null,
"e": 12905,
"s": 12873,
"text": "Alternative hypothesis is true."
},
{
"code": null,
"e": 12989,
"s": 12905,
"text": "There can be type 2 error which implies that null hypothesis is rejected mistakenly"
},
{
"code": null,
"e": 13077,
"s": 12989,
"text": "Yes, there is a statistical significance. But it does not imply practical significance."
},
{
"code": null,
"e": 13096,
"s": 13077,
"text": "Condition vs Price"
},
{
"code": null,
"e": 13625,
"s": 13096,
"text": "The second hypothesis of this study focuses on effect of a car’s condition on its price. In order to understand this relation, Table 6 and Figure 6 can be useful. By looking at Figure 10, it can be said that ‘condition’ effects median price of cars seriously. On the other hand, there are a lot of outliers in the condition values which is an expected result for such a lar dataset. We do not see outliers at the bottom of the Figure 10. This is mostly because during data cleaning, cars that lower than $750 price were dropped."
},
{
"code": null,
"e": 14262,
"s": 13625,
"text": "Now, it is time to check the relation between condition and price. Before applying any linear relation test, diagnostic tests must be applied. Hence, it can be checked whether the relation satisfies the four assumptions: Linearity of residuals, Independence of residuals, Normal distribution of residuals, Equal variance of residuals. In order to test normality Jarque-Bera were conducted, for checking equal variance of residuals Omnibus test were applied. In addition, for checking multicollinearity Condition Number (condno) test were used, and to detect the presence of autocorrelation The Durban-Watson test were applied (Table 7)."
},
{
"code": null,
"e": 14948,
"s": 14262,
"text": "By considering Table 7, Jarque-Bera p-value and Omni p-value are significant. This indicates that there is a violation of normality and homogeneity of variance. In addition, The Durbin Watson (DW) statistic is a test for autocorrelation in the residuals from a statistical regression analysis. The Durbin-Watson statistic will always have a value between 0 and 4. A value of 2.0 means that there is no autocorrelation detected in the sample. Values from 0 to less than 2 indicate positive autocorrelation and values from from 2 to 4 indicate negative autocorrelation. The Durbin Watson score of ‘condition’ and ‘price’ is 1,49 which indicates that it’s a weak but positive correlation."
},
{
"code": null,
"e": 14989,
"s": 14948,
"text": "Inference of the results for ‘condition’"
},
{
"code": null,
"e": 15009,
"s": 14989,
"text": "The hypothesis was:"
},
{
"code": null,
"e": 15083,
"s": 15009,
"text": "H0: There is no significant relation between price and condition of a car"
},
{
"code": null,
"e": 15272,
"s": 15083,
"text": "By considering test result, we fail to reject null hypothesis. However, the hypothesis is based on a linear relation. Therefore, there are some possible interpretations for this situation:"
},
{
"code": null,
"e": 15396,
"s": 15272,
"text": "· There can be a relation between ‘condition’ and ‘price’ but it is not a linear relation. It can be a non-linear relation."
},
{
"code": null,
"e": 15503,
"s": 15396,
"text": "· There can be a linear relation but our data may not be representative and failed us to see the relation."
},
{
"code": null,
"e": 15608,
"s": 15503,
"text": "· The null hypothesis is correct and there is no a significant relation between ‘condition’ and ‘price’."
},
{
"code": null,
"e": 15645,
"s": 15608,
"text": "Challenges of Inferential Statistics"
},
{
"code": null,
"e": 15998,
"s": 15645,
"text": "In this data set, one of the biggest challenges is that the distribution of the predictor variables was violation normality. That’s why, classical statistical methods were not much helpful for analyzing this data. Besides, in the dataset there are only 3 numerical variables among 14 variables. This limits our opportunity to use Pearson-r correlation."
},
{
"code": null,
"e": 16246,
"s": 15998,
"text": "Therefore, we will move on the next section. In the next section, machine learning models will be applied and performance of the models will be tested by using mean absolute error (MAE), mean squared error (MSE) and root mean squared error (RMSE)."
},
{
"code": null,
"e": 16270,
"s": 16246,
"text": "Machine Learning Models"
},
{
"code": null,
"e": 16756,
"s": 16270,
"text": "This section used applied machine learning models as a framework for the data analysis. The data set is a supervised data which refers to fitting a model of dependent variables to the independent variables, with the goal of accurately predicting the dependent variable for future observations or understanding the relationship between the variables (Gareth, Daniela, Trevor, & Tibshirani, 2013). In relation to the data set, literature suggests below listed methods can be appropriate."
},
{
"code": null,
"e": 16829,
"s": 16756,
"text": "In this section, these machine learning models will be applied in order:"
},
{
"code": null,
"e": 16845,
"s": 16829,
"text": "· Random Forest"
},
{
"code": null,
"e": 16864,
"s": 16845,
"text": "· Ridge Regression"
},
{
"code": null,
"e": 16872,
"s": 16864,
"text": "· Lasso"
},
{
"code": null,
"e": 16893,
"s": 16872,
"text": "· K-Nearest Neighbor"
},
{
"code": null,
"e": 16903,
"s": 16893,
"text": "· XGBoost"
},
{
"code": null,
"e": 17009,
"s": 16903,
"text": "In addition, before ridge regression, simple linear model will be applied and results will be considered."
},
{
"code": null,
"e": 17033,
"s": 17009,
"text": "Pre-processing the data"
},
{
"code": null,
"e": 17325,
"s": 17033,
"text": "Label Encoding. In the dataset, there are 13 predictors. 2 of them are numerical variables while rest of them are categorical. In order to apply machine learning models, we need numeric representation of the features. Therefore, all non-numeric features were transformed into numerical form."
},
{
"code": null,
"e": 17447,
"s": 17325,
"text": "Train the data. In this process, 20% of the data was split for the test data and 80% of the data was taken as train data."
},
{
"code": null,
"e": 17757,
"s": 17447,
"text": "Scaling the Data. While exploring the data in the previous sections, it was seen that the data is not normally distributed. Without scaling, the machine learning models will try to disregard coefficients of features that has low values because their impact will be so small compared to the big value features."
},
{
"code": null,
"e": 18247,
"s": 17757,
"text": "While scaling, it’s also important to scale with correct method because inappropriate scaling causes inappropriate target quantification and inappropriate measures of performance (Hurwitz, E., & Marwala, 2012). Min-max scaler is appropriate especially when the data is not normal distribution and want outliers to have reduced influence. Besides, both ridge and lasso get influenced by magnitude of the features to perform regularization. Therefore, Min-Max Scaler was used on the dataset."
},
{
"code": null,
"e": 18261,
"s": 18247,
"text": "Random Forest"
},
{
"code": null,
"e": 18487,
"s": 18261,
"text": "Random forest is a set of multiple decision trees. Deep decision trees may suffer from overfitting, but random forest prevents overfitting by creating trees on random subsets. That’s why, it’s a good model to in the analysis."
},
{
"code": null,
"e": 18663,
"s": 18487,
"text": "In the analysis, 200 trees were created. In general, the more trees give the better results. As a result, 4001.8 RMSE and 2122.92 mean absolute error (MAE) obtained (Table 8)."
},
{
"code": null,
"e": 19056,
"s": 18663,
"text": "If we look at Figure 11, we see that there are seven leaf nodes. This tree uses only three variables: year, drive and fuel. The leaf nodes do not have a question because these are where the final predictions are made. To classify a new point, simply move down the tree, using the features of the point to answer the questions until you arrive at a leaf node where the class is the prediction."
},
{
"code": null,
"e": 19440,
"s": 19056,
"text": "Variable Importance: In order to quantify the usefulness of all the variables in the entire random forest, we can look at the relative importance of the variables. Figure 12 is a simple bar plot of the feature importance to illustrate the disparities in the relative significance of the variables. For this study, reaching 90% of the cumulative importance is considered as a success."
},
{
"code": null,
"e": 20101,
"s": 19440,
"text": "Model with only important features: Number of features for 90% cumulative importance is 7 (Fig. 13). The features are: year, odometer, make, drive, fuel, manufacturer, cylinders. The ultimate purpose of the modelling is to get a smaller number of features that can give us a strong prediction. At this point, the model was run with only these seven important features. The new RMSE is 3960.11 (Table 9). This score is slightly better than the full model (4001.80 % vs 3960.11). In addition, this performance was obtained just by using 7 features instead of 13. Therefore, it can be considered as an improvement in both prediction power and computational cost."
},
{
"code": null,
"e": 20119,
"s": 20101,
"text": "Linear Regression"
},
{
"code": null,
"e": 20214,
"s": 20119,
"text": "Before applying ridge and lasso, examining linear regression results can be useful (Table 10)."
},
{
"code": null,
"e": 20498,
"s": 20214,
"text": "As we can see in the Table 10, the performance of the linear regression is not much good compared to random forest. The difference between actual values and predicted values is worthy of notice (Fig. 14). That’s why, we need different models that may give better predictions results."
},
{
"code": null,
"e": 20515,
"s": 20498,
"text": "Ridge Regression"
},
{
"code": null,
"e": 20809,
"s": 20515,
"text": "Ordinary least square (OLS) gives unbiased regression coefficients (maximum likelihood estimates “as observed in the data-set”). Ridge regression and lasso allow to regularize (“shrink”) coefficients. In Figure 15, it can be seen how coefficients are shringking with increasing value of alpha."
},
{
"code": null,
"e": 20933,
"s": 20809,
"text": "In order to find best alpha value in ridge regression, cross validation was applied. The results are presented at table 11."
},
{
"code": null,
"e": 21150,
"s": 20933,
"text": "Compared to OLS, the performance of ridge is almost same. Considering figure 16, ridge regression suggest that these six variables are the most important ones: year, odometer, fuel, cylinders, title status and drive."
},
{
"code": null,
"e": 21156,
"s": 21150,
"text": "Lasso"
},
{
"code": null,
"e": 21687,
"s": 21156,
"text": "Ridge shrinks the coefficients of the variables but does not make them zero. This may be good for certain cases, but it can create a challenge in model interpretation in settings in which the number of variables is quite large (Gareth, Daniela, Trevor, & Tibshirani, 2013). For this dataset, number of variables is not large, so there is no a serious need for lasso model. However, taking a look at lasso can give us another perspective. And, there is no harm to applying lasso to the dataset other than investing time and effort."
},
{
"code": null,
"e": 21823,
"s": 21687,
"text": "In order to find best lambda value from Fig. 17, cross-validation was applied. In this evaluation, obtained RMSE is 7578.82 (table 12)."
},
{
"code": null,
"e": 22022,
"s": 21823,
"text": "Similar to the ridge results, lasso also gave six significant features: year, odometer, fuel, cylinders, title status, drive. While making final interpretation, this can be taken into consideration."
},
{
"code": null,
"e": 22048,
"s": 22022,
"text": "K-nearest Neighbors (KNN)"
},
{
"code": null,
"e": 22775,
"s": 22048,
"text": "KNN-classifier can be used when your data set is small enough, so that KNN-Classifier completes running in a shorter time. The KNN algorithm can compete with the most accurate models because it makes highly accurate predictions. Therefore, we can use the KNN algorithm for applications that require a good prediction but do not require a human-readable model. The quality of the predictions depends on the distance measure. Therefore, the KNN algorithm is suitable for applications for which sufficient domain knowledge is available (IBM Knowledge Center, n.d.) Because we have 13 features for prediction, KNN is an appropriate method to apply for this study. For evaluation of the RMSE values, we can take a look at table 12."
},
{
"code": null,
"e": 23388,
"s": 22775,
"text": "At table 13 and fig. 19, it can be observed that RMSE value is at lowest when k is seven. On the other hand, there is no significant difference between RMSE values for k are two and seven. The rationale here is that if a set of K values appear to be more or less equally good, then we might as well choose the simplest model — that is, the model with the smallest number of predictors. For our case, we can justify to choose 2 predictors because it has lowest RMSE value (Table 13). However, considering previous models, six or seven predictors still have a strong reason to choose and more consistent with them."
},
{
"code": null,
"e": 23396,
"s": 23388,
"text": "XGBoost"
},
{
"code": null,
"e": 23877,
"s": 23396,
"text": "XGBoost is a specific implementation of the Gradient Boosting method which uses more accurate approximations to find the best tree model. It employs a number of nifty tricks that make it exceptionally successful, particularly with structured data. XGBoost has additional advantages: training is very fast and can be parallelized / distributed across clusters. Therefore, XGBoost was another model that is used in this study. Performance of XGBoost is as shown in Table (table 14)."
},
{
"code": null,
"e": 23958,
"s": 23877,
"text": "Fitting the model: As a first step, the objective parameter is set to be linear."
},
{
"code": null,
"e": 24141,
"s": 23958,
"text": "For the next step, 3-fold cross validation was performed. Max depth was chosen as 3. So that the model was kept simple. Finally, the number of times is set to perform boosting as 50."
},
{
"code": null,
"e": 24715,
"s": 24141,
"text": "Figure 20 provides a different perspective to the model. The final prediction for a given value (leaf) is the sum of predictions from each branch. On the other hand, decision tree may not be a robustness way for making prediction for our data set because it tries to make a regression but the dataset has many categorical variables. In addition to decision tree, feature importance figure (fig. 21) can give another perspective for evaluation. By considering figure 21, it can be said that odometer, manufacturer, year, and make are important features to include the model."
},
{
"code": null,
"e": 24726,
"s": 24715,
"text": "Conclusion"
},
{
"code": null,
"e": 25313,
"s": 24726,
"text": "By performing different models, it was aimed to get different perspectives and eventually compared their performance. With this study, it purpose was to predict prices of used cars by using a dataset that has 13 predictors and 380962 observations. With the help of the data visualizations and exploratory data analysis, the dataset was uncovered and features were explored deeply. The relation between features were examined. At the last stage, predictive models were applied to predict price of cars in an order: random forest, linear regression, ridge regression, lasso, KNN, XGBoost."
},
{
"code": null,
"e": 25740,
"s": 25313,
"text": "By considering all four metrics from table 15, it can be concluded that random forest the best model for the prediction for used car prices. Random Forest as a regression model gave the best MAE, MSE and RMSE values (Table 14). According to random forest, here are the most important features: year, odometer, make, drive, fuel, manufacturer, cylinders. These features provide 3960.11 RMSE just by using seven listed features."
},
{
"code": null,
"e": 26261,
"s": 25740,
"text": "This study used different models in order to predict used car prices. However, there was a relatively small dataset for making a strong inference because number of observations was only 380962. Gathering more data can yield more robust predictions. Secondly, there could be more features that can be good predictors. For example, here are some variables that might improve the model: number of doors, gas/mile (per gallon), color, mechanical and cosmetic reconditioning time, used-to-new ratio, appraisal-to-trade ratio."
},
{
"code": null,
"e": 26537,
"s": 26261,
"text": "Another point that that has room to improvement is that data cleaning process can be dome more rigorously with the help of more technical information. For example, instead of using ‘ffill’ method, there might be indicators that helps to fill missing values more meaningfully."
},
{
"code": null,
"e": 27077,
"s": 26537,
"text": "As suggestion for further studies, while pre-processing data, instead of using label encoder, one hot encoder method can be used. Thus, all non-numeric features can be converted to nominal data instead of ordinal data (Raschka & Mirjalili, 2017). This may cause a serious change in performance of predictive models. Also, after training the data, instead of min-max scaler, standard scaler can be performned and results can be compared. Different scalers can be checked whether there is an improvement in prediction power of models or not."
},
{
"code": null,
"e": 27242,
"s": 27077,
"text": "IBM Knowledge Center. (n.d). Use of KNN. Retrieved from: https://www.ibm.com/support/knowledgecenter/SSHRBY/com.ibm.swg.im.dashdb.analytics.doc/doc/r_knn_usage.html"
},
{
"code": null,
"e": 27335,
"s": 27242,
"text": "Gareth, J., Daniela, W., Trevor, H., & Tibshirani, R. (2013). An Introduction to Statistical"
},
{
"code": null,
"e": 27397,
"s": 27335,
"text": "Learning (Vol. 8). https://doi.org/10.1016/j.peva.2007.06.006"
},
{
"code": null,
"e": 27569,
"s": 27397,
"text": "Hurwitz, E., & Marwala, T. (2012). Common mistakes when applying computational intelligence and machine learning to stock market modelling. arXiv preprint arXiv:1208.4429."
},
{
"code": null,
"e": 27832,
"s": 27569,
"text": "Pal, N., Arora, P., Kohli, P., Sundararaman, D., & Palakurthy, S. S. (2018, April). How Much Is My Car Worth? A Methodology for Predicting Used Cars’ Prices Using Random Forest. In Future of Information and Communication Conference (pp. 413–422). Springer, Cham."
}
] |
Consuming a REST API ( Github Users ) using Fetch - React Client - GeeksforGeeks | 09 Nov, 2021
In this article you will learn to develop a React application, which will fetch the data from a REST API using Fetch. We will use GitHub Users API to fetch the user’s public information with their username. You can find the API reference and source code links at the end of this article.
Before moving onto the development part, to initialize a simple react application you can follow the steps mentioned below:
Step 1: Create React application.
npx create-react-app foldername
Step 2: Move into the project folder.
cd foldername
Step 3: Create a components folder and now Project Structure will look like:
Project Structure
Custom components resides in the components folder, with everything put together in the MainComponent.js, we will place this component inside App.js, which itself goes under “root” DOM node and everything inside this node will be managed by React DOM.
We are going to develop three components:
Main Component: Responsible for fetch operation and state changes in the application.
Search Bar: A search bar to get the user input for GitHub username.
UserInfoCard: A reusable component to display the GitHub user information.
Step 4: In the MainComponent.js component, we have two state variables, username ( input from the user ) and userData ( response from the REST API ). We need to fetch the user data, every time there is an update to the username. To achieve this, we are going to use useEffect hook from React.
Javascript
const [username, setUsername] = useState("");const [userData, setUserData] = useState({}); useEffect(() => { getUserData(); }, [username]);
Step 5: Now to get the response from GitHub users API, we are going to make a GET request using Fetch, which will be the role of getUserData() function.
Javascript
var gitHubUrl = `https://api.github.com/users/${username}`; const getUserData = async () => { const response = await fetch(gitHubUrl); const jsonData = await response.json(); if (jsonData && jsonData.message !== "Not Found") { setUserData(jsonData); console.log(jsonData) } else if (username !== "") { console.log('Username does not exist'); } else { setUserData({}) } };
getUserData() is an asynchronous function, in which fetch(gitHubUrl) makes the request and returns a promise. When the request is complete, the promise is resolved with response object. This object is basically a generic placeholder for various response formats. response.json() is used to extract the JSON object from the response, it returns a promise, hence the await.
So finally, our MainComponent.js file is looks like:
Javascript
import React, { useState, useEffect } from "react";import SearchBar from "./SearchBar";import UserInfoCard from "./UserInfoCard"; function Main() { const [username, setUsername] = useState(""); const [userData, setUserData] = useState(Object); useEffect(() => { getUserData(); }, [username]); var gitHubUrl = `https://api.github.com/users/${username}`; const getUserData = async () => { const response = await fetch(gitHubUrl); const jsonData = await response.json(); if (jsonData && jsonData.message !== "Not Found") { setUserData(jsonData); console.log(jsonData) } else if (username !== "") { console.log('Username does not exist'); } else { setUserData({}) } }; return ( <div> <SearchBar username={username} setUsername={setUsername} /> <UserInfoCard userData={userData} /> </div> );} export default Main;
Step 6: Now, moving on to the SearchBar component, which serves the purpose of receiving the user input for username. It is a simple component, with an input field of text type. On any change, it fires of the setUsername with the updated value.
Javascript
import React from "react"; function SearchBar({username, setUsername}){ const onChange = (e) =>{ setUsername(e.target.value) } return( <div className="searchbar"> <input placeholder="Search" type="text" onChange={(event) => {onChange(event)}} onKeyUp={(event) => {onChange(event)}} onPaste={(event) => {onChange(event)}} /> </div> );} export default SearchBar;
Step 7: Our last component, is a reusable UI component, which is basically a Card Component that receives userData as props, and just displays it in any chosen format. You can tweak the App.css file to understand the various design aspects.
Javascript
import React from "react"; function UserInfoCard({ userData }) { return ( <div className="datacontainer"> {userData.avatar_url ? (<div className="dataitem"> <img src={userData.avatar_url} alt="avatar" /></div>) : (<div></div>)} {userData.login ? (<div className="dataitem">Login: {userData.login}</div>) : (<div></div>)} {userData.name ? (<div className="dataitem"> Name : {userData.name}</div>) : (<div></div>)} {userData.blog ? (<div className="dataitem"> Blog: {userData.blog}</div>) : (<div></div>)} </div> );} export default UserInfoCard;
That is all, with these three components put together, completes our React application, which you can download from the source code link provided below, and run it on your system. Source code does include an extra component, to store the retrieved data in Local Storage, which was not covered in this article. So if you’re interested, go ahead and check that out as well.
Step to run the application: To start the application on your system, run the following command:
npm start
Output:
GitHub Users API: https://docs.github.com/en/rest/reference/users
Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Source Code: https://github.com/notnotparas/github-users-api
React-Questions
Web-API
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to navigate on path by button click in react router ?
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
How to check the version of ReactJS ?
How to create a table in ReactJS ?
Express.js express.Router() Function
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 24397,
"s": 24369,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 24686,
"s": 24397,
"text": "In this article you will learn to develop a React application, which will fetch the data from a REST API using Fetch. We will use GitHub Users API to fetch the user’s public information with their username. You can find the API reference and source code links at the end of this article. "
},
{
"code": null,
"e": 24811,
"s": 24686,
"text": "Before moving onto the development part, to initialize a simple react application you can follow the steps mentioned below: "
},
{
"code": null,
"e": 24845,
"s": 24811,
"text": "Step 1: Create React application."
},
{
"code": null,
"e": 24877,
"s": 24845,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 24915,
"s": 24877,
"text": "Step 2: Move into the project folder."
},
{
"code": null,
"e": 24929,
"s": 24915,
"text": "cd foldername"
},
{
"code": null,
"e": 25007,
"s": 24929,
"text": "Step 3: Create a components folder and now Project Structure will look like: "
},
{
"code": null,
"e": 25025,
"s": 25007,
"text": "Project Structure"
},
{
"code": null,
"e": 25277,
"s": 25025,
"text": "Custom components resides in the components folder, with everything put together in the MainComponent.js, we will place this component inside App.js, which itself goes under “root” DOM node and everything inside this node will be managed by React DOM."
},
{
"code": null,
"e": 25319,
"s": 25277,
"text": "We are going to develop three components:"
},
{
"code": null,
"e": 25405,
"s": 25319,
"text": "Main Component: Responsible for fetch operation and state changes in the application."
},
{
"code": null,
"e": 25473,
"s": 25405,
"text": "Search Bar: A search bar to get the user input for GitHub username."
},
{
"code": null,
"e": 25548,
"s": 25473,
"text": "UserInfoCard: A reusable component to display the GitHub user information."
},
{
"code": null,
"e": 25843,
"s": 25548,
"text": "Step 4: In the MainComponent.js component, we have two state variables, username ( input from the user ) and userData ( response from the REST API ). We need to fetch the user data, every time there is an update to the username. To achieve this, we are going to use useEffect hook from React. "
},
{
"code": null,
"e": 25854,
"s": 25843,
"text": "Javascript"
},
{
"code": "const [username, setUsername] = useState(\"\");const [userData, setUserData] = useState({}); useEffect(() => { getUserData(); }, [username]);",
"e": 25999,
"s": 25854,
"text": null
},
{
"code": null,
"e": 26153,
"s": 25999,
"text": "Step 5: Now to get the response from GitHub users API, we are going to make a GET request using Fetch, which will be the role of getUserData() function. "
},
{
"code": null,
"e": 26166,
"s": 26155,
"text": "Javascript"
},
{
"code": "var gitHubUrl = `https://api.github.com/users/${username}`; const getUserData = async () => { const response = await fetch(gitHubUrl); const jsonData = await response.json(); if (jsonData && jsonData.message !== \"Not Found\") { setUserData(jsonData); console.log(jsonData) } else if (username !== \"\") { console.log('Username does not exist'); } else { setUserData({}) } };",
"e": 26642,
"s": 26166,
"text": null
},
{
"code": null,
"e": 27016,
"s": 26642,
"text": "getUserData() is an asynchronous function, in which fetch(gitHubUrl) makes the request and returns a promise. When the request is complete, the promise is resolved with response object. This object is basically a generic placeholder for various response formats. response.json() is used to extract the JSON object from the response, it returns a promise, hence the await. "
},
{
"code": null,
"e": 27069,
"s": 27016,
"text": "So finally, our MainComponent.js file is looks like:"
},
{
"code": null,
"e": 27080,
"s": 27069,
"text": "Javascript"
},
{
"code": "import React, { useState, useEffect } from \"react\";import SearchBar from \"./SearchBar\";import UserInfoCard from \"./UserInfoCard\"; function Main() { const [username, setUsername] = useState(\"\"); const [userData, setUserData] = useState(Object); useEffect(() => { getUserData(); }, [username]); var gitHubUrl = `https://api.github.com/users/${username}`; const getUserData = async () => { const response = await fetch(gitHubUrl); const jsonData = await response.json(); if (jsonData && jsonData.message !== \"Not Found\") { setUserData(jsonData); console.log(jsonData) } else if (username !== \"\") { console.log('Username does not exist'); } else { setUserData({}) } }; return ( <div> <SearchBar username={username} setUsername={setUsername} /> <UserInfoCard userData={userData} /> </div> );} export default Main;",
"e": 28093,
"s": 27080,
"text": null
},
{
"code": null,
"e": 28338,
"s": 28093,
"text": "Step 6: Now, moving on to the SearchBar component, which serves the purpose of receiving the user input for username. It is a simple component, with an input field of text type. On any change, it fires of the setUsername with the updated value."
},
{
"code": null,
"e": 28349,
"s": 28338,
"text": "Javascript"
},
{
"code": "import React from \"react\"; function SearchBar({username, setUsername}){ const onChange = (e) =>{ setUsername(e.target.value) } return( <div className=\"searchbar\"> <input placeholder=\"Search\" type=\"text\" onChange={(event) => {onChange(event)}} onKeyUp={(event) => {onChange(event)}} onPaste={(event) => {onChange(event)}} /> </div> );} export default SearchBar;",
"e": 28818,
"s": 28349,
"text": null
},
{
"code": null,
"e": 29060,
"s": 28818,
"text": "Step 7: Our last component, is a reusable UI component, which is basically a Card Component that receives userData as props, and just displays it in any chosen format. You can tweak the App.css file to understand the various design aspects. "
},
{
"code": null,
"e": 29071,
"s": 29060,
"text": "Javascript"
},
{
"code": "import React from \"react\"; function UserInfoCard({ userData }) { return ( <div className=\"datacontainer\"> {userData.avatar_url ? (<div className=\"dataitem\"> <img src={userData.avatar_url} alt=\"avatar\" /></div>) : (<div></div>)} {userData.login ? (<div className=\"dataitem\">Login: {userData.login}</div>) : (<div></div>)} {userData.name ? (<div className=\"dataitem\"> Name : {userData.name}</div>) : (<div></div>)} {userData.blog ? (<div className=\"dataitem\"> Blog: {userData.blog}</div>) : (<div></div>)} </div> );} export default UserInfoCard;",
"e": 29744,
"s": 29071,
"text": null
},
{
"code": null,
"e": 30118,
"s": 29744,
"text": "That is all, with these three components put together, completes our React application, which you can download from the source code link provided below, and run it on your system. Source code does include an extra component, to store the retrieved data in Local Storage, which was not covered in this article. So if you’re interested, go ahead and check that out as well. "
},
{
"code": null,
"e": 30215,
"s": 30118,
"text": "Step to run the application: To start the application on your system, run the following command:"
},
{
"code": null,
"e": 30225,
"s": 30215,
"text": "npm start"
},
{
"code": null,
"e": 30233,
"s": 30225,
"text": "Output:"
},
{
"code": null,
"e": 30299,
"s": 30233,
"text": "GitHub Users API: https://docs.github.com/en/rest/reference/users"
},
{
"code": null,
"e": 30369,
"s": 30299,
"text": "Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API"
},
{
"code": null,
"e": 30430,
"s": 30369,
"text": "Source Code: https://github.com/notnotparas/github-users-api"
},
{
"code": null,
"e": 30446,
"s": 30430,
"text": "React-Questions"
},
{
"code": null,
"e": 30454,
"s": 30446,
"text": "Web-API"
},
{
"code": null,
"e": 30462,
"s": 30454,
"text": "ReactJS"
},
{
"code": null,
"e": 30479,
"s": 30462,
"text": "Web Technologies"
},
{
"code": null,
"e": 30577,
"s": 30479,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30586,
"s": 30577,
"text": "Comments"
},
{
"code": null,
"e": 30599,
"s": 30586,
"text": "Old Comments"
},
{
"code": null,
"e": 30657,
"s": 30599,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 30684,
"s": 30657,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 30726,
"s": 30684,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 30764,
"s": 30726,
"text": "How to check the version of ReactJS ?"
},
{
"code": null,
"e": 30799,
"s": 30764,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 30836,
"s": 30799,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 30869,
"s": 30836,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30931,
"s": 30869,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30992,
"s": 30931,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
C# | CharEnumerator.MoveNext() Method - GeeksforGeeks | 30 Apr, 2019
CharEnumerator.MoveNext() Method is used to increments the internal index of the current CharEnumerator object to the next character of the enumerated string.
Syntax:
public bool MoveNext();
Return Value: This method returns the boolean value true value if the index is successfully incremented and within the enumerated string otherwise, false.
Below are the programs to illustrate the use of CharEnumerator.MoveNext() Method:
Example 1:
// C# program to illustrate the// use of CharEnumerator.MoveNext()// Methodusing System; class GFG { // Driver code public static void Main() { // Initialize a string object string str = "A Computer Science Portal for Geeks!"; // Instantiate a CharEnumerator object CharEnumerator chEnum = str.GetEnumerator(); // Printing the string while (chEnum.MoveNext()) { Console.Write(chEnum.Current); } }}
A Computer Science Portal for Geeks!
Example 2:
// C# program to illustrate the// use of CharEnumerator.MoveNext()// Methodusing System; class GFG { // Driver code public static void Main() { // Initialize a string object string str = "Best Data Structure and Algorithms Tutorials!"; // Instantiate a CharEnumerator object CharEnumerator chEnum = str.GetEnumerator(); // Printing the string while (chEnum.MoveNext()) { if (chEnum.Current == ' ') { Console.WriteLine(); continue; } Console.Write(chEnum.Current); } }}
Best
Data
Structure
and
Algorithms
Tutorials!
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.charenumerator.movenext?view=netframework-4.7.2
CSharp-CharEnumerator-Class
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
C# | Inheritance
Partial Classes in C#
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": "\n30 Apr, 2019"
},
{
"code": null,
"e": 24070,
"s": 23911,
"text": "CharEnumerator.MoveNext() Method is used to increments the internal index of the current CharEnumerator object to the next character of the enumerated string."
},
{
"code": null,
"e": 24078,
"s": 24070,
"text": "Syntax:"
},
{
"code": null,
"e": 24102,
"s": 24078,
"text": "public bool MoveNext();"
},
{
"code": null,
"e": 24257,
"s": 24102,
"text": "Return Value: This method returns the boolean value true value if the index is successfully incremented and within the enumerated string otherwise, false."
},
{
"code": null,
"e": 24339,
"s": 24257,
"text": "Below are the programs to illustrate the use of CharEnumerator.MoveNext() Method:"
},
{
"code": null,
"e": 24350,
"s": 24339,
"text": "Example 1:"
},
{
"code": "// C# program to illustrate the// use of CharEnumerator.MoveNext()// Methodusing System; class GFG { // Driver code public static void Main() { // Initialize a string object string str = \"A Computer Science Portal for Geeks!\"; // Instantiate a CharEnumerator object CharEnumerator chEnum = str.GetEnumerator(); // Printing the string while (chEnum.MoveNext()) { Console.Write(chEnum.Current); } }}",
"e": 24835,
"s": 24350,
"text": null
},
{
"code": null,
"e": 24873,
"s": 24835,
"text": "A Computer Science Portal for Geeks!\n"
},
{
"code": null,
"e": 24884,
"s": 24873,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate the// use of CharEnumerator.MoveNext()// Methodusing System; class GFG { // Driver code public static void Main() { // Initialize a string object string str = \"Best Data Structure and Algorithms Tutorials!\"; // Instantiate a CharEnumerator object CharEnumerator chEnum = str.GetEnumerator(); // Printing the string while (chEnum.MoveNext()) { if (chEnum.Current == ' ') { Console.WriteLine(); continue; } Console.Write(chEnum.Current); } }}",
"e": 25504,
"s": 24884,
"text": null
},
{
"code": null,
"e": 25551,
"s": 25504,
"text": "Best\nData\nStructure\nand\nAlgorithms\nTutorials!\n"
},
{
"code": null,
"e": 25562,
"s": 25551,
"text": "Reference:"
},
{
"code": null,
"e": 25661,
"s": 25562,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.charenumerator.movenext?view=netframework-4.7.2"
},
{
"code": null,
"e": 25689,
"s": 25661,
"text": "CSharp-CharEnumerator-Class"
},
{
"code": null,
"e": 25703,
"s": 25689,
"text": "CSharp-method"
},
{
"code": null,
"e": 25706,
"s": 25703,
"text": "C#"
},
{
"code": null,
"e": 25804,
"s": 25706,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25813,
"s": 25804,
"text": "Comments"
},
{
"code": null,
"e": 25826,
"s": 25813,
"text": "Old Comments"
},
{
"code": null,
"e": 25866,
"s": 25826,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 25889,
"s": 25866,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 25917,
"s": 25889,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 25934,
"s": 25917,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 25956,
"s": 25934,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 25996,
"s": 25956,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 26029,
"s": 25996,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 26072,
"s": 26029,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 26088,
"s": 26072,
"text": "C# | List Class"
}
] |
ASP.NET MVC - Quick Guide | ASP.NET MVC is basically a web development framework from Microsoft, which combines the features of MVC (Model-View-Controller) architecture, the most up-to-date ideas and techniques from Agile development, and the best parts of the existing ASP.NET platform.
ASP.NET MVC is not something, which is built from ground zero. It is a complete alternative to traditional ASP.NET Web Forms. It is built on the top of ASP.NET, so developers enjoy almost all the ASP.NET features while building the MVC application.
ASP.NET 1.0 was released on January 5, 2002, as part of .Net Framework version 1.0. At that time, it was easy to think of ASP.NET and Web Forms as one and the same thing. ASP.NET has however always supported two layers of abstraction −
System.Web.UI − The Web Forms layer, comprising server controls, ViewState, and so on.
System.Web.UI − The Web Forms layer, comprising server controls, ViewState, and so on.
System.Web − It supplies the basic web stack, including modules, handlers, the HTTP stack, etc.
System.Web − It supplies the basic web stack, including modules, handlers, the HTTP stack, etc.
By the time ASP.NET MVC was announced in 2007, the MVC pattern was becoming one of the most popular ways of building web frameworks.
In April 2009, the ASP.NET MVC source code was released under the Microsoft Public License (MS-PL). "ASP.NET MVC framework is a lightweight, highly testable presentation framework that is integrated with the existing ASP.NET features.
Some of these integrated features are master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly.
In March 2012, Microsoft had released part of its web stack (including ASP.NET MVC, Razor and Web API) under an open source license (Apache License 2.0). ASP.NET Web Forms was not included in this initiative.
Microsoft decided to create their own MVC framework for building web applications. The MVC framework simply builds on top of ASP.NET. When you are building a web application with ASP.NET MVC, there will be no illusions of state, there will not be such a thing as a page load and no page life cycle at all, etc.
Another design goal for ASP.NET MVC was to be extensible throughout all aspects of the framework. So when we talk about views, views have to be rendered by a particular type of view engine. The default view engine is still something that can take an ASPX file. But if you don't like using ASPX files, you can use something else and plug in your own view
engine.
There is a component inside the MVC framework that will instantiate your controllers. You might not like the way that the MVC framework instantiates your controller, you might want to handle that job yourself. So, there are lots of places in MVC where you can inject your own custom logic to handle tasks.
The whole idea behind using the Model View Controller design pattern is that you maintain a separation of concerns. Your controller is no longer encumbered with a lot of ties to the ASP.NET runtime or ties to the ASPX page, which is very hard to test. You now just have a class with regular methods on it that you can invoke in unit tests to find out if that controller is going to behave correctly.
Following are the benefits of using ASP.NET MVC −
Makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
Makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
Enables full control over the rendered HTML and provides a clean separation of concerns.
Enables full control over the rendered HTML and provides a clean separation of concerns.
Direct control over HTML also means better accessibility for implementing compliance with evolving Web standards.
Direct control over HTML also means better accessibility for implementing compliance with evolving Web standards.
Facilitates adding more interactivity and responsiveness to existing apps.
Facilitates adding more interactivity and responsiveness to existing apps.
Provides better support for test-driven development (TDD).
Provides better support for test-driven development (TDD).
Works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior.
Works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior.
The MVC (Model-View-Controller) design pattern has actually been around for a few decades, and it's been used across many different technologies. Everything from Smalltalk to C++ to Java, and now C Sharp and .NET use this design pattern to build a user interface.
Following are some salient features of the MVC pattern −
Originally it was named Thing-Model-View-Editor in 1979, and then it was later simplified to Model- View-Controller.
Originally it was named Thing-Model-View-Editor in 1979, and then it was later simplified to Model- View-Controller.
It is a powerful and elegant means of separating concerns within an application (for example, separating data access logic from display logic) and applies itself extremely well to web applications.
It is a powerful and elegant means of separating concerns within an application (for example, separating data access logic from display logic) and applies itself extremely well to web applications.
Its explicit separation of concerns does add a small amount of extra complexity to an application’s design, but the extraordinary benefits outweigh the extra effort.
Its explicit separation of concerns does add a small amount of extra complexity to an application’s design, but the extraordinary benefits outweigh the extra effort.
The MVC architectural pattern separates the user interface (UI) of an application into three main parts.
The Model − A set of classes that describes the data you are working with as well as the business logic.
The Model − A set of classes that describes the data you are working with as well as the business logic.
The View − Defines how the application’s UI will be displayed. It is a pure HTML, which decides how the UI is going to look like.
The View − Defines how the application’s UI will be displayed. It is a pure HTML, which decides how the UI is going to look like.
The Controller − A set of classes that handles communication from the user, overall application flow, and application-specific logic.
The Controller − A set of classes that handles communication from the user, overall application flow, and application-specific logic.
The idea is that you'll have a component called the view, which is solely responsible for rendering this user interface whether that be HTML or whether it actually be UI widgets on a desktop application.
The view talks to a model, and that model contains all of the data that the view needs to display. Views generally don't have much logic inside of them at all.
In a web application, the view might not have any code associated with it at all. It might just have HTML and then some expressions of where to take pieces of data from the model and plug them into the correct places inside the HTML template that you've built in the view.
The controller that organizes is everything. When an HTTP request arrives for an MVC application, that request gets routed to a controller, and then it's up to the controller to talk to either the database, the file system, or the model.
MVC development tool is included with Visual Studio 2012 and onwards. It can also be installed on Visual Studio 2010 SP1/Visual Web Developer 2010 Express SP1. If you are using Visual Studio 2010, you can install MVC 4 using the Web Platform Installer http://www.microsoft.com
Microsoft provides a free version of Visual Studio, which also contains SQL Server and it can be downloaded from https://www.visualstudio.com
Step 1 − Once downloading is complete, run the installer. The following dialog will be displayed.
Step 2 − Click the ‘Install’ button and it will start the installation process.
Once the installation process is completed successfully, you will see the following dialog.
Step 3 − Close this dialog and restart your computer if required.
Step 4 − Open Visual Studio from the Start Menu, which will open the following dialog. It will take a while for the first time only for preparation.
Once all is done, you will see the main window of Visual Studio as shown in the following screenshot.
You are now ready to start your application.
In this chapter, we will look at a simple working example of ASP.NET MVC. We will be building a simple web app here. To create an ASP.NET MVC application, we will use Visual Studio 2015, which contains all of the features you need to create, test, and deploy an MVC Framework application.
Following are the steps to create a project using project templates available in Visual Studio.
Step 1 − Open the Visual Studio. Click File → New → Project menu option.
A new Project dialog opens.
Step 2 − From the left pane, select Templates → Visual C# → Web.
Step 3 − In the middle pane, select ASP.NET Web Application.
Step 4 − Enter the project name, MVCFirstApp, in the Name field and click ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project.
Step 5 − To keep things simple, select the ‘Empty’ option and check the MVC checkbox in the Add folders and core references section. Click Ok.
It will create a basic MVC project with minimal predefined content.
Once the project is created by Visual Studio, you will see a number of files and folders displayed in the Solution Explorer window.
As you know that we have created ASP.Net MVC project from an empty project template, so for the moment the application does not contain anything to run.
Step 6 − Run this application from Debug → Start Debugging menu option and you will see a 404 Not Found Error.
The default browser is, Internet Explorer, but you can select any browser that you have installed from the toolbar.
To remove the 404 Not Found error, we need to add a controller, which handles all the incoming requests.
Step 1 − To add a controller, right-click on the controller folder in the solution explorer and select Add → Controller.
It will display the Add Scaffold dialog.
Step 2 − Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.
Step 3 − Set the name to HomeController and click the Add button.
You will see a new C# file HomeController.cs in the Controllers folder, which is open for editing in Visual Studio as well.
Step 4 − To make this a working example, let’s modify the controller class by changing the action method called Index using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFirstApp.Controllers {
public class HomeController : Controller {
// GET: Home
public string Index(){
return "Hello World, this is ASP.Net MVC Tutorials";
}
}
}
Step 5 − Run this application and you will see that the browser is displaying the result of the Index action method.
In this chapter, we will discuss the overall MVC pipeline and the life of an HTTP request as it travels through the MVC framework in ASP.NET. At a high level, a life cycle is simply a series of steps or events used to handle some type of request or to change an application state. You may already be familiar with various framework life cycles, the concept is not unique to MVC.
For example, the ASP.NET webforms platform features a complex page life cycle. Other .NET platforms, like Windows phone apps, have their own application life cycles. One thing that is true for all these platforms regardless of the technology is that understanding the processing pipeline can help you better leverage the features available and MVC is no different.
MVC has two life cycles −
The application life cycle
The request life cycle
The application life cycle refers to the time at which the application process actually begins running IIS until the time it stops. This is marked by the application start and end events in the startup file of your application.
It is the sequence of events that happen every time an HTTP request is handled by our application.
The entry point for every MVC application begins with routing. After the ASP.NET platform has received a request, it figures out how it should be handled through the URL Routing Module.
Modules are .NET components that can hook into the application life cycle and add functionality. The routing module is responsible for matching the incoming URL to routes that we define in our application.
All routes have an associated route handler with them and this is the entry point to the MVC framework.
The MVC framework handles converting the route data into a concrete controller that can handle requests. After the controller has been created, the next major step is Action Execution. A component called the action invoker finds and selects an appropriate Action method to invoke the controller.
After our action result has been prepared, the next stage triggers, which is Result Execution. MVC separates declaring the result from executing the result. If the result is a view type, the View Engine will be called and it's responsible for finding and rending our view.
If the result is not a view, the action result will execute on its own. This Result Execution is what generates an actual response to the original HTTP request.
Routing is the process of directing an HTTP request to a controller and the functionality of this processing is implemented in System.Web.Routing. This assembly is not part of ASP.NET MVC. It is actually part of the ASP.NET runtime, and it was officially released with the ASP.NET as a .NET 3.5 SP1.
System.Web.Routing is used by the MVC framework, but it's also used by ASP.NET Dynamic Data. The MVC framework leverages routing to direct a request to a controller. The Global.asax file is that part of your application, where you will define the route for your application.
This is the code from the application start event in Global.asax from the MVC App which we created in the previous chapter.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCFirstApp {
public class MvcApplication : System.Web.HttpApplication {
protected void Application_Start(){
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
Following is the implementation of RouteConfig class, which contains one method RegisterRoutes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCFirstApp {
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes){
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new{ controller = "Home", action = "Index", id = UrlParameter.Optional});
}
}
}
You will define the routes and those routes will map URLs to a specific controller action. An action is just a method on the controller. It can also pick parameters out of that URL and pass them as parameters into the method.
So this route that is defined in the application is the default route. As seen in the above code, when you see a URL arrive in the form of (something)/(something)/(something), then the first piece is the controller name, second piece is the action name, and the third piece is an ID parameter.
MVC applications use the ASP.NET routing system, which decides how URLs map to controllers and actions.
When Visual Studio creates the MVC project, it adds some default routes to get us started. When you run your application, you will see that Visual Studio has directed the browser to port 63664. You will almost certainly see a different port number in the URL that your browser requests because Visual Studio allocates a random port when the project is created.
In the last example, we have added a HomeController, so you can also request any of the following URLs, and they will be directed to the Index action on the HomeController.
http://localhost:63664/Home/
http://localhost:63664/Home/Index
When a browser requests http://mysite/ or http://mysite/Home, it gets back the output from HomeController’s Index method.
You can try this as well by changing the URL in the browser. In this example, it is http://localhost:63664/, except that the port might be different.
If you append /Home or /Home/Index to the URL and press ‘Enter’ button, you will see the same result from the MVC application.
As you can see in this case, the convention is that we have a controller called HomeController and this HomeController will be the starting point for our MVC application.
The default routes that Visual Studio creates for a new project assumes that you will follow this convention. But if you want to follow your own convention then you would need to modify the routes.
You can certainly add your own routes. If you don't like these action names, if you have different ID parameters or if you just in general have a different URL structure for your site, then you can add your own route entries.
Let’s take a look at a simple example. Consider we have a page that contains the list of processes. Following is the code, which will route to the process page.
routes.MapRoute(
"Process",
"Process/{action}/{id}",
defaults: new{
controller = "Process", action = "List ", id = UrlParameter.Optional}
);
When someone comes in and looks for a URL with Process/Action/Id, they will go to the Process Controller. We can make the action a little bit different, the default action, we can make that a List instead of Index.
Now a request that arrives looks like localhosts/process. The routing engine will use this routing configuration to pass that along, so it's going to use a default action of List.
Following is the complete class implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCFirstApp{
public class RouteConfig{
public static void RegisterRoutes(RouteCollection routes){
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Process", "Process/{action}/{id}",
defaults: new{
controller = " Process", action = "List ", id =
UrlParameter.Optional});
routes.MapRoute(
name: "Default", url: "{controller}/{action}/{id}",
defaults: new{
controller = "Home", action = "Index", id =
UrlParameter.Optional});
}
}
}
Step 1 − Run this and request for a process page with the following URL http://localhost:63664/Process
You will see an HTTP 404, because the routing engine is looking for ProcessController, which is not available.
Step 2 − Create ProcessController by right-clicking on Controllers folder in the solution explorer and select Add → Controller.
It will display the Add Scaffold dialog.
Step 3 − Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.
Step 4 − Set the name to ProcessController and click ‘Add’ button.
Now you will see a new C# file ProcessController.cs in the Controllers folder, which is open for editing in Visual Studio as well.
Now our default action is going to be List, so we want to have a List action here instead of Index.
Step 5 − Change the return type from ActionResult to string and also return some string from this action method using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFirstApp.Controllers{
public class ProcessController : Controller{
// GET: Process
public string List(){
return "This is Process page";
}
}
}
Step 6 − When you run this application, again you will see the result from the default route. When you specify the following URL, http://localhost:63664/Process/List, then you will see the result from the ProcessController.
Controllers are essentially the central unit of your ASP.NET MVC application. It is the 1st recipient, which interacts with incoming HTTP Request. So, the controller decides which model will be selected, and then it takes the data from the model and passes the same to the respective view, after that view is rendered. Actually, controllers are controlling the overall flow of the application taking the input and rendering the proper output.
Controllers are C# classes inheriting from System.Web.Mvc.Controller, which is the builtin controller base class. Each public method in a controller is known as an action method, meaning you can invoke it from the Web via some URL to perform an action.
The MVC convention is to put controllers in the Controllers folder that Visual Studio created when the project was set up.
Let’s take a look at a simple example of Controller by creating a new ASP.Net MVC project.
Step 1 − Open the Visual Studio and click on File → New → Project menu option.
A new Project dialog opens.
Step 2 − From the left pane, select Templates → Visual C# → Web.
Step 3 − In the middle pane, select ASP.NET Web Application.
Step 4 − Enter the project name ‘MVCControllerDemo’ in the Name field and click ok to continue. You will see the following dialog, which asks you to set the initial content for the ASP.NET project.
Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok.
It will create a basic MVC project with minimal predefined content.
Once the project is created by Visual Studio you will see a number of files and folders displayed in the Solution Explorer window.
Since we have created ASP.Net MVC project from an empty project template, so at the moment, the application does not contain anything to run.
Step 6 − Add EmployeeController by right-clicking on Controllers folder in the solution explorer. Select Add → Controller.
It will display the Add Scaffold dialog.
Step 7 − Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.
Step 8 − Set the name to EmployeeController and click ‘Add’ button.
You will see a new C# file EmployeeController.cs in the Controllers folder, which is open for editing in Visual Studio as well.
Now, in this application we will add a custom route for Employee controller with the default Route.
Step 1 − Go to “RouteConfig.cs” file under “App_Start” folder and add the following route.
routes.MapRoute(
"Employee", "Employee/{name}", new{
controller = "Employee", action = "Search", name =
UrlParameter.Optional });
Following is the complete implementation of RouteConfig.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCControllerDemo {
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes){
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Employee", "Employee/{name}", new{
controller = "Employee", action = "Search", name = UrlParameter.Optional });
routes.MapRoute(
name: "Default", url: "{controller}/{action}/{id}", defaults: new{
controller = "Home", action = "Index", id = UrlParameter.Optional });
}
}
}
Consider a scenario wherein any user comes and searches for an employee, specifying the URL “Employee/Mark”. In this case, Mark will be treated as a parameter name not like Action method. So in this kind of scenario our default route won’t work significantly.
To fetch the incoming value from the browser when the parameter is getting passed, MVC framework provides a simple way to address this problem. It is by using the parameter inside the Action method.
Step 2 − Change the EmployeeController class using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers {
public class EmployeeController : Controller {
// GET: Employee
public ActionResult Search(string name){
var input = Server.HtmlEncode(name);
return Content(input);
}
}
}
If you add a parameter to an action method, then the MVC framework will look for the value that matches the parameter name. It will apply all the possible combination to find out the parameter value. It will search in the Route data, query string, etc.
Hence, if you request for /Employee/Mark”, then the MVC framework will decide that I need a parameter with “UserInput”, and then Mark will get picked from the URL and that will get automatically passed.
Server.HtmlEncode will simply convert any kind of malicious script in plain text. When the above code is compiled and executed and requests the following URL http://localhost:61465/Employee/Mark, you will get the following output.
As you can see in the above screenshot, Mark is picked from the URL.
ASP.NET MVC Action Methods are responsible to execute requests and generate responses to it. By default, it generates a response in the form of ActionResult. Actions typically have a one-to-one mapping with user interactions.
For example, enter a URL into the browser, click on any particular link, and submit a form, etc. Each of these user interactions causes a request to be sent to the server. In each case, the URL of the request includes information that the MVC framework uses to invoke an action method. The one restriction on action method is that they have to be instance method, so they cannot be static methods. Also there is no return value restrictions. So you can return the string, integer, etc.
Actions are the ultimate request destination in an MVC application and it uses the controller base class. Let's take a look at the request processing.
When a URL arrives, like /Home/index, it is the UrlRoutingModule that inspects and understands that something configured within the routing table knows how to handle that URL.
When a URL arrives, like /Home/index, it is the UrlRoutingModule that inspects and understands that something configured within the routing table knows how to handle that URL.
The UrlRoutingModule puts together the information we've configured in the routing table and hands over control to the MVC route handler.
The UrlRoutingModule puts together the information we've configured in the routing table and hands over control to the MVC route handler.
The MVC route handler passes the controller over to the MvcHandler which is an HTTP handler.
The MVC route handler passes the controller over to the MvcHandler which is an HTTP handler.
MvcHandler uses a controller factory to instantiate the controller and it knows what controller to instantiate because it looks in the RouteData for that controller value.
MvcHandler uses a controller factory to instantiate the controller and it knows what controller to instantiate because it looks in the RouteData for that controller value.
Once the MvcHandler has a controller, the only thing that MvcHandler knows about is IController Interface, so it simply tells the controller to execute.
Once the MvcHandler has a controller, the only thing that MvcHandler knows about is IController Interface, so it simply tells the controller to execute.
When it tells the controller to execute, that's been derived from the MVC's controller base class. The Execute method creates an action invoker and tells that action invoker to go and find a method to invoke, find an action to invoke.
When it tells the controller to execute, that's been derived from the MVC's controller base class. The Execute method creates an action invoker and tells that action invoker to go and find a method to invoke, find an action to invoke.
The action invoker, again, looks in the RouteData and finds that action parameter that's been passed along from the routing engine.
The action invoker, again, looks in the RouteData and finds that action parameter that's been passed along from the routing engine.
Actions basically return different types of action results. The ActionResult class is the base for all action results. Following is the list of different kind of action results and its behavior.
ContentResult
Returns a string
FileContentResult
Returns file content
FilePathResult
Returns file content
FileStreamResult
Returns file content
EmptyResult
Returns nothing
JavaScriptResult
Returns script for execution
JsonResult
Returns JSON formatted data
RedirectToResult
Redirects to the specified URL
HttpUnauthorizedResult
Returns 403 HTTP Status code
RedirectToRouteResult
Redirects to different action/different controller action
ViewResult
Received as a response for view engine
PartialViewResult
Received as a response for view engine
Let’s have a look at a simple example from the previous chapter in which we have created an EmployeeController.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers {
public class EmployeeController : Controller{
// GET: Employee
public ActionResult Search(string name){
var input = Server.HtmlEncode(name);
return Content(input);
}
}
}
When you request the following URL http://localhost:61465/Employee/Mark, then you will receive the following output as an action.
Let us add one another controller.
Step 1 − Right-click on Controllers folder and select Add → Controller.
It will display the Add Scaffold dialog.
Step 2 − Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.
Step 3 − Set the name to CustomerController and click ‘Add’ button.
Now you will see a new C# file ‘CustomerController.cs’ in the Controllers folder, which is open for editing in Visual Studio as well.
Similarly, add one more controller with name HomeController. Following is the HomeController.cs class implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers {
public class HomeController : Controller{
// GET: Home
public string Index(){
return "This is Home Controller";
}
}
}
Step 4 − Run this application and you will receive the following output.
Step 5 − Add the following code in Customer controller, which we have created above.
public string GetAllCustomers(){
return @"<ul>
<li>Ali Raza</li>
<li>Mark Upston</li>
<li>Allan Bommer</li>
<li>Greg Jerry</li>
</ul>";
}
Step 6 − Run this application and request for http://localhost:61465/Customer/GetAllCustomers. You will see the following output.
You can also redirect to actions for the same controller or even for a different controller.
Following is a simple example in which we will redirect from HomeController to Customer Controller by changing the code in HomeController using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers{
public class HomeController : Controller{
// GET: Home
public ActionResult Index(){
return RedirectToAction("GetAllCustomers","Customer");
}
}
}
As you can see, we have used the RedirectToAction() method ActionResult, which takes two parameters, action name and controller name.
When you run this application, you will see the default route will redirect it to /Customer/GetAllCustomers
In ASP.NET MVC, controllers define action methods that usually have a one-to-one relationship with possible user interactions, but sometimes you want to perform logic either before an action method is called or after an action method runs.
To support this, ASP.NET MVC provides filters. Filters are custom classes that provide both a declarative and programmatic means to add pre-action and post-action behavior to controller action methods.
An action filter is an attribute that you can apply to a controller action or an entire controller that modifies the way in which the action is executed. The ASP.NET MVC framework includes several action filters −
OutputCache − Caches the output of a controller action for a specified amount of
time.
OutputCache − Caches the output of a controller action for a specified amount of
time.
HandleError − Handles errors raised when a controller action is executed.
HandleError − Handles errors raised when a controller action is executed.
Authorize − Enables you to restrict access to a particular user or role.
Authorize − Enables you to restrict access to a particular user or role.
The ASP.NET MVC framework supports four different types of filters −
Authorization Filters − Implements the IAuthorizationFilter attribute.
Authorization Filters − Implements the IAuthorizationFilter attribute.
Action Filters − Implements the IActionFilter attribute.
Action Filters − Implements the IActionFilter attribute.
Result Filters − Implements the IResultFilter attribute.
Result Filters − Implements the IResultFilter attribute.
Exception Filters − Implements the IExceptionFilter attribute.
Exception Filters − Implements the IExceptionFilter attribute.
Filters are executed in the order listed above. For example, authorization filters are always executed before action filters and exception filters are always executed after every other type of filter.
Authorization filters are used to implement authentication and authorization for controller actions. For example, the Authorize filter is an example of an Authorization filter.
Let’s take a look at a simple example by creating a new ASP.Net MVC project.
Step 1 − Open the Visual Studio and click File → New → Project menu option.
A new Project dialog opens.
Step 2 − From the left pane, select Templates → Visual C# → Web.
Step 3 − In the middle pane, select ASP.NET Web Application.
Step 4 − Enter project name MVCFiltersDemo in the Name field and click ok to continue and you will see the following dialog which asks you to set the initial content for the ASP.NET project.
Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok.
It will create a basic MVC project with minimal predefined content.
Step 6 − To add a controller, right-click on the controller folder in the solution explorer and select Add → Controller.
It will display the Add Scaffold dialog.
Step 7 − Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.
Step 8 − Set the name to HomeController and click ‘Add’ button.
You will see a new C# file ‘HomeController.cs’ in the Controllers folder, which is open for editing in Visual Studio as well.
An action filter can be applied to either an individual controller action or an entire controller. For example, an action filter OutputCache is applied to an action named Index() that returns the string. This filter causes the value returned by the action to be cached for 15 seconds.
To make this a working example, let’s modify the controller class by changing the action method called Index using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFiltersDemo.Controllers {
public class HomeController : Controller{
// GET: Home
[OutputCache(Duration = 15)]
public string Index(){
return "This is ASP.Net MVC Filters Tutorial";
}
}
}
When you run this application, you will see that the browser is displaying the result of the Index action method.
Let’s add another action method, which will display the current time.
namespace MVCFiltersDemo.Controllers{
public class HomeController : Controller{
// GET: Home
[OutputCache(Duration = 15)]
public string Index(){
return "This is ASP.Net MVC Filters Tutorial";
}
[OutputCache(Duration = 20)]
public string GetCurrentTime(){
return DateTime.Now.ToString("T");
}
}
}
Request for the following URL, http://localhost:62833/Home/GetCurrentTime, and you will receive the following output.
If you refresh the browser, you will see the same time because the action is cached for 20 seconds. It will be updated when you refresh it after 20 seconds.
To create your own custom filter, ASP.NET MVC framework provides a base class which is known as ActionFilterAttribute. This class implements both IActionFilter and IResultFilter interfaces and both are derived from the Filter class.
Let’s take a look at a simple example of custom filter by creating a new folder in your project with ActionFilters. Add one class for which right-click on ActionFilters folder and select Add → Class.
Enter ‘MyLogActionFilter’ in the name field and click ‘Add’ button.
This class will be derived from the ActionFilterAttribute, which is a base class and overrides the following method. Following is the complete implementation of MyLogActionFilter.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCFiltersDemo.ActionFilters {
public class MyLogActionFilter : ActionFilterAttribute{
public override void OnActionExecuting(ActionExecutingContext filterContext){
Log("OnActionExecuting", filterContext.RouteData);
}
public override void OnActionExecuted(ActionExecutedContext filterContext){
Log("OnActionExecuted", filterContext.RouteData);
}
public override void OnResultExecuting(ResultExecutingContext filterContext){
Log("OnResultExecuting", filterContext.RouteData);
}
public override void OnResultExecuted(ResultExecutedContext filterContext){
Log("OnResultExecuted", filterContext.RouteData);
}
private void Log(string methodName, RouteData routeData){
var controllerName = routeData.Values["controller"];
var actionName = routeData.Values["action"];
var message = String.Format(
"{0} controller:{1} action:{2}", methodName, controllerName, actionName);
Debug.WriteLine(message, "Action Filter Log");
}
}
}
Let us now apply the log filter to the HomeController using the following code.
using MVCFiltersDemo.ActionFilters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFiltersDemo.Controllers {
[MyLogActionFilter]
public class HomeController : Controller{
// GET: Home
[OutputCache(Duration = 10)]
public string Index(){
return "This is ASP.Net MVC Filters Tutorial";
}
[OutputCache(Duration = 10)]
public string GetCurrentTime(){
return DateTime.Now.ToString("T");
}
}
}
Run the application and then observe the output window.
As seen in the above screenshot, the stages of processing the action are logged to the Visual Studio output window.
Action selectors are attributes that can be applied to action methods and are used to influence which action method gets invoked in response to a request. It helps the routing engine to select the correct action method to handle a particular request.
It plays a very crucial role when you are writing your action methods. These selectors will decide the behavior of the method invocation based on the modified name given in front of the action method. It is usually used to alias the name of the action method.
There are three types of action selector attributes −
ActionName
NonAction
ActionVerbs
This class represents an attribute that is used for the name of an action. It also allows developers to use a different action name than the method name.
Let’s take a look at a simple example from the last chapter in which we have HomeController containing two action methods.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFiltersDemo.Controllers {
public class HomeController : Controller{
// GET: Home
public string Index(){
return "This is ASP.Net MVC Filters Tutorial";
}
public string GetCurrentTime(){
return DateTime.Now.ToString("T");
}
}
}
Let’s apply the the ActionName selector for GetCurrentTime by writing [ActionName("CurrentTime")] above the GetCurrentTime() as shown in the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFiltersDemo.Controllers {
public class HomeController : Controller{
// GET: Home
public string Index(){
return "This is ASP.Net MVC Filters Tutorial";
}
[ActionName("CurrentTime")]
public string GetCurrentTime(){
return DateTime.Now.ToString("T");
}
}
}
Now run this application and enter the following URL in the browser http://localhost:62833/Home/CurrentTime, you will receive the following output.
You can see that we have used the CurrentTime instead of the original action name, which is GetCurrentTime in the above URL.
NonAction is another built-in attribute, which indicates that a public method of a Controller is not an action method. It is used when you want that a method shouldn’t be treated as an action method.
Let’s take a look at a simple example by adding another method in HomeController and also apply the NonAction attribute using the following code.
using MVCFiltersDemo.ActionFilters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFiltersDemo.Controllers {
public class HomeController : Controller{
// GET: Home
public string Index(){
return "This is ASP.Net MVC Filters Tutorial";
}
[ActionName("CurrentTime")]
public string GetCurrentTime(){
return TimeString();
}
[NonAction]
public string TimeString(){
return "Time is " + DateTime.Now.ToString("T");
}
}
}
The new method TimeString is called from the GetCurrentTime() but you can’t use it as action in URL.
Let’s run this application and specify the following URL http://localhost:62833/Home/CurrentTime in the browser. You will receive the following output.
Let us now check the /TimeString as action in the URL and see what happens.
You can see that it gives ‘404—Not Found’ error.
Another selector filter that you can apply is the ActionVerbs attributes. So this restricts the indication of a specific action to specific HttpVerbs. You can define two different action methods with the same name but one action method responds to an HTTP Get request and another action method responds to an HTTP Post request.
MVC framework supports the following ActionVerbs.
HttpGet
HttpPost
HttpPut
HttpDelete
HttpOptions
HttpPatch
Let’s take a look at a simple example in which we will create EmployeeController.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers {
public class EmployeeController : Controller{
// GET: Employee
public ActionResult Search(string name = “No name Entered”){
var input = Server.HtmlEncode(name);
return Content(input);
}
}
}
Now let’s add another action method with the same name using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers {
public class EmployeeController : Controller{
// GET: Employee
//public ActionResult Index()
//{
// return View();
//}
public ActionResult Search(string name){
var input = Server.HtmlEncode(name);
return Content(input);
}
public ActionResult Search(){
var input = "Another Search action";
return Content(input);
}
}
}
When you run this application, it will give an error because the MVC framework is unable to figure out which action method should be picked up for the request.
Let us specify the HttpGet ActionVerb with the action you want as response using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers {
public class EmployeeController : Controller{
// GET: Employee
//public ActionResult Index()
//{
// return View();
//}
public ActionResult Search(string name){
var input = Server.HtmlEncode(name);
return Content(input);
}
[HttpGet]
public ActionResult Search(){
var input = "Another Search action";
return Content(input);
}
}
}
When you run this application, you will receive the following output.
In an ASP.NET MVC application, there is nothing like a page and it also doesn’t include anything that directly corresponds to a page when you specify a path in URL. The closest thing to a page in an ASP.NET MVC application is known as a View.
In ASP.NET MVC application, all incoming browser requests are handled by the controller and these requests are mapped to controller actions. A controller action might return a view or it might also perform some other type of action such as redirecting to another controller action.
Let’s take a look at a simple example of View by creating a new ASP.NET MVC project.
Step 1 − Open the Visual Studio and click File → New → Project menu option.
A new Project dialog opens.
Step 2 − From the left pane, select Templates → Visual C# → Web.
Step 3 − In the middle pane, select ASP.NET Web Application.
Step 4 − Enter the project name ‘MVCViewDemo’ in the Name field and click Ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project.
Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok.
It will create a basic MVC project with minimal predefined content. We now need to add controller.
Step 6 − Right-click on the controller folder in the solution explorer and select Add → Controller.
It will display the Add Scaffold dialog.
Step 7 − Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.
Step 8 − Set the name to HomeController and click ‘Add’ button.
You will see a new C# file ‘HomeController.cs’ in the Controllers folder which is open for editing in Visual Studio as well.
Let’s update the HomeController.cs file, which contains two action methods as shown in the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCViewDemo.Controllers {
public class HomeController : Controller{
// GET: Home
public ActionResult Index(){
return View();
}
public string Mycontroller(){
return "Hi, I am a controller";
}
}
}
Step 9 − Run this application and apend /Home/MyController to the URL in the browser and press enter. You will receive the following output.
As MyController action simply returns the string, to return a View from the action we need to add a View first.
Step 10 − Before adding a view let’s add another action, which will return a default view.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCViewDemo.Controllers {
public class HomeController : Controller{
// GET: Home
public ActionResult Index(){
return View();
}
public string Mycontroller(){
return "Hi, I am a controller";
}
public ActionResult MyView(){
return View();
}
}
}
Step 11 − Run this application and apend /Home/MyView to the URL in the browser and press enter. You will receive the following output.
You can see here that we have an error and this error is actually quite descriptive, which tells us it can't find the MyView view.
Step 12 − To add a view, right-click inside the MyView action and select Add view.
It will display the Add View dialog and it is going to add the default name.
Step 13 − Uncheck the ‘Use a layout page’ checkbox and click ‘Add’ button.
We now have the default code inside view.
Step 14 − Add some text in this view using the following code.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>MyView</title>
</head>
<body>
<div>
Hi, I am a view
</div>
</body>
</html>
Step 15 − Run this application and apend /Home/MyView to the URL in the browser. Press enter and you will receive the following output.
You can now see the text from the View.
In this chapter, we will discuss about building models in an ASP.NET MVC Framework application. A model stores data that is retrieved according to the commands from the Controller and displayed in the View.
Model is a collection of classes wherein you will be working with data and business logic. Hence, basically models are business domain-specific containers. It is used to interact with database. It can also be used to manipulate the data to implement the business logic.
Let’s take a look at a simple example of Model by creating a new ASP.Net MVC project.
Step 1 − Open the Visual Studio. Click File → New → Project menu option.
A new Project dialog opens.
Step 2 − From the left pane, select Templates → Visual C# → Web.
Step 3 − In the middle pane, select ASP.NET Web Application.
Step 4 − Enter the project name ‘MVCSimpleApp’ in the Name field and click Ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project.
Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok.
It will create a basic MVC project with minimal predefined content.
We need to add a controller now.
Step 6 − Right-click on the controller folder in the solution explorer and select Add → Controller.
It will display the Add Scaffold dialog.
Step 7 − Select the MVC 5 Controller – with read/write actions option. This template will create an Index method with default action for Controller. This will also list other methods like Edit/Delete/Create as well.
Step 8 − Click ‘Add’ button and Add Controller dialog will appear.
Step 9 − Set the name to EmployeeController and click the ‘Add’ button.
Step 10 − You will see a new C# file ‘EmployeeController.cs’ in the Controllers folder, which is open for editing in Visual Studio with some default actions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCSimpleApp.Controllers {
public class EmployeeController : Controller{
// GET: Employee
public ActionResult Index(){
return View();
}
// GET: Employee/Details/5
public ActionResult Details(int id){
return View();
}
// GET: Employee/Create
public ActionResult Create(){
return View();
}
// POST: Employee/Create
[HttpPost]
public ActionResult Create(FormCollection collection){
try{
// TODO: Add insert logic here
return RedirectToAction("Index");
}catch{
return View();
}
}
// GET: Employee/Edit/5
public ActionResult Edit(int id){
return View();
}
// POST: Employee/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection){
try{
// TODO: Add update logic here
return RedirectToAction("Index");
}catch{
return View();
}
}
// GET: Employee/Delete/5
public ActionResult Delete(int id){
return View();
}
// POST: Employee/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection){
try{
// TODO: Add delete logic here
return RedirectToAction("Index");
}catch{
return View();
}
}
}
}
Let’s add a model.
Step 11 − Right-click on the Models folder in the solution explorer and select Add → Class.
You will see the Add New Item dialog.
Step 12 − Select Class in the middle pan and enter Employee.cs in the name field.
Step 13 − Add some properties to Employee class using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCSimpleApp.Models {
public class Employee{
public int ID { get; set; }
public string Name { get; set; }
public DateTime JoiningDate { get; set; }
public int Age { get; set; }
}
}
Let’s update the EmployeeController.cs file by adding one more method, which will return the list of employee.
[NonAction]
public List<Employee> GetEmployeeList(){
return new List<Employee>{
new Employee{
ID = 1,
Name = "Allan",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 23
},
new Employee{
ID = 2,
Name = "Carson",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 45
},
new Employee{
ID = 3,
Name = "Carson",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 37
},
new Employee{
ID = 4,
Name = "Laura",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 26
},
};
}
Step 14 − Update the index action method as shown in the following code.
public ActionResult Index(){
var employees = from e in GetEmployeeList()
orderby e.ID
select e;
return View(employees);
}
Step 15 − Run this application and append /employee to the URL in the browser and press Enter. You will see the following output.
As seen in the above screenshot, there is an error and this error is actually quite descriptive which tells us it can't find the Index view.
Step 16 − Hence to add a view, right-click inside the Index action and select Add view.
It will display the Add View dialog and it is going to add the default name.
Step 17 − Select the List from the Template dropdown and Employee in Model class dropdown and also uncheck the ‘Use a layout page’ checkbox and click ‘Add’ button.
It will add some default code for you in this view.
@model IEnumerable<MVCSimpleApp.Models.Employee>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>Index</title>
</head>
<body>
<p>@Html.ActionLink("Create New", "Create")</p>
<table class = "table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.JoiningDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.JoiningDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
@Html.ActionLink("Details", "Details", new { id = item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</table>
</body>
</html>
Step 18 − Run this application and you will receive the following output.
A list of employees will be displayed.
In ASP.Net web forms, developers are using the toolbox for adding controls on any particular page. However, in ASP.NET MVC application there is no toolbox available to drag and drop HTML controls on the view. In ASP.NET MVC application, if you want to create a view it should contain HTML code. So those developers who are new to MVC especially with web forms background finds this a little hard.
To overcome this problem, ASP.NET MVC provides HtmlHelper class which contains different methods that help you create HTML controls programmatically. All HtmlHelper methods generate HTML and return the result as a string. The final HTML is generated at runtime by these functions. The HtmlHelper class is designed to generate UI and it should not be used in controllers or models.
There are different types of helper methods.
Createinputs − Creates inputs for text boxes and buttons.
Createinputs − Creates inputs for text boxes and buttons.
Createlinks − Creates links that are based on information from the routing tables.
Createlinks − Creates links that are based on information from the routing tables.
Createforms − Create form tags that can post back to our action, or to post back to an action on a different controller.
Createforms − Create form tags that can post back to our action, or to post back to an action on a different controller.
Action(String)
Overloaded. Invokes the specified child action method and returns the result as an HTML string. (Defined by ChildActionExtensions)
Action(String, Object)
Overloaded. Invokes the specified child action method with the specified parameters and returns the result as an HTML string. (Defined by ChildActionExtensions)
Action(String, RouteValueDictionary)
Overloaded. Invokes the specified child action method using the specified parameters and returns the result as an HTML string. (Defined by ChildActionExtensions)
Action(String, String)
Overloaded. Invokes the specified child action method using the specified controller name and returns the result as an HTML string. (Defined by ChildActionExtensions)
Action(String, String, Object)
Overloaded. Invokes the specified child action method using the specified parameters and controller name and returns the result as an HTML string. (Defined by ChildActionExtensions)
Action(String, String, RouteValueDictionary)
Overloaded. Invokes the specified child action method using the specified parameters and controller name and returns the result as an HTML string. (Defined by ChildActionExtensions)
ActionLink(String, String)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, Object)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, Object, Object)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, RouteValueDictionary)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, RouteValueDictionary, IDictionary<String, Object>)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, String)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, String, Object, Object)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, String, RouteValueDictionary, IDictionary<String, Object>)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, String, String, String, String, Object, Object)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, String, String, String, String, RouteValueDictionary, IDictionary<String, Object>)
Overloaded. (Defined by LinkExtensions)
BeginForm()
Overloaded. Writes an opening <form> tag to the response. The form uses the POST method, and the request is processed by the action method for the view. (Defined by FormExtensions)
BeginForm(Object)
Overloaded. Writes an opening <form> tag to the response and includes the route values in the action attribute. The form uses the POST method, and the request is processed by the action method for the view. (Defined by FormExtensions)
BeginForm(RouteValueDictionary)
Overloaded. Writes an opening <form> tag to the response and includes the route values from the route value dictionary in the action attribute. The form uses the POST method, and the request is processed by the action method for the view. (Defined by FormExtensions.)
BeginForm(String, String)
Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the POST method. (Defined by FormExtensions)
BeginForm(String, String, FormMethod)
Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the specified HTTP method. (Defined by FormExtensions)
BeginForm(String, String, FormMethod, IDictionary<String, Object>)
Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the specified HTTP method and includes the HTML attributes from a dictionary. (Defined by FormExtensions)
BeginForm(String, String, FormMethod, Object)
Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the specified HTTP method and includes the HTML attributes. (Defined by FormExtensions)
BeginForm(String, String, Object)
Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values. The form uses the POST method. (Defined by FormExtensions)
BeginForm(String, String, Object, FormMethod)
Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller, action, and route values. The form uses the specified HTTP method. (Defined by FormExtensions)
BeginForm(String, String, Object, FormMethod, Object)
Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller, action, and route values. The form uses the specified HTTP method and includes the HTML attributes. (Defined by FormExtensions)
BeginForm(String, String, RouteValueDictionary)
Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values from the route value dictionary. The form uses the POST method. (Defined by FormExtensions)
BeginForm(String, String, RouteValueDictionary, FormMethod)
Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values from the route value dictionary. The form uses the specified HTTP method. (Defined by FormExtensions)
BeginForm(String, String, RouteValueDictionary, FormMethod, IDictionary<String, Object>)
Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values from the route value dictionary. The form uses the specified HTTP method, and includes the HTML attributes from the dictionary. (Defined by FormExtensions)
BeginRouteForm(Object)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(RouteValueDictionary)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, FormMethod)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, FormMethod, IDictionary<String, Object>)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, FormMethod, Object)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, Object)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, Object, FormMethod)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, Object, FormMethod, Object)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, RouteValueDictionary)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, RouteValueDictionary, FormMethod)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, RouteValueDictionary, FormMethod, IDictionary<String, Object>)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
CheckBox(String)
Overloaded. Returns a checkbox input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)
CheckBox(String, Boolean)
Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, and a value to indicate whether the check box is selected. (Defined by InputExtensions)
CheckBox(String, Boolean, IDictionary<String, Object>)
Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, a value to indicate whether the check box is selected, and the HTML attributes. (Defined by InputExtensions)
CheckBox(String, Boolean, Object)
Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, a value that indicates whether the check box is selected, and the HTML attributes. (Defined by InputExtensions)
CheckBox(String, IDictionary<String, Object>)
Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, and the HTML attributes. (Defined by InputExtensions)
CheckBox(String, Object)
Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, and the HTML attributes. (Defined by InputExtensions)
Display(String)
Overloaded. Returns HTML markup for each property in the object that is represented by a string expression. (Defined by DisplayExtensions)
Display(String, Object)
Overloaded. Returns HTML markup for each property in the object that is represented by a string expression, using additional view data. (Defined by DisplayExtensions)
Display(String, String)
Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template. (Defined by DisplayExtensions)
Display(String, String, Object)
Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template and additional view data. (Defined by DisplayExtensions)
Display(String, String, String)
Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template and an HTML field ID. (Defined by DisplayExtensions)
Display(String, String, String, Object)
Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template, HTML field ID, and additional view data. (Defined by DisplayExtensions)
DisplayForModel()
Overloaded. Returns HTML markup for each property in the model. (Defined by DisplayExtensions)
DisplayForModel(Object)
Overloaded. Returns HTML markup for each property in the model, using additional view data. (Defined by DisplayExtensions)
DisplayForModel(String)
Overloaded. Returns HTML markup for each property in the model using the specified template. (Defined by DisplayExtensions)
DisplayForModel(String, Object)
Overloaded. Returns HTML markup for each property in the model, using the specified template and additional view data. (Defined by DisplayExtensions)
DisplayForModel(String, String)
Overloaded. Returns HTML markup for each property in the model using the specified template and HTML field ID. (Defined by DisplayExtensions)
DisplayForModel(String, String, Object)
Overloaded. Returns HTML markup for each property in the model, using the specified template, an HTML field ID, and additional view data. (Defined by DisplayExtensions)
DisplayName(String)
Gets the display name. (Defined by DisplayNameExtensions)
DisplayNameForModel()
Gets the display name for the model. (Defined by DisplayNameExtensions)
DisplayText(String)
Returns HTML markup for each property in the object that is represented by the specified expression. (Defined by DisplayTextExtensions)
DropDownList(String)
Overloaded. Returns a single-selection select element using the specified HTML helper and the name of the form field. (Defined by SelectExtensions)
DropDownList(String, IEnumerable<SelectListItem>)
Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, and the specified list items. (Defined by SelectExtensions)
DropDownList(String, IEnumerable<SelectListItem>, IDictionary<String, Object>)
Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HTML attributes. (Defined by SelectExtensions)
DropDownList(String, IEnumerable<SelectListItem>, Object)
Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HTML attributes. (Defined by SelectExtensions)
DropDownList(String, IEnumerable<SelectListItem>, String)
Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and an option label. (Defined by SelectExtensions)
DropDownList(String, IEnumerable<SelectListItem>, String, IDictionary<String, Object>)
Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, an option label, and the specified HTML attributes. (Defined by SelectExtensions)
DropDownList(String, IEnumerable<SelectListItem>, String, Object)
Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, an option label, and the specified HTML attributes. (Defined by SelectExtensions)
DropDownList(String, String)
Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, and an option label. (Defined by SelectExtensions)
Editor(String)
Overloaded. Returns an HTML input element for each property in the object that is represented by the expression. (Defined by EditorExtensions)
Editor(String, Object)
Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using additional view data. (Defined by EditorExtensions)
Editor(String, String)
Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template. (Defined by EditorExtensions)
Editor(String, String, Object)
Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template and additional view data. (Defined by EditorExtensions)
Editor(String, String, String)
Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template and HTML field name. (Defined by EditorExtensions)
Editor(String, String, String, Object)
Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template, HTML field name, and additional view data. (Defined by EditorExtensions)
EditorForModel()
Overloaded. Returns an HTML input element for each property in the model. (Defined by EditorExtensions)
EditorForModel(Object)
Overloaded. Returns an HTML input element for each property in the model, using additional view data. (Defined by EditorExtensions)
EditorForModel(String)
Overloaded. Returns an HTML input element for each property in the model, using the specified template. (Defined by EditorExtensions)
EditorForModel(String, Object)
Overloaded. Returns an HTML input element for each property in the model, using the specified template and additional view data. (Defined by EditorExtensions)
EditorForModel(String, String)
Overloaded. Returns an HTML input element for each property in the model, using the specified template name and HTML field name. (Defined by EditorExtensions)
EditorForModel(String, String, Object)
Overloaded. Returns an HTML input element for each property in the model, using the template name, HTML field name, and additional view data. (Defined by EditorExtensions)
EndForm()
Renders the closing </form> tag to the response. (Defined by FormExtensions)
Hidden(String)
Overloaded. Returns a hidden input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)
Hidden(String, Object)
Overloaded. Returns a hidden input element by using the specified HTML helper, the name of the form field, and the value. (Defined by InputExtensions)
Hidden(String, Object, IDictionary<String, Object>)
Overloaded. Returns a hidden input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)
Hidden(String, Object, Object)
Overloaded. Returns a hidden input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)
Id(String)
Gets the ID of the HtmlHelper string. (Defined by NameExtensions)
IdForModel()
Gets the ID of the HtmlHelper string. (Defined by NameExtensions)
Label(String)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
Label(String, IDictionary<String, Object>)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
Label(String, Object)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
Label(String, String)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression using the label text. (Defined by LabelExtensions)
Label(String, String, IDictionary<String, Object>)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
Label(String, String, Object)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
LabelForModel()
Overloaded. Returns an HTML label element and the property name of the property that is represented by the model. (Defined by LabelExtensions)
LabelForModel(IDictionary<String, Object>)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
LabelForModel(Object)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
LabelForModel(String)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression using the label text. (Defined by LabelExtensions)
LabelForModel(String, IDictionary<String, Object>)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
LabelForModel(String, Object)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
ListBox(String)
Overloaded. Returns a multi-select select element using the specified HTML helper and the name of the form field. (Defined by SelectExtensions)
ListBox(String, IEnumerable<SelectListItem>)
Overloaded. Returns a multi-select select element using the specified HTML helper, the name of the form field, and the specified list items. (Defined by SelectExtensions)
ListBox(String, IEnumerable<SelectListItem>, IDictionary<String, Object>)
Overloaded. Returns a multi-select select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HMTL attributes. (Defined by SelectExtensions)
ListBox(String, IEnumerable<SelectListItem>, Object)
Overloaded. Returns a multi-select select element using the specified HTML helper, the name of the form field, and the specified list items. (Defined by SelectExtensions)
Name(String)
Gets the full HTML field name for the object that is represented by the expression. (Defined by NameExtensions)
NameForModel()
Gets the full HTML field name for the object that is represented by the expression. (Defined by NameExtensions.)
Partial(String)
Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)
Partial(String, Object)
Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)
Partial(String, Object, ViewDataDictionary)
Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)
Partial(String, ViewDataDictionary)
Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)
Password(String)
Overloaded. Returns a password input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)
Password(String, Object)
Overloaded. Returns a password input element by using the specified HTML helper, the name of the form field, and the value. (Defined by InputExtensions)
Password(String, Object, IDictionary<String, Object>)
Overloaded. Returns a password input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)
Password(String, Object, Object)
Overloaded. Returns a password input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)
RadioButton(String, Object)
Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)
RadioButton(String, Object, Boolean)
Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)
RadioButton(String, Object, Boolean, IDictionary<String, Object>)
Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)
RadioButton(String, Object, Boolean, Object)
Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)
RadioButton(String, Object, IDictionary<String, Object>)
Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)
RadioButton(String, Object, Object)
Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)
RenderAction(String)
Overloaded. Invokes the specified child action method and renders the result inline in the parent view. (Defined by ChildActionExtensions)
RenderAction(String, Object)
Overloaded. Invokes the specified child action method using the specified parameters and renders the result inline in the parent view. (Defined by ChildActionExtensions)
RenderAction(String, RouteValueDictionary)
Overloaded. Invokes the specified child action method using the specified parameters and renders the result inline in the parent view. (Defined by ChildActionExtensions)
RenderAction(String, String)
Overloaded. Invokes the specified child action method using the specified controller name and renders the result inline in the parent view. (Defined by ChildActionExtensions)
RenderAction(String, String, Object)
Overloaded. Invokes the specified child action method using the specified parameters and controller name and renders the result inline in the parent view. (Defined by ChildActionExtensions)
RenderAction(String, String, RouteValueDictionary)
Overloaded. Invokes the specified child action method using the specified parameters and controller name and renders the result inline in the parent view. (Defined by ChildActionExtensions)
RenderPartial(String)
Overloaded. Renders the specified partial view by using the specified HTML helper. (Defined by RenderPartialExtensions)
RenderPartial(String, Object)
Overloaded. Renders the specified partial view, passing it a copy of the current ViewDataDictionary object, but with the Model property set to the specified model. (Defined by RenderPartialExtensions)
RenderPartial(String, Object, ViewDataDictionary)
Overloaded. Renders the specified partial view, replacing the partial view's ViewData property with the specified ViewDataDictionary object and setting the Model property of the view data to the specified model. (Defined by RenderPartialExtensions)
RenderPartial(String, ViewDataDictionary)
Overloaded. Renders the specified partial view, replacing its ViewData property with the specified ViewDataDictionary object. (Defined by RenderPartialExtensions)
RouteLink(String, Object)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, Object, Object)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, RouteValueDictionary)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, RouteValueDictionary, IDictionary<String, Object>)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, String)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, String, Object)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, String, Object, Object)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, String, RouteValueDictionary)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, String, RouteValueDictionary, IDictionary<String, Object>)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, String, String, String, String, Object, Object)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, String, String, String, String, RouteValueDictionary, IDictionary<String, Object>)
Overloaded. (Defined by LinkExtensions)
TextArea(String)
Overloaded. Returns the specified textarea element by using the specified HTML helper and the name of the form field. (Defined by TextAreaExtensions.)
TextArea(String, IDictionary<String, Object>)
Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, and the specified HTML attributes. (Defined by TextAreaExtensions)
TextArea(String, Object)
Overloaded. Returns the specified textarea element by using the specified HTML helper and HTML attributes. (Defined by TextAreaExtensions)
TextArea(String, String)
Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, and the text content. (Defined by TextAreaExtensions)
TextArea(String, String, IDictionary<String, Object>)
Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, and the specified HTML attributes. (Defined by TextAreaExtensions)
TextArea(String, String, Int32, Int32, IDictionary<String, Object>)
Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, the number of rows and columns, and the specified HTML attributes. (Defined by TextAreaExtensions)
TextArea(String, String, Int32, Int32, Object)
Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, the number of rows and columns, and the specified HTML attributes. (Defined by TextAreaExtensions)
TextArea(String, String, Object)
Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, and the specified HTML attributes. (Defined by TextAreaExtensions)
TextBox(String)
Overloaded. Returns a text input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)
TextBox(String, Object)
Overloaded. Returns a text input element by using the specified HTML helper, the name of the form field, and the value. (Defined by InputExtensions)
TextBox(String, Object, IDictionary<String, Object>)
Overloaded. Returns a text input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)
TextBox(String, Object, Object)
Overloaded. Returns a text input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)
TextBox(String, Object, String)
Overloaded. Returns a text input element. (Defined by InputExtensions)
TextBox(String, Object, String, IDictionary<String, Object>)
Overloaded. Returns a text input element. (Defined by InputExtensions)
TextBox(String, Object, String, Object)
Overloaded. Returns a text input element. (Defined by InputExtensions)
Validate(String)
Retrieves the validation metadata for the specified model and applies each rule to the data field. (Defined by ValidationExtensions)
ValidationMessage(String)
Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, IDictionary<String, Object>)
Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions.)
ValidationMessage(String, IDictionary<String, Object>, String)
Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, Object)
Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, Object, String)
Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, String)
Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, String, IDictionary<String, Object>)
Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, String, IDictionary<String, Object>, String)
Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, String, Object)
Overloaded. Displays a validation message if an error exists forthe specified field in the ModelStateDictionary object. (Definedby ValidationExtensions)
ValidationMessage(String, String, Object, String)
Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, String, String)
Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationSummary()
Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationSummary(Boolean)
Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)
ValidationSummary(Boolean, String)
Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)
ValidationSummary(Boolean, String, IDictionary<String, Object>)
Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)
ValidationSummary(Boolean, String, IDictionary<String, Object>, String)
Overloaded. (Defined by ValidationExtensions)
ValidationSummary(Boolean, String, Object)
Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)
ValidationSummary(Boolean, String, Object, String)
Overloaded. (Defined by ValidationExtensions)
ValidationSummary(Boolean, String, String)
Overloaded. (Defined by ValidationExtensions)
ValidationSummary(String)
Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationSummary(String, IDictionary<String, Object>)
Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationSummary(String, IDictionary<String, Object>, String)
Overloaded. (Defined by ValidationExtensions)
ValidationSummary(String, Object)
Overloaded. Returns an unordered list (ul element) of validation messages in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationSummary(String, Object, String)
Overloaded. (Defined by ValidationExtensions)
ValidationSummary(String, String)
Overloaded. (Defined by ValidationExtensions)
Value(String)
Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)
Value(String, String)
Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)
ValueForModel()
Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)
ValueForModel(String)
Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)
If you look at the view from the last chapter which we have generated from EmployeeController index action, you will see the number of operations that started with Html, like Html.ActionLink and Html.DisplayNameFor, etc. as shown in the following code.
@model IEnumerable<MVCSimpleApp.Models.Employee>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>Index</title>
</head>
<body>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class = "table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.JoiningDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.JoiningDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
@Html.ActionLink("Details", "Details", new { id = item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</table>
</body>
</html>
This HTML is a property that we inherit from the ViewPage base class. So, it's available in all of our views and it returns an instance of a type called HTML Helper.
Let’s take a look at a simple example in which we will enable the user to edit the employee. Hence, this edit action will be using significant numbers of different HTML Helpers.
If you look at the above code, you will see at the end the following HTML Helper methods
@Html.ActionLink("Edit", "Edit", new { id = item.ID })
In the ActionLink helper, the first parameter is of the link which is “Edit”, the second parameter is the action method in the Controller, which is also “Edit”, and the third parameter ID is of any particular employee you want to edit.
Let’s change the EmployeeController class by adding a static list and also change the index action using the following code.
public static List<Employee> empList = new List<Employee>{
new Employee{
ID = 1,
Name = "Allan",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 23
},
new Employee{
ID = 2,
Name = "Carson",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 45
},
new Employee{
ID = 3,
Name = "Carson",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 37
},
new Employee{
ID = 4,
Name = "Laura",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 26
},
};
public ActionResult Index(){
var employees = from e in empList
orderby e.ID
select e;
return View(employees);
}
Let’s update the Edit action. You will see two Edit actions one for GET and one for POST. Let’s update the Edit action for Get, which has only Id in the parameter as shown in the following code.
// GET: Employee/Edit/5
public ActionResult Edit(int id){
List<Employee> empList = GetEmployeeList();
var employee = empList.Single(m => m.ID == id);
return View(employee);
}
Now, we know that we have action for Edit but we don’t have any view for these actions. So we need to add a View as well. To do this, right-click on the Edit action and select Add View.
You will see the default name for view. Select Edit from the Template dropdown and Employee from the Model class dropdown.
Following is the default implementation in the Edit view.
@model MVCSimpleApp.Models.Employee
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>Edit</title>
</head>
<body>
@using (Html.BeginForm()){
@Html.AntiForgeryToken()
<div class = "form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(
true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.ID)
<div class = "form-group">
@Html.LabelFor(
model => model.Name, htmlAttributes: new{
@class = "control-label col-md-2" })
<div class = "col-md-10">
@Html.EditorFor(model => model.Name, new{
htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new{
@class = "text-danger" })
</div>
</div>
<div class = "form-group">
@Html.LabelFor(
model => model.JoiningDate, htmlAttributes: new{
@class = "control-label col-md-2" })
<div class = "col-md-10">
@Html.EditorFor(
model => model.JoiningDate, new{
htmlAttributes = new{ @class = "form-control" } })
@Html.ValidationMessageFor(
model => model.JoiningDate, "", new{
@class = "text-danger" })
</div>
</div>
<div class = "form-group">
@Html.LabelFor(
model => model.Age, htmlAttributes: new{
@class = "control-label col-md-2" })
<div class = "col-md-10">
@Html.EditorFor(
model => model.Age, new{
htmlAttributes = new{ @class = "form-control" } })
@Html.ValidationMessageFor(
model => model.Age, "", new{
@class = "text-danger" })
</div>
</div>
<div class = "form-group">
<div class = "col-md-offset-2 col-md-10">
<input type = "submit" value = "Save" class = "btn btn-default"/>
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
As you can see that there are many helper methods used. So, here “HTML.BeginForm” writes an opening Form Tag. It also ensures that the method is going to be “Post”, when the user clicks on the “Save” button.
Html.BeginForm is very useful, because it enables you to change the URL, change the method, etc.
In the above code, you will see one more HTML helper and that is “@HTML.HiddenFor”, which emits the hidden field.
MVC Framework is smart enough to figure out that this ID field is mentioned in the model class and hence it needs to be prevented from getting edited, that is why it is marked as hidden.
The Html.LabelFor HTML Helper creates the labels on the screen. The Html.ValidationMessageFor helper displays proper error message if anything is wrongly entered while making the change.
We also need to change the Edit action for POST because once you update the employee then it will call this action.
// POST: Employee/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection){
try{
var employee = empList.Single(m => m.ID == id);
if (TryUpdateModel(employee)){
//To Do:- database code
return RedirectToAction("Index");
}
return View(employee);
}catch{
return View();
}
}
Let’s run this application and request for the following URL http://localhost:63004/employee. You will receive the following output.
Click on the edit link on any particular employee, let’s say click on Allan edit link. You will see the following view.
Let’s change the age from 23 to 29 and click ‘Save’ button, then you will see the updated age on the Index View.
ASP.NET MVC model binding allows you to map HTTP request data with a model. It is the process of creating .NET objects using the data sent by the browser in an HTTP request. The ASP.NET Web Forms developers who are new to ASP.Net MVC are mostly confused how the values from View get converted to the Model class when it reaches the Action method of the Controller class, so this conversion is done by the Model binder.
Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene.
Let’s take a look at a simple example in which we add a ‘Create View’ in our project from the last chapter and we will see how we get these values from the View to the EmployeeController action method.
Following is the Create Action method for POST.
// POST: Employee/Create
[HttpPost]
public ActionResult Create(FormCollection collection){
try{
// TODO: Add insert logic here
return RedirectToAction("Index");
}catch{
return View();
}
}
Right-click on the Create Action method and select Add View...
It will display the Add View dialog.
As you can see in the above screenshot, the default name is already mentioned. Now select Create from the Template dropdown and Employee from the Model class dropdown.
You will see the default code in the Create.cshtml view.
@model MVCSimpleApp.Models.Employee
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>Create</title>
</head>
<body>
@using (Html.BeginForm()){
@Html.AntiForgeryToken()
<div class = "form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class = "form-group">
@Html.LabelFor(model => model.Name, htmlAttributes:
new{ @class = "control-label col-md-2" })
<div class = "col-md-10">
@Html.EditorFor(model => model.Name, new{ htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "",
new{ @class = "text-danger" })
</div>
</div>
<div class = "form-group">
@Html.LabelFor(model => model.JoiningDate, htmlAttributes:
new{ @class = "control-label col-md-2" })
<div class = "col-md-10">
@Html.EditorFor(model => model.JoiningDate, new{ htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.JoiningDate, "",
new { @class = "text-danger" })
</div>
</div>
<div class = "form-group">
@Html.LabelFor(model => model.Age, htmlAttributes:
new { @class = "control-label col-md-2" })
<div class = "col-md-10">
@Html.EditorFor(model => model.Age, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Age, "", new{ @class = "text-danger" })
</div>
</div>
<div class = "form-group">
<div class = "col-md-offset-2 col-md-10">
<input type = "submit" value = "Create" class = "btn btn-default"/>
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
When the user enters values on Create View then it is available in FormCollection as well as Request.Form. We can use any of these values to populate the employee info from the view.
Let’s use the following code to create the Employee using FormCollection.
// POST: Employee/Create
[HttpPost]
public ActionResult Create(FormCollection collection){
try {
Employee emp = new Employee();
emp.Name = collection["Name"];
DateTime jDate;
DateTime.TryParse(collection["DOB"], out jDate);
emp.JoiningDate = jDate;
string age = collection["Age"];
emp.Age = Int32.Parse(age);
empList.Add(emp);
return RedirectToAction("Index");
}catch {
return View();
}
}
Run this application and request for this URL http://localhost:63004/Employee/. You will receive the following output.
Click the ‘Create New’ link on top of the page and it will go to the following view.
Let’s enter data for another employee you want to add.
Click on the create button and you will see that the new employee is added in your list.
In the above example, we are getting all the posted values from the HTML view and then mapping these values to the Employee properties and assigning them one by one.
In this case, we will also be doing the type casting wherever the posted values are not of the same format as of the Model property.
This is also known as manual binding and this type of implementation might not be that bad for simple and small data model. However, if you have huge data models and need a lot of type casting then we can utilize the power and ease-of-use of ASP.NET MVC Model binding.
Let’s take a look at the same example we did for Model binding.
We need to change the parameter of Create Method to accept the Employee Model object rather than FormCollection as shown in the following code.
// POST: Employee/Create
[HttpPost]
public ActionResult Create(Employee emp){
try{
empList.Add(emp);
return RedirectToAction("Index");
}catch{
return View();
}
}
Now the magic of Model Binding depends on the id of HTML variables that are supplying the values.
For our Employee Model, the id of the HTML input fields should be the same as the Property names of the Employee Model and you can see that Visual Studio is using the same property names of the model while creating a view.
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
The mapping will be based on the Property name by default. This is where we will find HTML helper methods very helpful because these helper methods will generate the HTML, which will have proper Names for the Model Binding to work.
Run this application and request for the URL http://localhost:63004/Employee/. You will see the following output.
Let’s click on the Create New link on the top of the page and it will go to the following view.
Let’s enter data for another employee that we want to add.
Now click the create button and you will see that the new employee is added to your list using the ASP.Net MVC model binding.
In all ASP.NET MVC applications created in this tutorial we have been passing hard-coded data from the Controllers to the View templates. But, in order to build a real Web application, you might want to use a real database. In this chapter, we will see how to use a database engine in order to store and retrieve the data needed for your application.
To store and retrieve data, we will use a .NET Framework data-access technology known as the Entity Framework to define and work with Models.
The Entity Framework (EF) supports Code First technique, which allows you to create model objects by writing simple classes and then the database will be created on the fly from your classes, which enables a very clean and rapid development workflow.
Let’s take a look at a simple example in which we will add support for Entity framework in our example.
Step 1 − To install the Entity Framework, right-click on your project and select NuGet Package Manager → Manage NuGet Packages for Solution...
It will open the NuGet Package Manager. Search for Entity framework in the search box.
Select the Entity Framework and click ‘Install’ button. It will open the Preview dialog.
Click Ok to continue.
Click the ‘I Accept’ button to start installation.
Once the Entity Framework is installed you will see the message in out window as seen in the above screenshot.
We need to add another class to the Employee Model, which will communicate with Entity Framework to retrieve and save the data using the following code.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace MVCSimpleApp.Models{
public class Employee{
public int ID { get; set; }
public string Name { get; set; }
public DateTime JoiningDate { get; set; }
public int Age { get; set; }
}
public class EmpDBContext : DbContext{
public EmpDBContext()
{ }
public DbSet<Employee> Employees { get; set; }
}
}
As seen above, EmpDBContext is derived from an EF class known as DbContext. In this class, we have one property with the name DbSet, which basically represents the entity you want to query and save.
We need to specify the connection string under <configuration> tag for our database in the Web.config file.
<connectionStrings>
<add name = "EmpDBContext" connectionString = "Data
Source = (LocalDb)\v14.0;AttachDbFilename = |DataDirectory|\EmpDB.mdf;Initial
Catalog = EmployeeDB;Integrated Security = SSPI;"
providerName = "System.Data.SqlClient"/>
</connectionStrings>
You don't actually need to add the EmpDBContext connection string. If you don't specify a connection string, Entity Framework will create localDB database in the user’s directory with the fully qualified name of the DbContext class. For this demo, we will not add the connection string to make things simple.
Now we need to update the EmployeeController.cs file so that we can actually save and retrieve data from the database instead of using hardcoded data.
First we add create a private EmpDBContext class object and then update the Index, Create and Edit action methods as shown in the following code.
using MVCSimpleApp.Models;
using System.Linq;
using System.Web.Mvc;
namespace MVCSimpleApp.Controllers {
public class EmployeeController : Controller{
private EmpDBContext db = new EmpDBContext();
// GET: Employee
public ActionResult Index(){
var employees = from e in db.Employees
orderby e.ID
select e;
return View(employees);
}
// GET: Employee/Create
public ActionResult Create(){
return View();
}
// POST: Employee/Create
[HttpPost]
public ActionResult Create(Employee emp){
try{
db.Employees.Add(emp);
db.SaveChanges();
return RedirectToAction("Index");
}catch{
return View();
}
}
// GET: Employee/Edit/5
public ActionResult Edit(int id){
var employee = db.Employees.Single(m => m.ID == id);
return View(employee);
}
// POST: Employee/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection){
try{
var employee = db.Employees.Single(m => m.ID == id);
if (TryUpdateModel(employee)){
//To Do:- database code
db.SaveChanges();
return RedirectToAction("Index");
}
return View(employee);
}catch{
return View();
}
}
}
}
Then we run this application with the following URL http://localhost:63004/Employee. You will see the following output.
As you can see that there is no data on the view, this is because we have not added any records in our database, which is created by Visual Studio.
Let’s go to the SQL Server Object Explorer, you will see the database is created with the same name as we have in our DBContext class.
Let’s expand this database and you will see that it has one table which contains all the fields we have in our Employee model class.
To see the data in this table, right-click on the Employees table and select View Data.
You will see that we have no records at the moment.
Let’s add some records in the database directly as shown in the following screenshot.
Refresh the browser and you will see that data is now updated to the view from the database.
Let’s add one record from the browser by clicking the ‘Create New’ link. It will display the Create view.
Let’s add some data in the following field.
Click on the Create button and it will update the Index view as well add this new record to the database.
Now let’s go the SQL Server Object Explorer and refresh the database. Right-click on the Employees table and select the View data menu option. You will see that the record is added in the database.
Validation is an important aspect in ASP.NET MVC applications. It is used to check whether the user input is valid. ASP.NET MVC provides a set of validation that is easy-to-use and at the same time, it is also a powerful way to check for errors and, if necessary, display messages to the user.
DRY stands for Don't Repeat Yourself and is one of the core design principles of ASP.NET MVC. From the development point of view, it is encouraged to specify functionality or behavior only at one place and then it is used in the entire application from that one place.
This reduces the amount of code you need to write and makes the code you do write less error prone and easier to maintain.
Let’s take a look at a simple example of validation in our project from the last chapter. In this example, we will add data annotations to our model class, which provides some builtin set of validation attributes that can be applied to any model class or property directly in your application, such as Required, StringLength, RegularExpression, and Range validation attributes.
It also contains formatting attributes like DataType that help with formatting and don't provide any validation. The validation attributes specify behavior that you want to enforce on the model properties they are applied to.
The Required and MinimumLength attributes indicates that a property must have a value; but nothing prevents a user from entering white space to satisfy this validation. The RegularExpression attribute is used to limit what characters can be input.
Let’s update Employee class by adding different annotation attributes as shown in the following code.
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace MVCSimpleApp.Models {
public class Employee{
public int ID { get; set; }
[StringLength(60, MinimumLength = 3)]
public string Name { get; set; }
[Display(Name = "Joining Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",
ApplyFormatInEditMode = true)]
public DateTime JoiningDate { get; set; }
[Range(22, 60)]
public int Age { get; set; }
}
}
Now we also need to set limits to the database. However, the database in SQL Server Object Explorer shows the name property is set to NVARCHAR (MAX) as seen in the following screenshot.
To set this limitation on the database, we will use migrations to update the schema.
Open the Package Manager Console window from Tools → NuGet Package Manager → Package Manager Console.
Enter the following commands one by one in the Package Manager Console window.
Enable-Migrations
add-migration DataAnnotations
update-database
Following is the log after executing these commands in Package Manager Console window.
Visual Studio will also open the class which is derived from the DbMIgration class in which you can see the code that updates the schema constraints in Up method.
namespace MVCSimpleApp.Migrations {
using System;
using System.Data.Entity.Migrations;
public partial class DataAnnotations : DbMigration{
public override void Up(){
AlterColumn("dbo.Employees", "Name", c => c.String(maxLength: 60));
}
public override void Down(){
AlterColumn("dbo.Employees", "Name", c => c.String());
}
}
}
The Name field has a maximum length of 60, which is the new length limits in the database as shown in the following snapshot.
Run this application and go to Create view by specifying the following URL http://localhost:63004/Employees/Create
Let’s enter some invalid data in these fields and click Create Button as shown in the following screenshot.
You will see that jQuery client side validation detects the error, and it also displays an error message.
In this chapter, we will discuss how to implement security features in the application. We will also look at the new membership features included with ASP.NET and available for use from ASP.NET MVC. In the latest release of ASP.NET, we can manage user identities with the following −
Cloud
SQL database
Local Windows active directory
In this chapter, we will also take a look at the new identity components that is a part of ASP.NET and see how to customize membership for our users and roles.
Authentication of user means verifying the identity of the user. This is really important. You might need to present your application only to the authenticated users for obvious reasons.
Let’s create a new ASP.Net MVC application.
Click OK to continue.
When you start a new ASP.NET application, one of the steps in the process is configuring the authentication services for application needs.
Select MVC template and you will see that the Change Authentication button is now enabled.
This is done with the Change Authentication button that appears in the New Project dialog. The default authentication is, Individual User Accounts.
When you click the Change button, you will see a dialog with four options, which are as follows.
The first option is No Authentication and this option is used when you want to build a website that doesn't care who the visitors are.
It is open to anyone and every person connects as every single page. You can always change that later, but the No Authentication option means there will not be any features to identify users coming to the website.
The second option is Individual User Accounts and this is the traditional forms-based authentication where users can visit a website. They can register, create a login, and by default their username is stored in a SQL Server database using some new ASP.NET identity features, which we'll look at.
The password is also stored in the database, but it is hashed first. Since the password is hashed, you don't have to worry about plain-text passwords sitting in a database.
This option is typically used for internet sites where you want to establish the identity of a user. In addition to letting a user create a local login with a password for your site, you can also enable logins from third parties like Microsoft, Google, Facebook, and Twitter.
This allows a user to log into your site using their Live account or their Twitter account and they can select a local username, but you don't need to store any passwords.
This is the option that we'll spend some time with in this module; the individual user accounts option.
The third option is to use organizational accounts and this is typically used for business applications where you will be using active directory federation services.
You will either set up Office 365 or use Azure Active Directory Services, and you have a single sign-on for internal apps and Cloud apps.
You will also need to provide an app ID so your app will need to be registered with the Windows Azure management portal if this is Azure based, and the app ID will uniquely identify this application amongst all the applications that might be registered.
The fourth option is Windows authentication, which works well for intranet applications.
A user logs into Windows desktop and can launch a browser to the application that sits inside the same firewall. ASP.NET can automatically pick up the user's identity, the one that was established by active directory. This option does not allow any anonymous access to the site, but again that is a configuration setting that can be changed.
Let's take a look into the forms-based authentication, the one that goes by the name, Individual User Accounts. This application will store usernames and passwords, old passwords in a local SQL Server database, and when this project is created, Visual Studio will also add NuGet packages.
Now run this application and when you first come to this application you will be an anonymous user.
You won't have an account that you can log into yet so you will need to register on this site.
Click on the Register link and you will see the following view.
Enter your email id and password.
Click Register. Now, the application will recognize you.
It will be able to display your name. In the following screenshot, you can see Hello, [email protected]! is displayed. You can click on that and it's a link to a page where you can change the password.
You can also log off, shut down, reboot, come back a week later, and you should be able to log in with the credentials that you used earlier. Now click on the log off button and it will display the following page.
Click again on the Log in link and you will go to the following page.
You can login again with the same credentials.
A lot of work goes on behind the scene to get to this point. However, what we want to do is examine each of the features and see how this UI is built. What is managing the logoff and the login process? Where is this information sorted in the database?
Let's just start with a couple of simple basics. First we will see how is this username displayed. Open the _Layout.cshtml from the View/Shared folder in the Solution explorer.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8" />
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class = "navbar navbar-inverse navbar-fixed-top">
<div class = "container">
<div class = "navbar-header">
<button type = "button" class = "navbar-toggle" datatoggle = "collapse"
data-target = ".navbar-collapse">
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new
{ area = "" }, new { @class = "navbar-brand" })
</div>
<div class = "navbar-collapse collapse">
<ul class = "nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class = "container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
There is a common navigation bar, the application name, the menu, and there is a partial view that's being rendered called _loginpartial. That's actually the view that displays the username or the register and login name. So _loginpartial.cshtml is also in the shared folder.
@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated) {
using (Html.BeginForm("LogOff", "Account", FormMethod.Post,
new { id = "logoutForm", @class = "navbar-right" })){
@Html.AntiForgeryToken()
<ul class = "nav navbar-nav navbar-right">
<li>
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!",
"Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li>
<a href = "javascript:document.getElementById('logoutForm').submit()">Logoff</a>
</li>
</ul>
}
}else{
<ul class = "nav navbar-nav navbar-right">
<li>@Html.ActionLink("Register", "Register", "Account", routeValues:
null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null,
htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
As you can see above, there are if/else statements. If we do not know who the user is, because the request is not authenticated, this view will display register and login links. The user can click on the link to log in or register. All this is done by the account controller.
For now, we want to see how to get the username, and that's inside Request.IsAuthenticated. You can see a call to User.Identity.GetUserName. That will retrieve the username, which in this case is ‘[email protected]’
Let's suppose that we have some sort of information which we want to protect from unauthenticated users. So let’s create a new controller to display that information, but only when a user is logged in.
Right-click on the controller folder and select Add → Controller.
Select an MVC 5 controller - Empty controller and click ‘Add’.
Enter the name SecretController and click ‘Add’ button.
It will have two actions inside as shown in the following code.
using System.Web.Mvc;
namespace MVCSecurityDemo.Controllers{
public class SecretController : Controller{
// GET: Secret
public ContentResult Secret(){
return Content("Secret informations here");
}
public ContentResult PublicInfo(){
return Content("Public informations here");
}
}
}
When you run this application, you can access this information without any authentication as shown in the following screenshot.
So only authenticated users should be able to get to Secret action method and the PublicInfo can be used by anyone without any authentication.
To protect this particular action and keep unauthenticated users from arriving here, you can use the Authorize attribute. The Authorize attribute without any other parameters will make sure that the identity of the user is known and they're not an anonymous user.
// GET: Secret
[Authorize]
public ContentResult Secret(){
return Content("Secret informations here");
}
Now run this application again and specify the same URL http://localhost:54232/Secret/Secret. The MVC application will detect that you do not have access to that particular area of the application and it will redirect you automatically to the login page, where it will give you a chance to log in and try to get back to that area of the application where you were denied.
You can see that it is specified in the return URL, which essentially tells this page that if the user logs in successfully, redirect them back to /secret/secret.
Enter your credentials and click ‘Log in’ button. You will see that it goes directly to that page.
If you come back to the home page and log off, you cannot get to the secret page. You will be asked again to log in, but if go to /Secret/PublicInfo, you can see that page, even when you are not authenticated.
So, when you don't want to be placing authorization on every action when you're inside a controller where pretty much everything requires authorization. In that case you can always apply this filter to the controller itself and now every action inside of this controller will require the user to be authenticated.
using System.Web.Mvc;
namespace MVCSecurityDemo.Controllers{
[Authorize]
public class SecretController : Controller{
// GET: Secret
public ContentResult Secret(){
return Content("Secret informations here");
}
public ContentResult PublicInfo(){
return Content("Public informations here");
}
}
}
But if you really want any action to be open, you can come override this authorization rule with another attribute, which is, AllowAnonymous.
using System.Web.Mvc;
namespace MVCSecurityDemo.Controllers{
[Authorize]
public class SecretController : Controller{
// GET: Secret
public ContentResult Secret(){
return Content("Secret informations here");
}
[AllowAnonymous]
public ContentResult PublicInfo(){
return Content("Public informations here");
}
}
}
Run this application and you can access the /Secret/PublicInfo with logging in but other action will require authentication.
It will allow anonymous users into this one action only.
With the Authorize attribute, you can also specify some parameters, like allow some specific users into this action.
using System.Web.Mvc;
namespace MVCSecurityDemo.Controllers{
[Authorize(Users = "[email protected]")]
public class SecretController : Controller{
// GET: Secret
public ContentResult Secret(){
return Content("Secret informations here");
}
[AllowAnonymous]
public ContentResult PublicInfo(){
return Content("Public informations here");
}
}
}
When you run this application and go to /secret/secret, it will ask you to log in because it is not the proper user for this controller.
In this chapter, we will be focusing on one of the most common ASP.NET techniques like Caching to improve the performance of the application. Caching means to store something in memory that is being used frequently to provide better performance. We will see how you can dramatically improve the performance of an ASP.NET MVC application by taking advantage of the output cache.
In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is the same concept as output caching in web forms. The output cache enables you to cache the content returned by a controller action.
Output caching basically allows you to store the output of a particular controller in the memory. Hence, any future request coming for the same action in that controller will be returned from the cached result. That way, the same content does not need to be generated each and every time the same controller action is invoked.
We need caching in many different scenarios to improve the performance of an application. For example, you have an ASP.NET MVC application, which displays a list employees. Now when these records are retrieved from the database by executing a database query each and every time a user invokes the controller action it returns the Index view.
Hence you can take advantage of the output cache to avoid executing a database query every time a user invokes the same controller action. In this case, the view will be retrieved from the cache instead of being regenerated from the controller action.
Caching enables you to avoid performing redundant work on the server.
Let’s take a look at a simple example of caching in our project.
[OutputCache(Duration = 60)]
public ActionResult Index(){
var employees = from e in db.Employees
orderby e.ID
select e;
return View(employees);
}
As you can see, we have added “OutputCache” attribute on the index action of the EmployeeController. Now to understand this concept, let us run this application in debugger mode and also insert a breakpoint in the Index action method.
Specify the following URL http://localhost:63004/employee, and press ‘Enter’. You will see that the breakpoint is hit in the Index action method.
Press ‘F5’ button to continue and you will see the list of employees on your view, which are retrieved from the database.
Refresh the browser again within 60 seconds and you will see that the breakpoint is not hit this time. This is because we have used output cache with duration of seconds. So it will cache this result for 60 seconds and when you refresh the browser, it will get the result from the cache, and it won’t load the content from the database server.
In addition to duration parameter, there are other settings options as well which you can use with output cache. These settings are not only for MVC framework but it is inherited from ASP.Net Caching.
In some cases, you might want different cached versions, such as, when you create a detail page, then when you click on the detailed link you will get details for the selected employee.
But first we need to create the detail view. For this, right-click on the Details action method from the EmployeeController and select Add View...
You will see the Details name is selected by default. Now select Details from the Template dropdown and Employee from the Model class dropdown.
Click ‘Add’ to continue and you will see the Details.cshtml.
@model MVCSimpleApp.Models.Employee
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>Details</title>
</head>
<body>
<div>
<h4>Employee</h4>
<hr />
<dl class = "dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Name)
</dt>
<dd>
@Html.DisplayFor(model => model.Name)
</dd>
<dt>
@Html.DisplayNameFor(model => model.JoiningDate)
</dt>
<dd>
@Html.DisplayFor(model => model.JoiningDate)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Age)
</dt>
<dd>
@Html.DisplayFor(model => model.Age)
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
@Html.ActionLink("Back to List", "Index")
</p>
</body>
</html>
You can take advantage of the VaryByParam property of the [OutputCache] attribute. This property enables you to create different cached versions of the very same content when a form parameter or query string parameter varies. Following is the implementation of Details action.
// GET: Employee/Details/5
[OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
public ActionResult Details(int id){
var employee = db.Employees.SingleOrDefault(e => e.ID == id);
return View(employee);
}
When the above code is compiled and executed, you will receive the following output by specifying the URL http://localhost:63004/employee.
Click on the Details link of any link and you will see the details view of that particular employee.
The Details() action includes a VaryByParam property with the value “Id”. When different values of the Id parameter are passed to the controller action, different cached versions of the Details view are generated.
It is important to understand that using the VaryByParam property results in more caching. A different cached version of the Details view is created for each different version of the Id parameter.
You can create a cache profile in the web.config file. It is an alternative to configuring output cache properties by modifying properties of the [OutputCache] attribute. It offers a couple of important advantages which are as follows.
Controls how controller actions cache content in one central location.
Controls how controller actions cache content in one central location.
Creates one cache profile and apply the profile to several controllers or controller actions.
Creates one cache profile and apply the profile to several controllers or controller actions.
Modifies the web configuration file without recompiling your application.
Modifies the web configuration file without recompiling your application.
Disables caching for an application that has already been deployed to production.
Disables caching for an application that has already been deployed to production.
Let’s take a look at a simple example of cache profile by creating the cache profile in web.config file. The <caching> section must appear within the <system.web> section.
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name = "Cache10Min" duration = "600" varyByParam = "none"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
You can apply the Cache10Min profile to a controller action with the [OutputCache] attribute which is as follows.
[OutputCache(CacheProfile = "Cache10Min")]
public ActionResult Index(){
var employees = from e in db.Employees
orderby e.ID
select e;
return View(employees);
}
Run this application and specify the following URL http://localhost:63004/employee
If you invoke the Index() action as shown above then the same time will be returned for 10 Min.
In this chapter, we will look at the Razor view engine in ASP.NET MVC applications and some of the reasons why Razor exists. Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language.
Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine. You can use it anywhere to generate output like HTML. It's just that ASP.NET MVC has implemented a view engine that allows us to use Razor inside of an MVC application to produce HTML.
You will have a template file that's a mix of some literal text and some blocks of code. You combine that template with some data or a specific model where the template specifies where the data is supposed to appear, and then you execute the template to generate your output.
Razor is very similar to how ASPX files work. ASPX files are templates, which contain literal text and some C# code that specifies where your data should appear. We execute those to generate the HTML for our application.
Razor is very similar to how ASPX files work. ASPX files are templates, which contain literal text and some C# code that specifies where your data should appear. We execute those to generate the HTML for our application.
ASPX files have a dependency on the ASP.NET runtime to be available to parse and execute those ASPX files. Razor has no such dependencies.
ASPX files have a dependency on the ASP.NET runtime to be available to parse and execute those ASPX files. Razor has no such dependencies.
Unlike ASPX files, Razor has some different design goals.
Unlike ASPX files, Razor has some different design goals.
Microsoft wanted Razor to be easy to use and easy to learn, and work inside of tools like Visual Studio so that IntelliSense is available, the debugger is available, but they wanted Razor to have no ties to a specific technology, like ASP.NET or ASP.NET MVC.
If you're familiar with the life cycle of an ASPX file, then you're probably aware that there's a dependency on the ASP.NET runtime to be available to parse and execute those ASPX files. Microsoft wanted Razor to be smart, to make a developer's job easier.
Let’s take a look at a sample code from an ASPX file, which contains some literal text. This is our HTML markup. It also contains little bits of C# code.
<% foreach (var item in Model) { %>
<tr>
<td>
<%: Html.ActionLink("Edit", "Edit", new { id = item.ID })%> |
<%: Html.ActionLink("Details", "Details", new { id = item.ID }) %>|
<%: Html.ActionLink("Delete", "Delete", new { id = item.ID })%>
</td>
<td>
<%: item.Name %>
</td>
<td>
<%: String.Format("{0,g}", item.JoiningDate) %>
</td>
</tr>
<%}%>
But these Web forms were basically repurposed by Microsoft to work with the earlier releases of MVC, meaning ASPX files were never a perfect match for MVC.
The syntax is a bit clunky when you need to transition from C# code back to HTML and from HTML code back into C# code. You are also prompted by IntelliSense to do things that just don't make sense in an MVC project, like add directives for output caching and user controls into an ASPX view.
Now look at this code which produces the same output, the difference being it is using the Razor syntax.
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
@Html.ActionLink("Details", "Details", new { id = item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
<td>
@item.Name
</td>
<td>
@String.Format("{0,g}", item.JoiningDate)
</td>
</tr>
}
With Razor syntax you can begin a bit of C# code by using the ‘@’ sign and the Razor parse will automatically switch into parsing this statement, this foreach statement, as a bit of C# code.
But when we're finished with the foreach statement and we have our opening curly brace, we can transition from C# code into HTML without putting an explicit token in there, like the percent in the angle bracket signs.
The Razor parser is smart enough to switch between C# code and HTML and again, from HTML back into C# code when we need to place our closing curly brace here. If you compare these two blocks of code, I think you'll agree that the Razor version is easier to read and easier to write.
Let's create a new ASP.Net MVC project.
Enter the name of project in the name field and click Ok.
To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok. It will create a basic MVC project with minimal predefined content.
Once the project is created by Visual Studio, you will see a number of files and folders displayed in the Solution Explorer window. As we have created ASP.Net MVC project from an empty project template, so at the moment the application does not contain anything to run. Since we start with an empty application and don't even have a single controller, let’s add a HomeController.
To add a controller right-click on the controller folder in the solution explorer and select Add → Controller. It will display the Add Scaffold dialog.
Select the MVC 5 Controller – Empty option and click Add button and then the Add Controller dialog will appear.
Set the name to HomeController and click ‘Add’ button. You will see a new C# file ‘HomeController.cs’ in the Controllers folder, which is open for editing in Visual Studio as well.
Right-click on the Index action and select Add View...
Select Empty from the Template dropdown and click Add button. Visual Studio will create an Index.cshtml file inside the View/Home folder.
Notice that Razor view has a cshtml extension. If you're building your MVC application using Visual Basic it will be a VBHTML extension. At the top of this file is a code block that is explicitly setting this Layout property to null.
When you run this application you will see the blank webpage because we have created a View from an Empty template.
Let's add some C# code to make things more interesting. To write some C# code inside a Razor view, the first thing we will do is type the ‘@’ symbol that tells the parser that it is going to be doing something in code.
Let's create a FOR loop specify ‘@i’ inside the curly braces, which is essentially telling Razor to put the value of i.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>Index</title>
</head>
<body>
<div>
@for (int index = 0; index < 12; index++){
<div>@index </div>
}
</div>
</body>
</html>
Run this application and you will see the following output.
DataAnnotations is used to configure your model classes, which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of .NET applications, such as ASP.NET MVC, which allows these applications to leverage the same annotations for client-side validations. DataAnnotation attributes override default Code-First conventions.
System.ComponentModel.DataAnnotations includes the following attributes that impacts the nullability or size of the column.
Key
Timestamp
ConcurrencyCheck
Required
MinLength
MaxLength
StringLength
System.ComponentModel.DataAnnotations.Schema namespace includes the following attributes that impacts the schema of the database.
Table
Column
Index
ForeignKey
NotMapped
InverseProperty
Entity Framework relies on every entity having a key value that it uses for tracking entities. One of the conventions that Code First depends on is how it implies which property is the key in each of the Code First classes.
The convention is to look for a property named “Id” or one that combines the class name and “Id”, such as “StudentId”. The property will map to a primary key column in the database. The Student, Course and Enrollment classes follow this convention.
Now let’s suppose Student class used the name StdntID instead of ID. When Code First does not find a property that matches this convention it will throw an exception because of Entity Framework’s requirement that you must have a key property.
You can use the key annotation to specify which property is to be used as the EntityKey.
Let’s take a look at the Student class which contains StdntID. It doesn’t follow the default Code First convention so to handle this, Key attribute is added, which will make it a primary key.
public class Student{
[Key]
public int StdntID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
When you run the application and look into the database in SQL Server Explorer, you will see that the primary key is now StdntID in Students table.
Entity Framework also supports composite keys. Composite keys are primary keys that consist of more than one property. For example, you have a DrivingLicense class whose primary key is a combination of LicenseNumber and IssuingCountry.
public class DrivingLicense{
[Key, Column(Order = 1)]
public int LicenseNumber { get; set; }
[Key, Column(Order = 2)]
public string IssuingCountry { get; set; }
public DateTime Issued { get; set; }
public DateTime Expires { get; set; }
}
When you have composite keys, Entity Framework requires you to define an order of the key properties. You can do this using the Column annotation to specify an order.
Code First will treat Timestamp properties the same as ConcurrencyCheck properties, but it will also ensure that the database field generated by Code First is non-nullable.
It's more common to use rowversion or timestamp fields for concurrency checking. But rather than using the ConcurrencyCheck annotation, you can use the more specific TimeStamp annotation as long as the type of the property is byte array. You can only have one timestamp property in a given class.
Let’s take a look at a simple example by adding the TimeStamp property to the Course class.
public class Course{
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
[Timestamp]
public byte[] TStamp { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
As you can see in the above example, Timestamp attribute is applied to Byte[] property of the Course class. So, Code First will create a timestamp column TStamp in the Courses table.
The ConcurrencyCheck annotation allows you to flag one or more properties to be used for concurrency checking in the database, when a user edits or deletes an entity. If you've been working with the EF Designer, this aligns with setting a property's ConcurrencyMode to Fixed.
Let’s take a look at a simple example and see how ConcurrencyCheck works by adding it to the Title property in Course class.
public class Course{
public int CourseID { get; set; }
[ConcurrencyCheck]
public string Title { get; set; }
public int Credits { get; set; }
[Timestamp, DataType("timestamp")]
public byte[] TimeStamp { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
In the above Course class, ConcurrencyCheck attribute is applied to the existing Title property. Code First will include Title column in update command to check for optimistic concurrency as shown in the following code.
exec sp_executesql N'UPDATE [dbo].[Courses]
SET [Title] = @0
WHERE (([CourseID] = @1) AND ([Title] = @2))
',N'@0 nvarchar(max) ,@1 int,@2 nvarchar(max)
',@0 = N'Maths',@1 = 1,@2 = N'Calculus'
go
The Required annotation tells EF that a particular property is required. Let’s have a look at the following Student class in which Required id is added to the FirstMidName property. Required attribute will force EF to ensure that the property has data in it.
public class Student{
[Key]
public int StdntID { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
You can see in the above example of Student class Required attribute is applied to FirstMidName and LastName. So, Code First will create a NOT NULL FirstMidName and LastName column in the Students table as shown in the following screenshot.
The MaxLength attribute allows you to specify additional property validations. It can be applied to a string or array type property of a domain class. EF Code First will set the size of a column as specified in MaxLength attribute.
Let’s take a look at the following Course class in which MaxLength(24) attribute is applied to Title property.
public class Course{
public int CourseID { get; set; }
[ConcurrencyCheck]
[MaxLength(24)]
public string Title { get; set; }
public int Credits { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
When you run the above application, Code-First will create a nvarchar(24) column Title in the Coursed table as shown in the following screenshot.
Now when the user sets the Title which contains more than 24 characters, EF will throw EntityValidationError.
The MinLength attribute allows you to specify additional property validations, just as you did with MaxLength. MinLength attribute can also be used with MaxLength attribute as shown in the following code.
public class Course{
public int CourseID { get; set; }
[ConcurrencyCheck]
[MaxLength(24) , MinLength(5)]
public string Title { get; set; }
public int Credits { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
EF will throw EntityValidationError, if you set a value of Title property less than the specified length in MinLength attribute or greater than the specified length in MaxLength attribute.
StringLength also allows you to specify additional property validations like MaxLength. The difference being StringLength attribute can only be applied to a string type property of Domain classes.
public class Course{
public int CourseID { get; set; }
[StringLength (24)]
public string Title { get; set; }
public int Credits { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
Entity Framework also validates the value of a property for StringLength attribute. Now, if the user sets the Title, which contains more than 24 characters, then EF will throw EntityValidationError.
Default Code First convention creates a table name same as the class name. If you are letting Code First create the database, you can also change the name of the tables it is creating. You can use Code First with an existing database. But it's not always the case that the names of the classes match the names of the tables in your database.
Table attribute overrides this default convention. EF Code First will create a table with a specified name in Table attribute for a given domain class.
Let’s take a look at an example in which the class is named Student, and by convention, Code First presumes this will map to a table named Students. If that's not the case you can specify the name of the table with the Table attribute as shown in the following code.
[Table("StudentsInfo")]
public class Student{
[Key]
public int StdntID { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
You can now see that the Table attribute specifies the table as StudentsInfo. When the table is generated, you will see the table name StudentsInfo as shown in the following screenshot.
You cannot only specify the table name but you can also specify a schema for the table using the Table attribute using the following code.
[Table("StudentsInfo", Schema = "Admin")]
public class Student{
[Key]
public int StdntID { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
In the above example, the table is specified with admin schema. Now Code First will create StudentsInfo table in Admin schema as shown in the following screenshot.
It is also the same as Table attribute, but Table attribute overrides the table behavior while Column attribute overrides the column behavior. Default Code First convention creates a column name same as the property name.
If you are letting Code First create the database, and you also want to change the name of the columns in your tables. Column attribute overrides this default convention. EF Code First will create a column with a specified name in the Column attribute for a given property.
Let’s take a look at the following example again in which the property is named FirstMidName, and by convention, Code First presumes this will map to a column named FirstMidName. If that's not the case, you can specify the name of the column with the Column attribute as shown in the following code.
public class Student{
public int ID { get; set; }
public string LastName { get; set; }
[Column("FirstName")]
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
You can now see that the Column attribute specifies the column as FirstName. When the table is generated, you will see the column name FirstName as shown in the following screenshot.
The Index attribute was introduced in Entity Framework 6.1. Note − If you are using an earlier version, the information in this section does not apply.
You can create an index on one or more columns using the IndexAttribute. Adding the attribute to one or more properties will cause EF to create the corresponding index in the database when it creates the database.
Indexes make the retrieval of data faster and efficient, in most cases. However, overloading a table or view with indexes could unpleasantly affect the performance of other operations such as inserts or updates.
Indexing is the new feature in Entity Framework where you can improve the performance of your Code First application by reducing the time required to query data from the database.
You can add indexes to your database using the Index attribute, and override the default Unique and Clustered settings to get the index best suited to your scenario. By default, the index will be named IX_<property name>
Let’s take a look at the following code in which Index attribute is added in Course class for Credits.
public class Cours{
public int CourseID { get; set; }
public string Title { get; set; }
[Index]
public int Credits { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
You can see that the Index attribute is applied to the Credits property. Now when the table is generated, you will see IX_Credits in Indexes.
By default, indexes are non-unique, but you can use the IsUnique named parameter to specify that an index should be unique. The following example introduces a unique index as shown in the following code.
public class Course{
public int CourseID { get; set; }
[Index(IsUnique = true)]
public string Title { get; set; }
[Index]
public int Credits { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
Code First convention will take care of the most common relationships in your model, but there are some cases where it needs help. For example, by changing the name of the key property in the Student class created a problem with its relationship to Enrollment class.
public class Enrollment{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public Grade? Grade { get; set; }
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}
public class Student{
[Key]
public int StdntID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
While generating the database, Code First sees the StudentID property in the Enrollment class and recognizes it, by the convention that it matches a class name plus “ID”, as a foreign key to the Student class. But there is no StudentID property in the Student class, rather it is StdntID property in Student class.
The solution for this is to create a navigation property in the Enrollment and use the ForeignKey DataAnnotation to help Code First understand how to build the relationship between the two classes as shown in the following code.
public class Enrollment{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public Grade? Grade { get; set; }
public virtual Course Course { get; set; }
[ForeignKey("StudentID")]
public virtual Student Student { get; set; }
}
You can see now that the ForeignKey attribute is applied to navigation property.
By default conventions of Code First, every property that is of a supported data type and which includes getters and setters are represented in the database. But this isn’t always the case in applications. NotMapped attribute overrides this default convention. For example, you might have a property in the Student class such as FatherName, but it does not need to be stored. You can apply NotMapped attribute to a FatherName property, which you do not want to create a column in a database. Following is the code.
public class Student{
[Key]
public int StdntID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
[NotMapped]
public int FatherName { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
You can see that NotMapped attribute is applied to the FatherName property. Now when the table is generated, you will see that FatherName column will not be created in a database, but it is present in Student class.
Code First will not create a column for a property which does not have either getters or setters.
The InverseProperty is used when you have multiple relationships between classes. In the Enrollment class, you may want to keep track of who enrolled a Current Course and who enrolled a Previous Course.
Let’s add two navigation properties for the Enrollment class.
public class Enrollment{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public Grade? Grade { get; set; }
public virtual Course CurrCourse { get; set; }
public virtual Course PrevCourse { get; set; }
public virtual Student Student { get; set; }
}
Similarly, you’ll also need to add in the Course class referenced by these properties. The Course class has navigation properties back to the Enrollment class, which contains all the current and previous enrollments.
public class Course{
public int CourseID { get; set; }
public string Title { get; set; }
[Index]
public int Credits { get; set; }
public virtual ICollection<Enrollment> CurrEnrollments { get; set; }
public virtual ICollection<Enrollment> PrevEnrollments { get; set; }
}
Code First creates {Class Name}_{Primary Key} foreign key column if the foreign key property is not included in a particular class as shown in the above classes. When the database is generated you will see a number of foreign keys as seen in the following screenshot.
As you can see that Code First is not able to match up the properties in the two classes on its own. The database table for Enrollments should have one foreign key for the CurrCourse and one for the PrevCourse, but Code First will create four foreign key properties, i.e.
CurrCourse_CourseID
PrevCourse_CourseID
Course_CourseID
Course_CourseID1
To fix these problems, you can use the InverseProperty annotation to specify the alignment of the properties.
public class Course{
public int CourseID { get; set; }
public string Title { get; set; }
[Index]
public int Credits { get; set; }
[InverseProperty("CurrCourse")]
public virtual ICollection<Enrollment> CurrEnrollments { get; set; }
[InverseProperty("PrevCourse")]
public virtual ICollection<Enrollment> PrevEnrollments { get; set; }
}
As you can see now, when InverseProperty attribute is applied in the above Course class by specifying which reference property of Enrollment class it belongs to, Code First will generate database and create only two foreign key columns in Enrollments table as shown in the following screenshot.
We recommend you to execute the above example for better understanding.
In this chapter, we will talk about NuGet which is a package manager for .NET and Visual Studio. NuGet can be used to find and install packages, that is, software pieces and assemblies and things that you want to use in your project.
NuGet is not a tool that is specific to ASP.NET MVC projects. This is a tool that you can use inside of Visual Studio for console applications, WPF applications, Azure applications, any types of application.
NuGet is a package manager, and is responsible for downloading, installing, updating, and configuring software in your system. From the term software we don’t mean end users software like Microsoft Word or Notepad 2, etc. but pieces of software, which you want to use in your project, assembly references.
For example, assemblies you want to use might be mock, for mock object unit testing, or NHibernate for data access, and components you use when building your application. The above-mentioned components are open source software, but some NuGet packages you find are closed source software. Some of the packages you'll find are even produced by Microsoft.
The common theme along all the packages mentioned above, like mock and NHibernate, and Microsoft packages like a preview for the Entity Framework, is that they don't come with Visual Studio by default.
To install any of these components without NuGet, you will need the following steps.
If you want to use one of those components, you need to find the home page for some particular project and look for a download link. Then once the project is downloaded, it's typically in a ZIP format so you will need to extract it.
If you didn't download binaries, then you will first need to build the software and then reference it in your project. And many components at that point still require some configuration to get up and running.
NuGet replaces all of the steps discussed earlier and you just need to say Add Package. NuGet knows where to download the latest version, it knows how to extract it, how to establish a reference to that component, and even configure it. This leaves you more time to just build the software.
Let’s take a look at a simple example in which we will add support for Entity framework in our ASP.NET MVC project using NuGet.
Step 1 − Install the Entity Framework. Right-click on the project and select NuGet Package Manager → Manage NuGet Packages for Solution...
It will open the NuGet Package Manager.
Step 2 − Search for Entity framework in the search box.
Step 3 − Select the Entity Framework and click ‘Install’ button. It will open the Preview dialog.
Step 4 − Click Ok to continue.
Step 5 − Click the ‘I Accept’ button to start the installation.
Once the Entity Framework is installed you will see the message in out window as shown above.
When you install a package with NuGet, you will see a new packages directory in the same folder as the solution file hosting your project. This package directory contains all the packages that you have installed for any of the projects in that solution.
In other words, NuGet is not downloading packages into a central location, it's storing them on a per solution basis.
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
When you're building APIs on the Web, there are several ways you can build APIs on the Web. These include HTTP/RPC, and what this means is using HTTP in Remote Procedure Call to call into things, like Methods, across the Web.
The verbs themselves are included in the APIs, like Get Customers, Insert Invoice, Delete Customer, and that each of these endpoints end up being a separate URI.
Let’s take a look at a simple example of Web API by creating a new ASP.NET Web Application.
Step 1 − Open the Visual Studio and click File → New → Project menu option.
A new Project dialog opens.
Step 2 − From the left pane, select Templates → Visual C# → Web.
Step 3 − In the middle pane, select ASP.NET Web Application
Enter project name WebAPIDemo in the Name field and click Ok to continue. You will see the following dialog, which asks you to set the initial content for the ASP.NET project.
Step 4 − To keep things simple, select the Empty option and check the Web API checkbox in the ‘Add folders and core references for’ section and click Ok.
Step 5 − It will create a basic MVC project with minimal predefined content.
Once the project is created by Visual Studio, you will see a number of files and folders displayed in the Solution Explorer window.
Step 6 − Now we need to add a model. Right-click on the Models folder in the solution explorer and select Add → Class.
You will now see the Add New Item dialog.
Step 7 − Select Class in the middle pan and enter Employee.cs in the name field.
Step 8 − Add some properties to Employee class using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebAPIDemo.Models {
public class Employee{
public int ID { get; set; }
public string Name { get; set; }
public DateTime JoiningDate { get; set; }
public int Age { get; set; }
}
}
Step 9 − Let’s add the controller. Right-click on the controller folder in the solution explorer and select Add → Controller.
It will display the Add Scaffold dialog.
Step 10 − Select the Web API 2 Controller - Empty option. This template will create an Index method with default action for controller.
Step 11 − Click ‘Add’ button and the Add Controller dialog will appear.
Step 12 − Set the name to EmployeesController and click ‘Add’ button.
You will see a new C# file ‘EmployeeController.cs’ in the Controllers folder, which is open for editing in Visual Studio with some default actions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WebAPIDemo.Models;
namespace WebAPIDemo.Controllers{
public class EmployeesController : ApiController{
Employee[] employees = new Employee[]{
new Employee { ID = 1, Name = "Mark", JoiningDate =
DateTime.Parse(DateTime.Today.ToString()), Age = 30 },
new Employee { ID = 2, Name = "Allan", JoiningDate =
DateTime.Parse(DateTime.Today.ToString()), Age = 35 },
new Employee { ID = 3, Name = "Johny", JoiningDate =
DateTime.Parse(DateTime.Today.ToString()), Age = 21 }
};
public IEnumerable<Employee> GetAllEmployees(){
return employees;
}
public IHttpActionResult GetEmployee(int id){
var employee = employees.FirstOrDefault((p) => p.ID == id);
if (employee == null){
return NotFound();
}
return Ok(employee);
}
}
}
Step 13 − Run this application and specify /api/employees/ at the end of the URL and press ‘Enter’. You will see the following output.
Step 14 − Let us specify the following URL http://localhost:63457/api/employees/1 and you will see the following output.
ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Visual Studio 2013 includes pre-installed code generators for MVC and Web API projects. You add scaffolding to your project when you want to quickly add code that interacts with data models. Using scaffolding can reduce the amount of time to develop standard data operations in your project.
As you have seen that we have created the views for Index, Create, Edit actions and also need to update the actions methods as well. But ASP.Net MVC provides an easier way to create all these Views and action methods using scaffolding.
Let’s take a look at a simple example. We will create the same example which contains a model class Employee, but this time we will use scaffolding.
Step 1 − Open the Visual Studio and click on File → New → Project menu option.
A new Project dialog opens.
Step 2 − From the left pane, select Templates → Visual C# → Web.
Step 3 − In the middle pane, select ASP.NET Web Application.
Step 4 − Enter the project name ‘MVCScaffoldingDemo’ in the Name field and click Ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project.
Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’section and click Ok.
It will create a basic MVC project with minimal predefined content.
Once the project is created by Visual Studio, you will see a number of files and folders displayed in the Solution Explorer window.
First step is to install the Entity Framework. Right-click on the project and select NuGet Package Manager → Manage NuGet Packages for Solution...
It will open the ‘NuGet Package Manager’. Search for Entity framework in the search box.
Select the Entity Framework and click ‘Install’ button. It will open the Preview dialog.
Click Ok to continue.
Click ‘I Accept’ button to start installation.
Once the Entity Framework is installed you will see the message in the out window as shown in the above screenshot.
To add a model, right-click on the Models folder in the solution explorer and select Add → Class. You will see the ‘Add New Item’ dialog.
Select Class in the middle pan and enter Employee.cs in the name field.
Add some properties to Employee class using the following code.
using System;
namespace MVCScaffoldingDemo.Models {
public class Employee{
public int ID { get; set; }
public string Name { get; set; }
public DateTime JoiningDate { get; set; }
public int Age { get; set; }
}
}
We have an Employee Model, now we need to add another class, which will communicate with Entity Framework to retrieve and save the data. Following is the complete code in Employee.cs file.
using System;
using System.Data.Entity;
namespace MVCScaffoldingDemo.Models{
public class Employee{
public int ID { get; set; }
public string Name { get; set; }
public DateTime JoiningDate { get; set; }
public int Age { get; set; }
}
public class EmpDBContext : DbContext{
public DbSet<Employee> Employees { get; set; }
}
}
As you can see ‘EmpDBContext’ is derived from an EF class known as ‘DbContext’. In this class, we have one property with the name DbSet, which basically represents the entity which you want to query and save.
Now let’s build a solution and you will see the message when the project is successfully build.
To add a scaffold, right-click on Controllers folder in the Solution Explorer and select Add → New Scaffolded Item.
It will display the Add Scaffold dialog.
Select MVC 5 Controller with views, using Entity Framework in the middle pane and click ‘Add’ button, which will display the Add Controller dialog.
Select Employee from the Model class dropdown and EmpDBContext from the Data context class dropdown. You will also see that the controller name is selected by default.
Click ‘Add’ button to continue and you will see the following code in the EmployeesController, which is created by Visual Studio using Scaffolding.
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using MVCScaffoldingDemo.Models;
namespace MVCScaffoldingDemo.Controllers {
public class EmployeesController : Controller{
private EmpDBContext db = new EmpDBContext();
// GET: Employees
public ActionResult Index(){
return View(db.Employees.ToList());
}
// GET: Employees/Details/5
public ActionResult Details(int? id){
if (id == null){
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employee employee = db.Employees.Find(id);
if (employee == null){
return HttpNotFound();
}
return View(employee);
}
// GET: Employees/Create
public ActionResult Create(){
return View();
}
// POST: Employees/Create
// To protect from overposting attacks, please enable the specific
properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Name,JoiningDate,Age")]
Employee employee){
if (ModelState.IsValid){
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(employee);
}
// GET: Employees/Edit/5
public ActionResult Edit(int? id){
if (id == null){
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employee employee = db.Employees.Find(id);
if (employee == null){
return HttpNotFound();
}
return View(employee);
}
// POST: Employees/Edit/5
// To protect from overposting attacks, please enable the specific
properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,Name,JoiningDate,Age")]Employee employee){
if (ModelState.IsValid){
db.Entry(employee).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(employee);
}
// GET: Employees/Delete/5
public ActionResult Delete(int? id){
if (id == null){
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employee employee = db.Employees.Find(id);
if (employee == null){
return HttpNotFound();
}
return View(employee);
}
// POST: Employees/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id){
Employee employee = db.Employees.Find(id);
db.Employees.Remove(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing){
if (disposing){
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Run your application and specify the following URL http://localhost:59359/employees. You will see the following output.
You can see there is no data in the View, because we have not added any records to the database, which is created by Visual Studio.
Let’s add one record from the browser by clicking the ‘Create New’ link, it will display the Create view.
Let’s add some data in the following field.
Click the ‘Create’ button and it will update the Index view.
You can see that the new record is also added to the database.
As you can see that we have implemented the same example by using Scaffolding, which is a much easier way to create your Views and Action methods from your model class.
In this chapter, we will look at Bootstrap which is a front-end framework now included with ASP.NET and MVC. It is a popular front-end tool kit for web applications, and will help you build a user interface with HTML, CSS, and JavaScript.
It was originally created by web developers at Twitter for personal use, however, it is now an open source and has become popular with designers and developers because of its flexiblility and ease of use.
You can use Bootstrap to create an interface that looks good on everything from large desktop displays to small mobile screens. In this chapter, we will also look at how Bootstrap can work with your layout views to structure the look of an application.
Bootstrap provides all the pieces you need for layout, buttons, forms, menus, widgets, picture carousels, labels, badges, typography, and all sorts of features. Since Bootstrap is all HTML, CSS and JavaScript, all open standards, you can use it with any framework including ASP.NET MVC. When you start a new MVC project, Bootstrap will be present, meaning you'll find Bootstrap.css and Bootstrap.js in your project.
Let’s create a new ASP.NET Web Application.
Enter the name of the project, let’s say ‘MVCBootstrap’ and click Ok. You will see the following dialog.
In this dialog, if you select the empty template, you will get an empty web application and there will be no Bootstrap present. There won't be any controllers or any other script files either.
Now select the MVC template and click Ok. When Visual Studio creates this solution, one of the packages that it will download and install into the project will be the Bootstrap NuGet package. You can verify by going to packages.config and you can see the Bootstrap version 3 package.
You can also see the Content folder which contains different css files.
Run this application and you will see the following page.
When this page appears, most of the layout and styling that you see is layout and styling that has been applied by Bootstrap. It includes the navigation bar at the top with the links as well as the display that is advertising ASP.NET. It also includes all of these pieces down about getting started and getting more libraries and web hosting.
If you expand the browser just a little bit more, those will actually lay out side by side and that's part of Bootstrap's responsive design features.
If you look under the content folder, you will find the Bootstrap.css file.
The NuGet package also gives a minified version of that file that's a little bit smaller. Under scripts, you will find Bootstrap.js, that's required for some of the components of Bootstrap.
It does have a dependency on jQuery and fortunately jQuery is also installed in this project and there's a minified version of the Bootstrap JavaScript file.
Now the question is, where are all these added in the application? You might expect, that it would be in the layout template, the layout view for this project which is under View/Shared/_layout.cshtml.
The layout view controls the structure of the UI. Following is the complete code in _layout.cshtml file.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8" />
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class = "navbar navbar-inverse navbar-fixed-top">
<div class = "container">
<div class = "navbar-header">
<button type = "button" class = "navbar-toggle" datatoggle =
"collapse" data-target = ".navbar-collapse">
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new
{ area = "" }, new { @class = "navbar-brand" })
</div>
<div class = "navbar-collapse collapse">
<ul class = "nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class = "container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
In the above code there are two things to note. First at the top, after <title> you will see the following line of code.
@Styles.Render("~/Content/css")
The Styles.Render for Content/css is actually where the Bootstrap.css file is going to be included, and at the bottom, you will see the following line of code.
@Scripts.Render("~/bundles/bootstrap")
It is rendering the Bootstrap script. So in order to find out what exactly is inside of these bundles, we'll have to go into the BundleConfig file, which is in App_Start folder.
In BundleConfig, you can see at the bottom that the CSS bundle includes both Bootstrap.css and our custom site.css.
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
It is a place where we can add our own style sheets to customize the look of the application. You can also see the Bootstrap bundle that appears before the CSS bundle that includes Bootstrap.js, and another JavaScript file, respond.js.
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
Let’s comment Bootstrap.css as shown in the following code.
bundles.Add(new StyleBundle("~/Content/css").Include(
//"~/Content/bootstrap.css",
"~/Content/site.css"));
Run this application again, just to give you an idea of what Bootstrap is doing, because now the only styles that are available are the styles that are in site.css.
As you can see we lost the layout, the navigation bar at the top of the page. Now everything looks ordinary and boring.
Let us now see what Bootstrap is all about. There's a couple of things that Bootstrap just does automatically and there's a couple of things that Bootstrap can do for you when you add classes and have the right HTML structure. If you look at the _layout.cshtml file, you will see the navbar class as shown in the following code.
<div class = "navbar navbar-inverse navbar-fixed-top">
<div class = "container">
<div class = "navbar-header">
<button type = "button" class = "navbar-toggle" datatoggle =
"collapse" data-target = ".navbar-collapse">
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
</button>
<a class = "navbar-brand" href = "/">Application name</a>
</div>
<div class = "navbar-collapse collapse">
<ul class = "nav navbar-nav">
<li><a href = "/">Home</a></li>
<li><a href = "/Home/About">About</a></li>
<li><a href = "/Home/Contact">Contact</a></li>
</ul>
<ul class = "nav navbar-nav navbar-right">
<li><a href = "/Account/Register" id = "registerLink">Register</a></li>
<li><a href = "/Account/Login" id = "loginLink">Log in</a></li>
</ul>
</div>
</div>
</div>
It is CSS classes from Bootstrap like navbar, navbar inverse, and navbar fixed top. If you remove a few of these classes like navbar inverse, navbar fixed top and also uncomment the Bootstrap.css and then run your application again, you will see the following output.
You will see that we still have a navbar, but now it's not using inverse colors so it's white. It also doesn't stick to the top of the page. When you scroll down, the navigation bar scrolls off the top and you can no longer see it again.
In computer programming, unit testing is a software testing method by which individual units of source code are tested to determine whether they are fit for use. In other words, it is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation.
In procedural programming, a unit could be an entire module, but it is more commonly an individual function or procedure. In object-oriented programming, a unit is often an entire interface, such as a class, but could be an individual method.
Unit testing is often automated but it can also be done manually.
The primary goal of unit testing is to take the smallest piece of testable software in the application and determine whether it behaves exactly as you expect. Each unit is tested separately before integrating them into modules to test the interfaces between modules.
Let’s take a look at a simple example of unit testing in which we create a new ASP.NET MVC application with Unit Testing.
Step 1 − Open the Visual Studio and click File → New → Project menu option.
A new Project dialog opens.
Step 2 − From the left pane, select Templates > Visual C# > Web.
Step 3 − In the middle pane, select ASP.NET Web Application.
Step 4 − Enter the project name ‘MVCUnitTestingDemo’ in the Name field and click Ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project.
Step 5 − Select the MVC as template and don’t forget to check the Add unit tests checkbox which is at the bottom of dialog. You can also change the test project name as well, but in this example we leave it as is since it is the default name.
Once the project is created by Visual Studio, you will see a number of files and folders displayed in the Solution Explorer window.
Step 6 − You can see that two projects are there in the solution explorer. One is the ASP.NET Web project and the other is the unit testing project.
Step 7 − Run this application and you will see the following output.
As seen in the above screenshot, there are Home, About and Contact buttons on the navigation bar. Let’s select ‘About’ and you will see the following view.
Let’s select Contact and the following screen pops up.
Now let’s expand the ‘MVCUnitTestingDemo’ project and you will see the HomeController.cs file under the Controllers folder.
The HomeController contains three action methods as shown in the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCUnitTestingDemo.Controllers {
public class HomeController : Controller{
public ActionResult Index(){
return View();
}
public ActionResult About(){
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact(){
ViewBag.Message = "Your contact page.";
return View();
}
}
}
Let’s expand the MVCUnitTestingDemo.Tests project and you will see the HomeControllerTest.cs file under the Controllers folder.
In this HomeControllerTest class, you will see three methods as shown in the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MVCUnitTestingDemo;
using MVCUnitTestingDemo.Controllers;
namespace MVCUnitTestingDemo.Tests.Controllers{
[TestClass]
public class HomeControllerTest{
[TestMethod]
public void Index(){
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
[TestMethod]
public void About(){
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.About() as ViewResult;
// Assert
Assert.AreEqual("Your application description page.", result.ViewBag.Message);
}
[TestMethod]
public void Contact(){
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Contact() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
}
These three methods will test whether the Index, About and Contact action methods are working properly. To test these three action methods, go to the Test menu.
Select Run → All Tests to test these action methods.
Now you will see the Test Explorer on the left side in which you can see that all the tests are passed. Let us add one more action method, which will list all the employees. First we need to add an employee class in the Models folder.
Following is the Employee class implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCUnitTestingDemo.Models{
public class Employee{
public int ID { get; set; }
public string Name { get; set; }
public DateTime JoiningDate { get; set; }
public int Age { get; set; }
}
}
We need to add EmployeeController. Right-click on the controller folder in the solution explorer and select Add → Controller.
It will display the Add Scaffold dialog.
Select the MVC 5 Controller – Empty option and click ‘Add’ button and the Add Controller dialog will appear.
Set the name to EmployeeController and click ‘Add’ button.
You will see a new C# file ‘EmployeeController.cs’ in the Controllers folder which is open for editing in Visual Studio. Let’s update the EmployeeController using the following code.
using MVCUnitTestingDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCUnitTestingDemo.Controllers {
public class EmployeeController : Controller{
[NonAction]
public List<Employee> GetEmployeeList(){
return new List<Employee>{
new Employee{
ID = 1,
Name = "Allan",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 23
},
new Employee{
ID = 2,
Name = "Carson",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 45
},
new Employee{
ID = 3,
Name = "Carson",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 37
},
new Employee{
ID = 4,
Name = "Laura",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 26
},
};
}
// GET: Employee
public ActionResult Index(){
return View();
}
public ActionResult Employees(){
var employees = from e in GetEmployeeList()
orderby e.ID
select e;
return View(employees);
}
}
}
To add View for Employees action method, right-click on Employees action and select Add View...
You will see the default name for view. Select ‘List’ from the Template dropdown and ‘Employee’ from the Model class dropdown and click Ok.
Now we need to add the link Employees list, let’s open the _layout.cshtml file which is under Views/Shared folder and add the link for employees list below the Contact link.
<li>@Html.ActionLink("Employees List", "Employees", "Employee")</li>
Following is the complete implementation of _layout.cshtml.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8" />
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class = "navbar navbar-inverse navbar-fixed-top">
<div class = "container">
<div class = "navbar-header">
<button type = "button" class = "navbar-toggle" datatoggle =
"collapse" data-target = ".navbar-collapse">
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new
{ area = "" }, new { @class = "navbar-brand" })
</div>
<div class = "navbar-collapse collapse">
<ul class = "nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
<li>@Html.ActionLink("Employees List", "Employees", "Employee")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class = "container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
To test Employees action method from the Employee controller, we need to add another test method in our unit testing project. Following s the EmployeeControllerTest class in which we will test the Employees action method.
[TestClass]
public class EmployeeControllerTest{
[TestMethod]
public void Employees(){
// Arrange
EmployeeController controller = new EmployeeController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
Select Run → All Tests from the Test menu to test these action methods.
You can see that the Employees test method is also passed now. When you run the application, you will see the following output.
Click ‘Employees List’ option in the navigation bar and you will see the list of employees.
In this chapter, we will be covering how to deploy ASP.NET MVC application. After understating different concepts in ASP.NET MVC applications, now it’s time to understand the deployment process. So, whenever we are building any MVC application we are basically producing a dll file associated for the same with all the application settings and logic inside and these dlls are in the bin directory of the project as shown in the following screenshot.
Let’s take a look at a simple example in which we will deploy our example to Microsoft Azure.
Step 1 − Right-click on the project in the Solution Explorer and select Publish as shown in the following screenshot.
Step 2 − You will see the Publish Web dialog. Click on the Microsoft Azure Web Apps.
It will display the ‘Sign in’ page.
Step 3 − Enter credentials for the Microsoft Azure Subscription.
Once you’re successfully connected to your Azure account, you will see the following dialog.
Step 4 − Click ‘New’ button.
Step 5 − Enter the desired information on the above dialog such as Web App name, which must be a unique name. You will also need to enter App service plan, resource group, and then select your region.
Step 6 − Click ‘Next’ button to continue.
Step 7 − Click the ellipsis mark ‘...’ to select the connection string.
Step 8 − Select the server name and then choose the Windows Authentication option. Select the database name as well. Now you will see that the connection string is generated for you.
Step 9 − Click ‘Next’ to continue.
Step 10 − To check all the files and dlls which we will be publishing to Azure, click the Start Preview. Click ‘Publish’ button to publish your application.
Once the application is successfully published to Azure, you will see the message in the output window.
Step 11 − Now open your browser and enter the following URL ‘http://mymvcdemoapp.azurewebsites.net/employees’ and you will see the list of employees.
Step 12 − Now if you go to your Azure portal and click ‘App Services’, then you see that your application is deployed to Azure.
Step 13 − Click the name of your app and you will see the information related to that application such as URL, Status, Location, etc.
We have seen so far how to publish a web application to Azure app, after the application is created. You can also create an application, which will be deployed to Azure.
Let’s create a new ASP.NET MVC application.
Step 1 − Click Ok and you will see the following dialog.
Step 2 − Select MVC template and also check Host in the Cloud checkbox. Click Ok.
When the Configure Microsoft Azure Web App Settings dialog appears, make sure that you are signed in to Azure.
You can see the default name, but you can also change the Web App name.
Step 3 − Enter the desired information as shown in the following screenshot.
Step 4 − Select the ‘Create new server’ from the Database server dropdown and you will see the additional field.
Step 5 − Enter the Database server, username, and password. Click Ok.
Step 6 − Once the project is created, run the application and you will see that it is running on the localhost.
Step 7 − To deploy these applications to Azure, right-click on the project in the solution explorer and select ‘Publish’.
You will see the following dialog.
Step 8 − Click the ‘Microsoft Azure Web Apps’.
Step 9 − Select your application name from the Existing Web Apps and click Ok.
Step 10 − Click the ‘Validate Connection’ button to check for the connection on Azure.
Step 11 − Click ‘Next’ to continue.
Now you will see that the connection string is already generated by default.
Step 12 − Click ‘Next’ to continue.
Step 13 − To check all the files and dlls which will be published to Azure, click the ‘Start Preview’.
Step 14 − Click ‘Publish’ button to publish your application. Once the application is successfully published to Azure, you will see the message in the output window.
You will also see that the application is now running from the cloud.
Let’s go to Azure portal again. You will see the app here as well.
In this chapter, we will cover Self-Hosting. Self-Hosting creates a runtime environment for the application to run in any environment say MAC, or in Linux box, etc. Self-Hosting also means it will have a mini CLR version.
Let’s take a look at a simple example of self-hosting.
Step 1 − Once your ASP.NET MVC application is completed and you want to use selfhosting, right-click on the Project in the solution explorer.
You will see the following dialog.
Step 2 − Click the ‘Custom’ option, which will display the New Custom Profile dialog.
Step 3 − Enter the profile name and click Ok.
Step 4 − Select the File System from the Publish method dropdown list and also specify the target location. Click ‘Next’ button.
Step 5 − Expand the File Publish Options.
Step 6 − Check the ‘Delete all existing files prior to publish’ and ‘Precompile during publishing’ checkboxes and click ‘Next’ to continue.
Step 7 − Click ‘Publish’ button, it will publish the files at the desired location.
You will see all the files and folders in the target location on your system.
It will have all the files required to get deployed on the localhost.
Step 8 − Now open the Turn Windows Feature on or off and Expand Internet Information Services → World Wide Web Services → Application Development Features.
Step 9 − Check the checkboxes as shown in the above screenshot and click Ok.
Step 10 − Let’s open the IIS Manager as shown in the following screenshot.
Step 11 − You will see different connections on the left side of the screen, right-click on MyWebSite.
Step 12 − Select the ‘Convert to Application’ option.
As you can see, its physical path is the same as we have mentioned above while publishing, using the File system.
Step 13 − Click Ok to continue.
Now you can see that its icon has changed.
Step 14 − Open your browser and specify the following URL http://localhost/MyWebSite
You can see that it is running from the folder which we have specified during deployment.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2529,
"s": 2269,
"text": "ASP.NET MVC is basically a web development framework from Microsoft, which combines the features of MVC (Model-View-Controller) architecture, the most up-to-date ideas and techniques from Agile development, and the best parts of the existing ASP.NET platform."
},
{
"code": null,
"e": 2778,
"s": 2529,
"text": "ASP.NET MVC is not something, which is built from ground zero. It is a complete alternative to traditional ASP.NET Web Forms. It is built on the top of ASP.NET, so developers enjoy almost all the ASP.NET features while building the MVC application."
},
{
"code": null,
"e": 3014,
"s": 2778,
"text": "ASP.NET 1.0 was released on January 5, 2002, as part of .Net Framework version 1.0. At that time, it was easy to think of ASP.NET and Web Forms as one and the same thing. ASP.NET has however always supported two layers of abstraction −"
},
{
"code": null,
"e": 3101,
"s": 3014,
"text": "System.Web.UI − The Web Forms layer, comprising server controls, ViewState, and so on."
},
{
"code": null,
"e": 3188,
"s": 3101,
"text": "System.Web.UI − The Web Forms layer, comprising server controls, ViewState, and so on."
},
{
"code": null,
"e": 3284,
"s": 3188,
"text": "System.Web − It supplies the basic web stack, including modules, handlers, the HTTP stack, etc."
},
{
"code": null,
"e": 3380,
"s": 3284,
"text": "System.Web − It supplies the basic web stack, including modules, handlers, the HTTP stack, etc."
},
{
"code": null,
"e": 3513,
"s": 3380,
"text": "By the time ASP.NET MVC was announced in 2007, the MVC pattern was becoming one of the most popular ways of building web frameworks."
},
{
"code": null,
"e": 3748,
"s": 3513,
"text": "In April 2009, the ASP.NET MVC source code was released under the Microsoft Public License (MS-PL). \"ASP.NET MVC framework is a lightweight, highly testable presentation framework that is integrated with the existing ASP.NET features."
},
{
"code": null,
"e": 3897,
"s": 3748,
"text": "Some of these integrated features are master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly."
},
{
"code": null,
"e": 4106,
"s": 3897,
"text": "In March 2012, Microsoft had released part of its web stack (including ASP.NET MVC, Razor and Web API) under an open source license (Apache License 2.0). ASP.NET Web Forms was not included in this initiative."
},
{
"code": null,
"e": 4417,
"s": 4106,
"text": "Microsoft decided to create their own MVC framework for building web applications. The MVC framework simply builds on top of ASP.NET. When you are building a web application with ASP.NET MVC, there will be no illusions of state, there will not be such a thing as a page load and no page life cycle at all, etc."
},
{
"code": null,
"e": 4779,
"s": 4417,
"text": "Another design goal for ASP.NET MVC was to be extensible throughout all aspects of the framework. So when we talk about views, views have to be rendered by a particular type of view engine. The default view engine is still something that can take an ASPX file. But if you don't like using ASPX files, you can use something else and plug in your own view\nengine."
},
{
"code": null,
"e": 5085,
"s": 4779,
"text": "There is a component inside the MVC framework that will instantiate your controllers. You might not like the way that the MVC framework instantiates your controller, you might want to handle that job yourself. So, there are lots of places in MVC where you can inject your own custom logic to handle tasks."
},
{
"code": null,
"e": 5485,
"s": 5085,
"text": "The whole idea behind using the Model View Controller design pattern is that you maintain a separation of concerns. Your controller is no longer encumbered with a lot of ties to the ASP.NET runtime or ties to the ASPX page, which is very hard to test. You now just have a class with regular methods on it that you can invoke in unit tests to find out if that controller is going to behave correctly."
},
{
"code": null,
"e": 5535,
"s": 5485,
"text": "Following are the benefits of using ASP.NET MVC −"
},
{
"code": null,
"e": 5645,
"s": 5535,
"text": "Makes it easier to manage complexity by dividing an application into the model, the view, and the controller."
},
{
"code": null,
"e": 5755,
"s": 5645,
"text": "Makes it easier to manage complexity by dividing an application into the model, the view, and the controller."
},
{
"code": null,
"e": 5844,
"s": 5755,
"text": "Enables full control over the rendered HTML and provides a clean separation of concerns."
},
{
"code": null,
"e": 5933,
"s": 5844,
"text": "Enables full control over the rendered HTML and provides a clean separation of concerns."
},
{
"code": null,
"e": 6047,
"s": 5933,
"text": "Direct control over HTML also means better accessibility for implementing compliance with evolving Web standards."
},
{
"code": null,
"e": 6161,
"s": 6047,
"text": "Direct control over HTML also means better accessibility for implementing compliance with evolving Web standards."
},
{
"code": null,
"e": 6236,
"s": 6161,
"text": "Facilitates adding more interactivity and responsiveness to existing apps."
},
{
"code": null,
"e": 6311,
"s": 6236,
"text": "Facilitates adding more interactivity and responsiveness to existing apps."
},
{
"code": null,
"e": 6370,
"s": 6311,
"text": "Provides better support for test-driven development (TDD)."
},
{
"code": null,
"e": 6429,
"s": 6370,
"text": "Provides better support for test-driven development (TDD)."
},
{
"code": null,
"e": 6596,
"s": 6429,
"text": "Works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior."
},
{
"code": null,
"e": 6763,
"s": 6596,
"text": "Works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior."
},
{
"code": null,
"e": 7027,
"s": 6763,
"text": "The MVC (Model-View-Controller) design pattern has actually been around for a few decades, and it's been used across many different technologies. Everything from Smalltalk to C++ to Java, and now C Sharp and .NET use this design pattern to build a user interface."
},
{
"code": null,
"e": 7084,
"s": 7027,
"text": "Following are some salient features of the MVC pattern −"
},
{
"code": null,
"e": 7201,
"s": 7084,
"text": "Originally it was named Thing-Model-View-Editor in 1979, and then it was later simplified to Model- View-Controller."
},
{
"code": null,
"e": 7318,
"s": 7201,
"text": "Originally it was named Thing-Model-View-Editor in 1979, and then it was later simplified to Model- View-Controller."
},
{
"code": null,
"e": 7516,
"s": 7318,
"text": "It is a powerful and elegant means of separating concerns within an application (for example, separating data access logic from display logic) and applies itself extremely well to web applications."
},
{
"code": null,
"e": 7714,
"s": 7516,
"text": "It is a powerful and elegant means of separating concerns within an application (for example, separating data access logic from display logic) and applies itself extremely well to web applications."
},
{
"code": null,
"e": 7880,
"s": 7714,
"text": "Its explicit separation of concerns does add a small amount of extra complexity to an application’s design, but the extraordinary benefits outweigh the extra effort."
},
{
"code": null,
"e": 8046,
"s": 7880,
"text": "Its explicit separation of concerns does add a small amount of extra complexity to an application’s design, but the extraordinary benefits outweigh the extra effort."
},
{
"code": null,
"e": 8151,
"s": 8046,
"text": "The MVC architectural pattern separates the user interface (UI) of an application into three main parts."
},
{
"code": null,
"e": 8256,
"s": 8151,
"text": "The Model − A set of classes that describes the data you are working with as well as the business logic."
},
{
"code": null,
"e": 8361,
"s": 8256,
"text": "The Model − A set of classes that describes the data you are working with as well as the business logic."
},
{
"code": null,
"e": 8491,
"s": 8361,
"text": "The View − Defines how the application’s UI will be displayed. It is a pure HTML, which decides how the UI is going to look like."
},
{
"code": null,
"e": 8621,
"s": 8491,
"text": "The View − Defines how the application’s UI will be displayed. It is a pure HTML, which decides how the UI is going to look like."
},
{
"code": null,
"e": 8755,
"s": 8621,
"text": "The Controller − A set of classes that handles communication from the user, overall application flow, and application-specific logic."
},
{
"code": null,
"e": 8889,
"s": 8755,
"text": "The Controller − A set of classes that handles communication from the user, overall application flow, and application-specific logic."
},
{
"code": null,
"e": 9093,
"s": 8889,
"text": "The idea is that you'll have a component called the view, which is solely responsible for rendering this user interface whether that be HTML or whether it actually be UI widgets on a desktop application."
},
{
"code": null,
"e": 9253,
"s": 9093,
"text": "The view talks to a model, and that model contains all of the data that the view needs to display. Views generally don't have much logic inside of them at all."
},
{
"code": null,
"e": 9526,
"s": 9253,
"text": "In a web application, the view might not have any code associated with it at all. It might just have HTML and then some expressions of where to take pieces of data from the model and plug them into the correct places inside the HTML template that you've built in the view."
},
{
"code": null,
"e": 9764,
"s": 9526,
"text": "The controller that organizes is everything. When an HTTP request arrives for an MVC application, that request gets routed to a controller, and then it's up to the controller to talk to either the database, the file system, or the model."
},
{
"code": null,
"e": 10041,
"s": 9764,
"text": "MVC development tool is included with Visual Studio 2012 and onwards. It can also be installed on Visual Studio 2010 SP1/Visual Web Developer 2010 Express SP1. If you are using Visual Studio 2010, you can install MVC 4 using the Web Platform Installer http://www.microsoft.com"
},
{
"code": null,
"e": 10183,
"s": 10041,
"text": "Microsoft provides a free version of Visual Studio, which also contains SQL Server and it can be downloaded from https://www.visualstudio.com"
},
{
"code": null,
"e": 10281,
"s": 10183,
"text": "Step 1 − Once downloading is complete, run the installer. The following dialog will be displayed."
},
{
"code": null,
"e": 10361,
"s": 10281,
"text": "Step 2 − Click the ‘Install’ button and it will start the installation process."
},
{
"code": null,
"e": 10453,
"s": 10361,
"text": "Once the installation process is completed successfully, you will see the following dialog."
},
{
"code": null,
"e": 10519,
"s": 10453,
"text": "Step 3 − Close this dialog and restart your computer if required."
},
{
"code": null,
"e": 10668,
"s": 10519,
"text": "Step 4 − Open Visual Studio from the Start Menu, which will open the following dialog. It will take a while for the first time only for preparation."
},
{
"code": null,
"e": 10770,
"s": 10668,
"text": "Once all is done, you will see the main window of Visual Studio as shown in the following screenshot."
},
{
"code": null,
"e": 10815,
"s": 10770,
"text": "You are now ready to start your application."
},
{
"code": null,
"e": 11104,
"s": 10815,
"text": "In this chapter, we will look at a simple working example of ASP.NET MVC. We will be building a simple web app here. To create an ASP.NET MVC application, we will use Visual Studio 2015, which contains all of the features you need to create, test, and deploy an MVC Framework application."
},
{
"code": null,
"e": 11200,
"s": 11104,
"text": "Following are the steps to create a project using project templates available in Visual Studio."
},
{
"code": null,
"e": 11273,
"s": 11200,
"text": "Step 1 − Open the Visual Studio. Click File → New → Project menu option."
},
{
"code": null,
"e": 11301,
"s": 11273,
"text": "A new Project dialog opens."
},
{
"code": null,
"e": 11366,
"s": 11301,
"text": "Step 2 − From the left pane, select Templates → Visual C# → Web."
},
{
"code": null,
"e": 11427,
"s": 11366,
"text": "Step 3 − In the middle pane, select ASP.NET Web Application."
},
{
"code": null,
"e": 11618,
"s": 11427,
"text": "Step 4 − Enter the project name, MVCFirstApp, in the Name field and click ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project."
},
{
"code": null,
"e": 11761,
"s": 11618,
"text": "Step 5 − To keep things simple, select the ‘Empty’ option and check the MVC checkbox in the Add folders and core references section. Click Ok."
},
{
"code": null,
"e": 11829,
"s": 11761,
"text": "It will create a basic MVC project with minimal predefined content."
},
{
"code": null,
"e": 11961,
"s": 11829,
"text": "Once the project is created by Visual Studio, you will see a number of files and folders displayed in the Solution Explorer window."
},
{
"code": null,
"e": 12114,
"s": 11961,
"text": "As you know that we have created ASP.Net MVC project from an empty project template, so for the moment the application does not contain anything to run."
},
{
"code": null,
"e": 12225,
"s": 12114,
"text": "Step 6 − Run this application from Debug → Start Debugging menu option and you will see a 404 Not Found Error."
},
{
"code": null,
"e": 12341,
"s": 12225,
"text": "The default browser is, Internet Explorer, but you can select any browser that you have installed from the toolbar."
},
{
"code": null,
"e": 12446,
"s": 12341,
"text": "To remove the 404 Not Found error, we need to add a controller, which handles all the incoming requests."
},
{
"code": null,
"e": 12567,
"s": 12446,
"text": "Step 1 − To add a controller, right-click on the controller folder in the solution explorer and select Add → Controller."
},
{
"code": null,
"e": 12608,
"s": 12567,
"text": "It will display the Add Scaffold dialog."
},
{
"code": null,
"e": 12684,
"s": 12608,
"text": "Step 2 − Select the MVC 5 Controller – Empty option and click ‘Add’ button."
},
{
"code": null,
"e": 12723,
"s": 12684,
"text": "The Add Controller dialog will appear."
},
{
"code": null,
"e": 12789,
"s": 12723,
"text": "Step 3 − Set the name to HomeController and click the Add button."
},
{
"code": null,
"e": 12913,
"s": 12789,
"text": "You will see a new C# file HomeController.cs in the Controllers folder, which is open for editing in Visual Studio as well."
},
{
"code": null,
"e": 13057,
"s": 12913,
"text": "Step 4 − To make this a working example, let’s modify the controller class by changing the action method called Index using the following code."
},
{
"code": null,
"e": 13372,
"s": 13057,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCFirstApp.Controllers {\n public class HomeController : Controller {\n // GET: Home\n public string Index(){\n return \"Hello World, this is ASP.Net MVC Tutorials\";\n }\n }\n}"
},
{
"code": null,
"e": 13489,
"s": 13372,
"text": "Step 5 − Run this application and you will see that the browser is displaying the result of the Index action method."
},
{
"code": null,
"e": 13868,
"s": 13489,
"text": "In this chapter, we will discuss the overall MVC pipeline and the life of an HTTP request as it travels through the MVC framework in ASP.NET. At a high level, a life cycle is simply a series of steps or events used to handle some type of request or to change an application state. You may already be familiar with various framework life cycles, the concept is not unique to MVC."
},
{
"code": null,
"e": 14233,
"s": 13868,
"text": "For example, the ASP.NET webforms platform features a complex page life cycle. Other .NET platforms, like Windows phone apps, have their own application life cycles. One thing that is true for all these platforms regardless of the technology is that understanding the processing pipeline can help you better leverage the features available and MVC is no different."
},
{
"code": null,
"e": 14259,
"s": 14233,
"text": "MVC has two life cycles −"
},
{
"code": null,
"e": 14286,
"s": 14259,
"text": "The application life cycle"
},
{
"code": null,
"e": 14309,
"s": 14286,
"text": "The request life cycle"
},
{
"code": null,
"e": 14537,
"s": 14309,
"text": "The application life cycle refers to the time at which the application process actually begins running IIS until the time it stops. This is marked by the application start and end events in the startup file of your application."
},
{
"code": null,
"e": 14636,
"s": 14537,
"text": "It is the sequence of events that happen every time an HTTP request is handled by our application."
},
{
"code": null,
"e": 14822,
"s": 14636,
"text": "The entry point for every MVC application begins with routing. After the ASP.NET platform has received a request, it figures out how it should be handled through the URL Routing Module."
},
{
"code": null,
"e": 15028,
"s": 14822,
"text": "Modules are .NET components that can hook into the application life cycle and add functionality. The routing module is responsible for matching the incoming URL to routes that we define in our application."
},
{
"code": null,
"e": 15132,
"s": 15028,
"text": "All routes have an associated route handler with them and this is the entry point to the MVC framework."
},
{
"code": null,
"e": 15428,
"s": 15132,
"text": "The MVC framework handles converting the route data into a concrete controller that can handle requests. After the controller has been created, the next major step is Action Execution. A component called the action invoker finds and selects an appropriate Action method to invoke the controller."
},
{
"code": null,
"e": 15701,
"s": 15428,
"text": "After our action result has been prepared, the next stage triggers, which is Result Execution. MVC separates declaring the result from executing the result. If the result is a view type, the View Engine will be called and it's responsible for finding and rending our view."
},
{
"code": null,
"e": 15862,
"s": 15701,
"text": "If the result is not a view, the action result will execute on its own. This Result Execution is what generates an actual response to the original HTTP request."
},
{
"code": null,
"e": 16162,
"s": 15862,
"text": "Routing is the process of directing an HTTP request to a controller and the functionality of this processing is implemented in System.Web.Routing. This assembly is not part of ASP.NET MVC. It is actually part of the ASP.NET runtime, and it was officially released with the ASP.NET as a .NET 3.5 SP1."
},
{
"code": null,
"e": 16437,
"s": 16162,
"text": "System.Web.Routing is used by the MVC framework, but it's also used by ASP.NET Dynamic Data. The MVC framework leverages routing to direct a request to a controller. The Global.asax file is that part of your application, where you will define the route for your application."
},
{
"code": null,
"e": 16561,
"s": 16437,
"text": "This is the code from the application start event in Global.asax from the MVC App which we created in the previous chapter."
},
{
"code": null,
"e": 16941,
"s": 16561,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\n\nnamespace MVCFirstApp {\n public class MvcApplication : System.Web.HttpApplication {\n protected void Application_Start(){\n AreaRegistration.RegisterAllAreas();\n RouteConfig.RegisterRoutes(RouteTable.Routes);\n }\n }\n}"
},
{
"code": null,
"e": 17037,
"s": 16941,
"text": "Following is the implementation of RouteConfig class, which contains one method RegisterRoutes."
},
{
"code": null,
"e": 17563,
"s": 17037,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\n\nnamespace MVCFirstApp {\n public class RouteConfig {\n public static void RegisterRoutes(RouteCollection routes){\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n routes.MapRoute(\n name: \"Default\",\n url: \"{controller}/{action}/{id}\",\n defaults: new{ controller = \"Home\", action = \"Index\", id = UrlParameter.Optional});\n }\n }\n}"
},
{
"code": null,
"e": 17789,
"s": 17563,
"text": "You will define the routes and those routes will map URLs to a specific controller action. An action is just a method on the controller. It can also pick parameters out of that URL and pass them as parameters into the method."
},
{
"code": null,
"e": 18083,
"s": 17789,
"text": "So this route that is defined in the application is the default route. As seen in the above code, when you see a URL arrive in the form of (something)/(something)/(something), then the first piece is the controller name, second piece is the action name, and the third piece is an ID parameter."
},
{
"code": null,
"e": 18187,
"s": 18083,
"text": "MVC applications use the ASP.NET routing system, which decides how URLs map to controllers and actions."
},
{
"code": null,
"e": 18548,
"s": 18187,
"text": "When Visual Studio creates the MVC project, it adds some default routes to get us started. When you run your application, you will see that Visual Studio has directed the browser to port 63664. You will almost certainly see a different port number in the URL that your browser requests because Visual Studio allocates a random port when the project is created."
},
{
"code": null,
"e": 18721,
"s": 18548,
"text": "In the last example, we have added a HomeController, so you can also request any of the following URLs, and they will be directed to the Index action on the HomeController."
},
{
"code": null,
"e": 18750,
"s": 18721,
"text": "http://localhost:63664/Home/"
},
{
"code": null,
"e": 18784,
"s": 18750,
"text": "http://localhost:63664/Home/Index"
},
{
"code": null,
"e": 18906,
"s": 18784,
"text": "When a browser requests http://mysite/ or http://mysite/Home, it gets back the output from HomeController’s Index method."
},
{
"code": null,
"e": 19056,
"s": 18906,
"text": "You can try this as well by changing the URL in the browser. In this example, it is http://localhost:63664/, except that the port might be different."
},
{
"code": null,
"e": 19183,
"s": 19056,
"text": "If you append /Home or /Home/Index to the URL and press ‘Enter’ button, you will see the same result from the MVC application."
},
{
"code": null,
"e": 19354,
"s": 19183,
"text": "As you can see in this case, the convention is that we have a controller called HomeController and this HomeController will be the starting point for our MVC application."
},
{
"code": null,
"e": 19552,
"s": 19354,
"text": "The default routes that Visual Studio creates for a new project assumes that you will follow this convention. But if you want to follow your own convention then you would need to modify the routes."
},
{
"code": null,
"e": 19778,
"s": 19552,
"text": "You can certainly add your own routes. If you don't like these action names, if you have different ID parameters or if you just in general have a different URL structure for your site, then you can add your own route entries."
},
{
"code": null,
"e": 19939,
"s": 19778,
"text": "Let’s take a look at a simple example. Consider we have a page that contains the list of processes. Following is the code, which will route to the process page."
},
{
"code": null,
"e": 20095,
"s": 19939,
"text": "routes.MapRoute(\n \"Process\",\n \"Process/{action}/{id}\",\n defaults: new{\n controller = \"Process\", action = \"List \", id = UrlParameter.Optional}\n);"
},
{
"code": null,
"e": 20310,
"s": 20095,
"text": "When someone comes in and looks for a URL with Process/Action/Id, they will go to the Process Controller. We can make the action a little bit different, the default action, we can make that a List instead of Index."
},
{
"code": null,
"e": 20490,
"s": 20310,
"text": "Now a request that arrives looks like localhosts/process. The routing engine will use this routing configuration to pass that along, so it's going to use a default action of List."
},
{
"code": null,
"e": 20538,
"s": 20490,
"text": "Following is the complete class implementation."
},
{
"code": null,
"e": 21294,
"s": 20538,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\n\nnamespace MVCFirstApp{\n public class RouteConfig{\n public static void RegisterRoutes(RouteCollection routes){\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n\t\t\t\n routes.MapRoute(\n \"Process\", \"Process/{action}/{id}\",\n defaults: new{\n controller = \" Process\", action = \"List \", id =\n UrlParameter.Optional});\n\t\t\t\t\t\n routes.MapRoute(\n name: \"Default\", url: \"{controller}/{action}/{id}\",\n defaults: new{\n controller = \"Home\", action = \"Index\", id =\n UrlParameter.Optional});\n }\n }\n}"
},
{
"code": null,
"e": 21397,
"s": 21294,
"text": "Step 1 − Run this and request for a process page with the following URL http://localhost:63664/Process"
},
{
"code": null,
"e": 21508,
"s": 21397,
"text": "You will see an HTTP 404, because the routing engine is looking for ProcessController, which is not available."
},
{
"code": null,
"e": 21636,
"s": 21508,
"text": "Step 2 − Create ProcessController by right-clicking on Controllers folder in the solution explorer and select Add → Controller."
},
{
"code": null,
"e": 21677,
"s": 21636,
"text": "It will display the Add Scaffold dialog."
},
{
"code": null,
"e": 21753,
"s": 21677,
"text": "Step 3 − Select the MVC 5 Controller – Empty option and click ‘Add’ button."
},
{
"code": null,
"e": 21792,
"s": 21753,
"text": "The Add Controller dialog will appear."
},
{
"code": null,
"e": 21859,
"s": 21792,
"text": "Step 4 − Set the name to ProcessController and click ‘Add’ button."
},
{
"code": null,
"e": 21990,
"s": 21859,
"text": "Now you will see a new C# file ProcessController.cs in the Controllers folder, which is open for editing in Visual Studio as well."
},
{
"code": null,
"e": 22090,
"s": 21990,
"text": "Now our default action is going to be List, so we want to have a List action here instead of Index."
},
{
"code": null,
"e": 22228,
"s": 22090,
"text": "Step 5 − Change the return type from ActionResult to string and also return some string from this action method using the following code."
},
{
"code": null,
"e": 22525,
"s": 22228,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCFirstApp.Controllers{\n public class ProcessController : Controller{\n // GET: Process\n public string List(){\n return \"This is Process page\";\n }\n }\n}"
},
{
"code": null,
"e": 22749,
"s": 22525,
"text": "Step 6 − When you run this application, again you will see the result from the default route. When you specify the following URL, http://localhost:63664/Process/List, then you will see the result from the ProcessController."
},
{
"code": null,
"e": 23192,
"s": 22749,
"text": "Controllers are essentially the central unit of your ASP.NET MVC application. It is the 1st recipient, which interacts with incoming HTTP Request. So, the controller decides which model will be selected, and then it takes the data from the model and passes the same to the respective view, after that view is rendered. Actually, controllers are controlling the overall flow of the application taking the input and rendering the proper output."
},
{
"code": null,
"e": 23445,
"s": 23192,
"text": "Controllers are C# classes inheriting from System.Web.Mvc.Controller, which is the builtin controller base class. Each public method in a controller is known as an action method, meaning you can invoke it from the Web via some URL to perform an action."
},
{
"code": null,
"e": 23568,
"s": 23445,
"text": "The MVC convention is to put controllers in the Controllers folder that Visual Studio created when the project was set up."
},
{
"code": null,
"e": 23659,
"s": 23568,
"text": "Let’s take a look at a simple example of Controller by creating a new ASP.Net MVC project."
},
{
"code": null,
"e": 23738,
"s": 23659,
"text": "Step 1 − Open the Visual Studio and click on File → New → Project menu option."
},
{
"code": null,
"e": 23766,
"s": 23738,
"text": "A new Project dialog opens."
},
{
"code": null,
"e": 23831,
"s": 23766,
"text": "Step 2 − From the left pane, select Templates → Visual C# → Web."
},
{
"code": null,
"e": 23892,
"s": 23831,
"text": "Step 3 − In the middle pane, select ASP.NET Web Application."
},
{
"code": null,
"e": 24090,
"s": 23892,
"text": "Step 4 − Enter the project name ‘MVCControllerDemo’ in the Name field and click ok to continue. You will see the following dialog, which asks you to set the initial content for the ASP.NET project."
},
{
"code": null,
"e": 24240,
"s": 24090,
"text": "Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok."
},
{
"code": null,
"e": 24308,
"s": 24240,
"text": "It will create a basic MVC project with minimal predefined content."
},
{
"code": null,
"e": 24439,
"s": 24308,
"text": "Once the project is created by Visual Studio you will see a number of files and folders displayed in the Solution Explorer window."
},
{
"code": null,
"e": 24581,
"s": 24439,
"text": "Since we have created ASP.Net MVC project from an empty project template, so at the moment, the application does not contain anything to run."
},
{
"code": null,
"e": 24704,
"s": 24581,
"text": "Step 6 − Add EmployeeController by right-clicking on Controllers folder in the solution explorer. Select Add → Controller."
},
{
"code": null,
"e": 24745,
"s": 24704,
"text": "It will display the Add Scaffold dialog."
},
{
"code": null,
"e": 24821,
"s": 24745,
"text": "Step 7 − Select the MVC 5 Controller – Empty option and click ‘Add’ button."
},
{
"code": null,
"e": 24860,
"s": 24821,
"text": "The Add Controller dialog will appear."
},
{
"code": null,
"e": 24928,
"s": 24860,
"text": "Step 8 − Set the name to EmployeeController and click ‘Add’ button."
},
{
"code": null,
"e": 25056,
"s": 24928,
"text": "You will see a new C# file EmployeeController.cs in the Controllers folder, which is open for editing in Visual Studio as well."
},
{
"code": null,
"e": 25156,
"s": 25056,
"text": "Now, in this application we will add a custom route for Employee controller with the default Route."
},
{
"code": null,
"e": 25247,
"s": 25156,
"text": "Step 1 − Go to “RouteConfig.cs” file under “App_Start” folder and add the following route."
},
{
"code": null,
"e": 25392,
"s": 25247,
"text": "routes.MapRoute(\n \"Employee\", \"Employee/{name}\", new{\n controller = \"Employee\", action = \"Search\", name =\n UrlParameter.Optional });"
},
{
"code": null,
"e": 25457,
"s": 25392,
"text": "Following is the complete implementation of RouteConfig.cs file."
},
{
"code": null,
"e": 26157,
"s": 25457,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\n\nnamespace MVCControllerDemo {\n public class RouteConfig {\n public static void RegisterRoutes(RouteCollection routes){\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n\t\t\t\n routes.MapRoute(\n \"Employee\", \"Employee/{name}\", new{\n controller = \"Employee\", action = \"Search\", name = UrlParameter.Optional });\n\t\t\t\t\t\n routes.MapRoute(\n name: \"Default\", url: \"{controller}/{action}/{id}\", defaults: new{\n controller = \"Home\", action = \"Index\", id = UrlParameter.Optional });\n }\n }\n}"
},
{
"code": null,
"e": 26417,
"s": 26157,
"text": "Consider a scenario wherein any user comes and searches for an employee, specifying the URL “Employee/Mark”. In this case, Mark will be treated as a parameter name not like Action method. So in this kind of scenario our default route won’t work significantly."
},
{
"code": null,
"e": 26616,
"s": 26417,
"text": "To fetch the incoming value from the browser when the parameter is getting passed, MVC framework provides a simple way to address this problem. It is by using the parameter inside the Action method."
},
{
"code": null,
"e": 26687,
"s": 26616,
"text": "Step 2 − Change the EmployeeController class using the following code."
},
{
"code": null,
"e": 27052,
"s": 26687,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCControllerDemo.Controllers {\n public class EmployeeController : Controller {\n // GET: Employee\n public ActionResult Search(string name){\n var input = Server.HtmlEncode(name);\n return Content(input);\n }\n }\n}"
},
{
"code": null,
"e": 27305,
"s": 27052,
"text": "If you add a parameter to an action method, then the MVC framework will look for the value that matches the parameter name. It will apply all the possible combination to find out the parameter value. It will search in the Route data, query string, etc."
},
{
"code": null,
"e": 27508,
"s": 27305,
"text": "Hence, if you request for /Employee/Mark”, then the MVC framework will decide that I need a parameter with “UserInput”, and then Mark will get picked from the URL and that will get automatically passed."
},
{
"code": null,
"e": 27739,
"s": 27508,
"text": "Server.HtmlEncode will simply convert any kind of malicious script in plain text. When the above code is compiled and executed and requests the following URL http://localhost:61465/Employee/Mark, you will get the following output."
},
{
"code": null,
"e": 27808,
"s": 27739,
"text": "As you can see in the above screenshot, Mark is picked from the URL."
},
{
"code": null,
"e": 28034,
"s": 27808,
"text": "ASP.NET MVC Action Methods are responsible to execute requests and generate responses to it. By default, it generates a response in the form of ActionResult. Actions typically have a one-to-one mapping with user interactions."
},
{
"code": null,
"e": 28520,
"s": 28034,
"text": "For example, enter a URL into the browser, click on any particular link, and submit a form, etc. Each of these user interactions causes a request to be sent to the server. In each case, the URL of the request includes information that the MVC framework uses to invoke an action method. The one restriction on action method is that they have to be instance method, so they cannot be static methods. Also there is no return value restrictions. So you can return the string, integer, etc."
},
{
"code": null,
"e": 28671,
"s": 28520,
"text": "Actions are the ultimate request destination in an MVC application and it uses the controller base class. Let's take a look at the request processing."
},
{
"code": null,
"e": 28847,
"s": 28671,
"text": "When a URL arrives, like /Home/index, it is the UrlRoutingModule that inspects and understands that something configured within the routing table knows how to handle that URL."
},
{
"code": null,
"e": 29023,
"s": 28847,
"text": "When a URL arrives, like /Home/index, it is the UrlRoutingModule that inspects and understands that something configured within the routing table knows how to handle that URL."
},
{
"code": null,
"e": 29161,
"s": 29023,
"text": "The UrlRoutingModule puts together the information we've configured in the routing table and hands over control to the MVC route handler."
},
{
"code": null,
"e": 29299,
"s": 29161,
"text": "The UrlRoutingModule puts together the information we've configured in the routing table and hands over control to the MVC route handler."
},
{
"code": null,
"e": 29392,
"s": 29299,
"text": "The MVC route handler passes the controller over to the MvcHandler which is an HTTP handler."
},
{
"code": null,
"e": 29485,
"s": 29392,
"text": "The MVC route handler passes the controller over to the MvcHandler which is an HTTP handler."
},
{
"code": null,
"e": 29657,
"s": 29485,
"text": "MvcHandler uses a controller factory to instantiate the controller and it knows what controller to instantiate because it looks in the RouteData for that controller value."
},
{
"code": null,
"e": 29829,
"s": 29657,
"text": "MvcHandler uses a controller factory to instantiate the controller and it knows what controller to instantiate because it looks in the RouteData for that controller value."
},
{
"code": null,
"e": 29982,
"s": 29829,
"text": "Once the MvcHandler has a controller, the only thing that MvcHandler knows about is IController Interface, so it simply tells the controller to execute."
},
{
"code": null,
"e": 30135,
"s": 29982,
"text": "Once the MvcHandler has a controller, the only thing that MvcHandler knows about is IController Interface, so it simply tells the controller to execute."
},
{
"code": null,
"e": 30370,
"s": 30135,
"text": "When it tells the controller to execute, that's been derived from the MVC's controller base class. The Execute method creates an action invoker and tells that action invoker to go and find a method to invoke, find an action to invoke."
},
{
"code": null,
"e": 30605,
"s": 30370,
"text": "When it tells the controller to execute, that's been derived from the MVC's controller base class. The Execute method creates an action invoker and tells that action invoker to go and find a method to invoke, find an action to invoke."
},
{
"code": null,
"e": 30737,
"s": 30605,
"text": "The action invoker, again, looks in the RouteData and finds that action parameter that's been passed along from the routing engine."
},
{
"code": null,
"e": 30869,
"s": 30737,
"text": "The action invoker, again, looks in the RouteData and finds that action parameter that's been passed along from the routing engine."
},
{
"code": null,
"e": 31064,
"s": 30869,
"text": "Actions basically return different types of action results. The ActionResult class is the base for all action results. Following is the list of different kind of action results and its behavior."
},
{
"code": null,
"e": 31078,
"s": 31064,
"text": "ContentResult"
},
{
"code": null,
"e": 31095,
"s": 31078,
"text": "Returns a string"
},
{
"code": null,
"e": 31113,
"s": 31095,
"text": "FileContentResult"
},
{
"code": null,
"e": 31134,
"s": 31113,
"text": "Returns file content"
},
{
"code": null,
"e": 31149,
"s": 31134,
"text": "FilePathResult"
},
{
"code": null,
"e": 31170,
"s": 31149,
"text": "Returns file content"
},
{
"code": null,
"e": 31187,
"s": 31170,
"text": "FileStreamResult"
},
{
"code": null,
"e": 31208,
"s": 31187,
"text": "Returns file content"
},
{
"code": null,
"e": 31220,
"s": 31208,
"text": "EmptyResult"
},
{
"code": null,
"e": 31236,
"s": 31220,
"text": "Returns nothing"
},
{
"code": null,
"e": 31253,
"s": 31236,
"text": "JavaScriptResult"
},
{
"code": null,
"e": 31282,
"s": 31253,
"text": "Returns script for execution"
},
{
"code": null,
"e": 31293,
"s": 31282,
"text": "JsonResult"
},
{
"code": null,
"e": 31321,
"s": 31293,
"text": "Returns JSON formatted data"
},
{
"code": null,
"e": 31338,
"s": 31321,
"text": "RedirectToResult"
},
{
"code": null,
"e": 31369,
"s": 31338,
"text": "Redirects to the specified URL"
},
{
"code": null,
"e": 31392,
"s": 31369,
"text": "HttpUnauthorizedResult"
},
{
"code": null,
"e": 31421,
"s": 31392,
"text": "Returns 403 HTTP Status code"
},
{
"code": null,
"e": 31443,
"s": 31421,
"text": "RedirectToRouteResult"
},
{
"code": null,
"e": 31501,
"s": 31443,
"text": "Redirects to different action/different controller action"
},
{
"code": null,
"e": 31512,
"s": 31501,
"text": "ViewResult"
},
{
"code": null,
"e": 31551,
"s": 31512,
"text": "Received as a response for view engine"
},
{
"code": null,
"e": 31569,
"s": 31551,
"text": "PartialViewResult"
},
{
"code": null,
"e": 31608,
"s": 31569,
"text": "Received as a response for view engine"
},
{
"code": null,
"e": 31720,
"s": 31608,
"text": "Let’s have a look at a simple example from the previous chapter in which we have created an EmployeeController."
},
{
"code": null,
"e": 32083,
"s": 31720,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCControllerDemo.Controllers {\n public class EmployeeController : Controller{\n // GET: Employee\n public ActionResult Search(string name){\n var input = Server.HtmlEncode(name);\n return Content(input);\n }\n }\n}"
},
{
"code": null,
"e": 32213,
"s": 32083,
"text": "When you request the following URL http://localhost:61465/Employee/Mark, then you will receive the following output as an action."
},
{
"code": null,
"e": 32248,
"s": 32213,
"text": "Let us add one another controller."
},
{
"code": null,
"e": 32320,
"s": 32248,
"text": "Step 1 − Right-click on Controllers folder and select Add → Controller."
},
{
"code": null,
"e": 32361,
"s": 32320,
"text": "It will display the Add Scaffold dialog."
},
{
"code": null,
"e": 32437,
"s": 32361,
"text": "Step 2 − Select the MVC 5 Controller – Empty option and click ‘Add’ button."
},
{
"code": null,
"e": 32476,
"s": 32437,
"text": "The Add Controller dialog will appear."
},
{
"code": null,
"e": 32544,
"s": 32476,
"text": "Step 3 − Set the name to CustomerController and click ‘Add’ button."
},
{
"code": null,
"e": 32678,
"s": 32544,
"text": "Now you will see a new C# file ‘CustomerController.cs’ in the Controllers folder, which is open for editing in Visual Studio as well."
},
{
"code": null,
"e": 32796,
"s": 32678,
"text": "Similarly, add one more controller with name HomeController. Following is the HomeController.cs class implementation."
},
{
"code": null,
"e": 33098,
"s": 32796,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCControllerDemo.Controllers {\n public class HomeController : Controller{\n // GET: Home\n public string Index(){\n return \"This is Home Controller\";\n }\n }\n}"
},
{
"code": null,
"e": 33171,
"s": 33098,
"text": "Step 4 − Run this application and you will receive the following output."
},
{
"code": null,
"e": 33256,
"s": 33171,
"text": "Step 5 − Add the following code in Customer controller, which we have created above."
},
{
"code": null,
"e": 33424,
"s": 33256,
"text": "public string GetAllCustomers(){\n return @\"<ul>\n <li>Ali Raza</li>\n <li>Mark Upston</li>\n <li>Allan Bommer</li>\n <li>Greg Jerry</li>\n </ul>\";\n}"
},
{
"code": null,
"e": 33554,
"s": 33424,
"text": "Step 6 − Run this application and request for http://localhost:61465/Customer/GetAllCustomers. You will see the following output."
},
{
"code": null,
"e": 33647,
"s": 33554,
"text": "You can also redirect to actions for the same controller or even for a different controller."
},
{
"code": null,
"e": 33811,
"s": 33647,
"text": "Following is a simple example in which we will redirect from HomeController to Customer Controller by changing the code in HomeController using the following code."
},
{
"code": null,
"e": 34139,
"s": 33811,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCControllerDemo.Controllers{\n public class HomeController : Controller{\n // GET: Home\n public ActionResult Index(){\n return RedirectToAction(\"GetAllCustomers\",\"Customer\");\n }\n }\n}"
},
{
"code": null,
"e": 34273,
"s": 34139,
"text": "As you can see, we have used the RedirectToAction() method ActionResult, which takes two parameters, action name and controller name."
},
{
"code": null,
"e": 34381,
"s": 34273,
"text": "When you run this application, you will see the default route will redirect it to /Customer/GetAllCustomers"
},
{
"code": null,
"e": 34621,
"s": 34381,
"text": "In ASP.NET MVC, controllers define action methods that usually have a one-to-one relationship with possible user interactions, but sometimes you want to perform logic either before an action method is called or after an action method runs."
},
{
"code": null,
"e": 34823,
"s": 34621,
"text": "To support this, ASP.NET MVC provides filters. Filters are custom classes that provide both a declarative and programmatic means to add pre-action and post-action behavior to controller action methods."
},
{
"code": null,
"e": 35037,
"s": 34823,
"text": "An action filter is an attribute that you can apply to a controller action or an entire controller that modifies the way in which the action is executed. The ASP.NET MVC framework includes several action filters −"
},
{
"code": null,
"e": 35124,
"s": 35037,
"text": "OutputCache − Caches the output of a controller action for a specified amount of\ntime."
},
{
"code": null,
"e": 35211,
"s": 35124,
"text": "OutputCache − Caches the output of a controller action for a specified amount of\ntime."
},
{
"code": null,
"e": 35285,
"s": 35211,
"text": "HandleError − Handles errors raised when a controller action is executed."
},
{
"code": null,
"e": 35359,
"s": 35285,
"text": "HandleError − Handles errors raised when a controller action is executed."
},
{
"code": null,
"e": 35432,
"s": 35359,
"text": "Authorize − Enables you to restrict access to a particular user or role."
},
{
"code": null,
"e": 35505,
"s": 35432,
"text": "Authorize − Enables you to restrict access to a particular user or role."
},
{
"code": null,
"e": 35574,
"s": 35505,
"text": "The ASP.NET MVC framework supports four different types of filters −"
},
{
"code": null,
"e": 35645,
"s": 35574,
"text": "Authorization Filters − Implements the IAuthorizationFilter attribute."
},
{
"code": null,
"e": 35716,
"s": 35645,
"text": "Authorization Filters − Implements the IAuthorizationFilter attribute."
},
{
"code": null,
"e": 35773,
"s": 35716,
"text": "Action Filters − Implements the IActionFilter attribute."
},
{
"code": null,
"e": 35830,
"s": 35773,
"text": "Action Filters − Implements the IActionFilter attribute."
},
{
"code": null,
"e": 35887,
"s": 35830,
"text": "Result Filters − Implements the IResultFilter attribute."
},
{
"code": null,
"e": 35944,
"s": 35887,
"text": "Result Filters − Implements the IResultFilter attribute."
},
{
"code": null,
"e": 36007,
"s": 35944,
"text": "Exception Filters − Implements the IExceptionFilter attribute."
},
{
"code": null,
"e": 36070,
"s": 36007,
"text": "Exception Filters − Implements the IExceptionFilter attribute."
},
{
"code": null,
"e": 36271,
"s": 36070,
"text": "Filters are executed in the order listed above. For example, authorization filters are always executed before action filters and exception filters are always executed after every other type of filter."
},
{
"code": null,
"e": 36448,
"s": 36271,
"text": "Authorization filters are used to implement authentication and authorization for controller actions. For example, the Authorize filter is an example of an Authorization filter."
},
{
"code": null,
"e": 36525,
"s": 36448,
"text": "Let’s take a look at a simple example by creating a new ASP.Net MVC project."
},
{
"code": null,
"e": 36601,
"s": 36525,
"text": "Step 1 − Open the Visual Studio and click File → New → Project menu option."
},
{
"code": null,
"e": 36629,
"s": 36601,
"text": "A new Project dialog opens."
},
{
"code": null,
"e": 36694,
"s": 36629,
"text": "Step 2 − From the left pane, select Templates → Visual C# → Web."
},
{
"code": null,
"e": 36755,
"s": 36694,
"text": "Step 3 − In the middle pane, select ASP.NET Web Application."
},
{
"code": null,
"e": 36946,
"s": 36755,
"text": "Step 4 − Enter project name MVCFiltersDemo in the Name field and click ok to continue and you will see the following dialog which asks you to set the initial content for the ASP.NET project."
},
{
"code": null,
"e": 37096,
"s": 36946,
"text": "Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok."
},
{
"code": null,
"e": 37164,
"s": 37096,
"text": "It will create a basic MVC project with minimal predefined content."
},
{
"code": null,
"e": 37285,
"s": 37164,
"text": "Step 6 − To add a controller, right-click on the controller folder in the solution explorer and select Add → Controller."
},
{
"code": null,
"e": 37326,
"s": 37285,
"text": "It will display the Add Scaffold dialog."
},
{
"code": null,
"e": 37402,
"s": 37326,
"text": "Step 7 − Select the MVC 5 Controller – Empty option and click ‘Add’ button."
},
{
"code": null,
"e": 37441,
"s": 37402,
"text": "The Add Controller dialog will appear."
},
{
"code": null,
"e": 37505,
"s": 37441,
"text": "Step 8 − Set the name to HomeController and click ‘Add’ button."
},
{
"code": null,
"e": 37631,
"s": 37505,
"text": "You will see a new C# file ‘HomeController.cs’ in the Controllers folder, which is open for editing in Visual Studio as well."
},
{
"code": null,
"e": 37916,
"s": 37631,
"text": "An action filter can be applied to either an individual controller action or an entire controller. For example, an action filter OutputCache is applied to an action named Index() that returns the string. This filter causes the value returned by the action to be cached for 15 seconds."
},
{
"code": null,
"e": 38051,
"s": 37916,
"text": "To make this a working example, let’s modify the controller class by changing the action method called Index using the following code."
},
{
"code": null,
"e": 38401,
"s": 38051,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCFiltersDemo.Controllers {\n public class HomeController : Controller{\n // GET: Home\n [OutputCache(Duration = 15)]\n\t\t\n public string Index(){\n return \"This is ASP.Net MVC Filters Tutorial\";\n }\n }\n}"
},
{
"code": null,
"e": 38515,
"s": 38401,
"text": "When you run this application, you will see that the browser is displaying the result of the Index action method."
},
{
"code": null,
"e": 38585,
"s": 38515,
"text": "Let’s add another action method, which will display the current time."
},
{
"code": null,
"e": 38953,
"s": 38585,
"text": "namespace MVCFiltersDemo.Controllers{\n public class HomeController : Controller{\n // GET: Home\n\t\t\n [OutputCache(Duration = 15)]\n public string Index(){\n return \"This is ASP.Net MVC Filters Tutorial\";\n }\n\t\t\n [OutputCache(Duration = 20)]\n public string GetCurrentTime(){\n return DateTime.Now.ToString(\"T\");\n }\n }\n}"
},
{
"code": null,
"e": 39071,
"s": 38953,
"text": "Request for the following URL, http://localhost:62833/Home/GetCurrentTime, and you will receive the following output."
},
{
"code": null,
"e": 39228,
"s": 39071,
"text": "If you refresh the browser, you will see the same time because the action is cached for 20 seconds. It will be updated when you refresh it after 20 seconds."
},
{
"code": null,
"e": 39461,
"s": 39228,
"text": "To create your own custom filter, ASP.NET MVC framework provides a base class which is known as ActionFilterAttribute. This class implements both IActionFilter and IResultFilter interfaces and both are derived from the Filter class."
},
{
"code": null,
"e": 39661,
"s": 39461,
"text": "Let’s take a look at a simple example of custom filter by creating a new folder in your project with ActionFilters. Add one class for which right-click on ActionFilters folder and select Add → Class."
},
{
"code": null,
"e": 39729,
"s": 39661,
"text": "Enter ‘MyLogActionFilter’ in the name field and click ‘Add’ button."
},
{
"code": null,
"e": 39909,
"s": 39729,
"text": "This class will be derived from the ActionFilterAttribute, which is a base class and overrides the following method. Following is the complete implementation of MyLogActionFilter."
},
{
"code": null,
"e": 41168,
"s": 39909,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\n\nnamespace MVCFiltersDemo.ActionFilters {\n public class MyLogActionFilter : ActionFilterAttribute{\n public override void OnActionExecuting(ActionExecutingContext filterContext){\n Log(\"OnActionExecuting\", filterContext.RouteData);\n }\n\t\t\n public override void OnActionExecuted(ActionExecutedContext filterContext){\n Log(\"OnActionExecuted\", filterContext.RouteData);\n }\n\t\t\n public override void OnResultExecuting(ResultExecutingContext filterContext){\n Log(\"OnResultExecuting\", filterContext.RouteData);\n }\n\t\t\n public override void OnResultExecuted(ResultExecutedContext filterContext){\n Log(\"OnResultExecuted\", filterContext.RouteData);\n }\n\t\t\n private void Log(string methodName, RouteData routeData){\n var controllerName = routeData.Values[\"controller\"];\n var actionName = routeData.Values[\"action\"];\n\t\t\t\n var message = String.Format(\n \"{0} controller:{1} action:{2}\", methodName, controllerName, actionName);\n\t\t\t\t\n Debug.WriteLine(message, \"Action Filter Log\");\n }\n }\n}"
},
{
"code": null,
"e": 41248,
"s": 41168,
"text": "Let us now apply the log filter to the HomeController using the following code."
},
{
"code": null,
"e": 41785,
"s": 41248,
"text": "using MVCFiltersDemo.ActionFilters;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCFiltersDemo.Controllers {\n [MyLogActionFilter]\n public class HomeController : Controller{\n // GET: Home\n\t\t\n [OutputCache(Duration = 10)]\n public string Index(){\n return \"This is ASP.Net MVC Filters Tutorial\";\n }\n\t\t\n [OutputCache(Duration = 10)]\n public string GetCurrentTime(){\n return DateTime.Now.ToString(\"T\");\n }\n }\n}"
},
{
"code": null,
"e": 41841,
"s": 41785,
"text": "Run the application and then observe the output window."
},
{
"code": null,
"e": 41957,
"s": 41841,
"text": "As seen in the above screenshot, the stages of processing the action are logged to the Visual Studio output window."
},
{
"code": null,
"e": 42208,
"s": 41957,
"text": "Action selectors are attributes that can be applied to action methods and are used to influence which action method gets invoked in response to a request. It helps the routing engine to select the correct action method to handle a particular request."
},
{
"code": null,
"e": 42468,
"s": 42208,
"text": "It plays a very crucial role when you are writing your action methods. These selectors will decide the behavior of the method invocation based on the modified name given in front of the action method. It is usually used to alias the name of the action method."
},
{
"code": null,
"e": 42522,
"s": 42468,
"text": "There are three types of action selector attributes −"
},
{
"code": null,
"e": 42533,
"s": 42522,
"text": "ActionName"
},
{
"code": null,
"e": 42543,
"s": 42533,
"text": "NonAction"
},
{
"code": null,
"e": 42555,
"s": 42543,
"text": "ActionVerbs"
},
{
"code": null,
"e": 42709,
"s": 42555,
"text": "This class represents an attribute that is used for the name of an action. It also allows developers to use a different action name than the method name."
},
{
"code": null,
"e": 42832,
"s": 42709,
"text": "Let’s take a look at a simple example from the last chapter in which we have HomeController containing two action methods."
},
{
"code": null,
"e": 43238,
"s": 42832,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCFiltersDemo.Controllers {\n public class HomeController : Controller{\n // GET: Home\n public string Index(){\n return \"This is ASP.Net MVC Filters Tutorial\";\n } \n\t\t\n public string GetCurrentTime(){\n return DateTime.Now.ToString(\"T\");\n }\n }\n}"
},
{
"code": null,
"e": 43395,
"s": 43238,
"text": "Let’s apply the the ActionName selector for GetCurrentTime by writing [ActionName(\"CurrentTime\")] above the GetCurrentTime() as shown in the following code."
},
{
"code": null,
"e": 43834,
"s": 43395,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCFiltersDemo.Controllers {\n public class HomeController : Controller{\n // GET: Home\n public string Index(){\n return \"This is ASP.Net MVC Filters Tutorial\";\n }\n\t\t\n [ActionName(\"CurrentTime\")]\n public string GetCurrentTime(){\n return DateTime.Now.ToString(\"T\");\n }\n }\n}"
},
{
"code": null,
"e": 43982,
"s": 43834,
"text": "Now run this application and enter the following URL in the browser http://localhost:62833/Home/CurrentTime, you will receive the following output."
},
{
"code": null,
"e": 44107,
"s": 43982,
"text": "You can see that we have used the CurrentTime instead of the original action name, which is GetCurrentTime in the above URL."
},
{
"code": null,
"e": 44307,
"s": 44107,
"text": "NonAction is another built-in attribute, which indicates that a public method of a Controller is not an action method. It is used when you want that a method shouldn’t be treated as an action method."
},
{
"code": null,
"e": 44453,
"s": 44307,
"text": "Let’s take a look at a simple example by adding another method in HomeController and also apply the NonAction attribute using the following code."
},
{
"code": null,
"e": 45034,
"s": 44453,
"text": "using MVCFiltersDemo.ActionFilters;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCFiltersDemo.Controllers {\n public class HomeController : Controller{\n // GET: Home\n public string Index(){\n return \"This is ASP.Net MVC Filters Tutorial\";\n }\n\t\t\n [ActionName(\"CurrentTime\")]\n public string GetCurrentTime(){\n return TimeString();\n }\n\t\t\n [NonAction]\n public string TimeString(){\n return \"Time is \" + DateTime.Now.ToString(\"T\");\n }\n }\n}"
},
{
"code": null,
"e": 45135,
"s": 45034,
"text": "The new method TimeString is called from the GetCurrentTime() but you can’t use it as action in URL."
},
{
"code": null,
"e": 45287,
"s": 45135,
"text": "Let’s run this application and specify the following URL http://localhost:62833/Home/CurrentTime in the browser. You will receive the following output."
},
{
"code": null,
"e": 45363,
"s": 45287,
"text": "Let us now check the /TimeString as action in the URL and see what happens."
},
{
"code": null,
"e": 45412,
"s": 45363,
"text": "You can see that it gives ‘404—Not Found’ error."
},
{
"code": null,
"e": 45740,
"s": 45412,
"text": "Another selector filter that you can apply is the ActionVerbs attributes. So this restricts the indication of a specific action to specific HttpVerbs. You can define two different action methods with the same name but one action method responds to an HTTP Get request and another action method responds to an HTTP Post request."
},
{
"code": null,
"e": 45790,
"s": 45740,
"text": "MVC framework supports the following ActionVerbs."
},
{
"code": null,
"e": 45798,
"s": 45790,
"text": "HttpGet"
},
{
"code": null,
"e": 45807,
"s": 45798,
"text": "HttpPost"
},
{
"code": null,
"e": 45815,
"s": 45807,
"text": "HttpPut"
},
{
"code": null,
"e": 45826,
"s": 45815,
"text": "HttpDelete"
},
{
"code": null,
"e": 45838,
"s": 45826,
"text": "HttpOptions"
},
{
"code": null,
"e": 45848,
"s": 45838,
"text": "HttpPatch"
},
{
"code": null,
"e": 45930,
"s": 45848,
"text": "Let’s take a look at a simple example in which we will create EmployeeController."
},
{
"code": null,
"e": 46313,
"s": 45930,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCControllerDemo.Controllers {\n public class EmployeeController : Controller{\n // GET: Employee\n public ActionResult Search(string name = “No name Entered”){\n var input = Server.HtmlEncode(name);\n return Content(input);\n }\n }\n}"
},
{
"code": null,
"e": 46394,
"s": 46313,
"text": "Now let’s add another action method with the same name using the following code."
},
{
"code": null,
"e": 46968,
"s": 46394,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCControllerDemo.Controllers {\n public class EmployeeController : Controller{\n // GET: Employee\n //public ActionResult Index()\n //{\n // return View();\n //}\n\t\t\n public ActionResult Search(string name){\n var input = Server.HtmlEncode(name);\n return Content(input);\n }\n\t\t\n public ActionResult Search(){\n var input = \"Another Search action\";\n return Content(input);\n }\n }\n}"
},
{
"code": null,
"e": 47128,
"s": 46968,
"text": "When you run this application, it will give an error because the MVC framework is unable to figure out which action method should be picked up for the request."
},
{
"code": null,
"e": 47229,
"s": 47128,
"text": "Let us specify the HttpGet ActionVerb with the action you want as response using the following code."
},
{
"code": null,
"e": 47819,
"s": 47229,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCControllerDemo.Controllers {\n public class EmployeeController : Controller{\n // GET: Employee\n //public ActionResult Index()\n //{\n // return View();\n //}\n\t\t\n public ActionResult Search(string name){\n var input = Server.HtmlEncode(name);\n return Content(input);\n }\n\t\t\n [HttpGet]\n public ActionResult Search(){\n var input = \"Another Search action\";\n return Content(input);\n }\n }\n}"
},
{
"code": null,
"e": 47889,
"s": 47819,
"text": "When you run this application, you will receive the following output."
},
{
"code": null,
"e": 48132,
"s": 47889,
"text": "In an ASP.NET MVC application, there is nothing like a page and it also doesn’t include anything that directly corresponds to a page when you specify a path in URL. The closest thing to a page in an ASP.NET MVC application is known as a View."
},
{
"code": null,
"e": 48414,
"s": 48132,
"text": "In ASP.NET MVC application, all incoming browser requests are handled by the controller and these requests are mapped to controller actions. A controller action might return a view or it might also perform some other type of action such as redirecting to another controller action."
},
{
"code": null,
"e": 48499,
"s": 48414,
"text": "Let’s take a look at a simple example of View by creating a new ASP.NET MVC project."
},
{
"code": null,
"e": 48575,
"s": 48499,
"text": "Step 1 − Open the Visual Studio and click File → New → Project menu option."
},
{
"code": null,
"e": 48603,
"s": 48575,
"text": "A new Project dialog opens."
},
{
"code": null,
"e": 48668,
"s": 48603,
"text": "Step 2 − From the left pane, select Templates → Visual C# → Web."
},
{
"code": null,
"e": 48729,
"s": 48668,
"text": "Step 3 − In the middle pane, select ASP.NET Web Application."
},
{
"code": null,
"e": 48920,
"s": 48729,
"text": "Step 4 − Enter the project name ‘MVCViewDemo’ in the Name field and click Ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project."
},
{
"code": null,
"e": 49070,
"s": 48920,
"text": "Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok."
},
{
"code": null,
"e": 49169,
"s": 49070,
"text": "It will create a basic MVC project with minimal predefined content. We now need to add controller."
},
{
"code": null,
"e": 49269,
"s": 49169,
"text": "Step 6 − Right-click on the controller folder in the solution explorer and select Add → Controller."
},
{
"code": null,
"e": 49310,
"s": 49269,
"text": "It will display the Add Scaffold dialog."
},
{
"code": null,
"e": 49386,
"s": 49310,
"text": "Step 7 − Select the MVC 5 Controller – Empty option and click ‘Add’ button."
},
{
"code": null,
"e": 49425,
"s": 49386,
"text": "The Add Controller dialog will appear."
},
{
"code": null,
"e": 49489,
"s": 49425,
"text": "Step 8 − Set the name to HomeController and click ‘Add’ button."
},
{
"code": null,
"e": 49614,
"s": 49489,
"text": "You will see a new C# file ‘HomeController.cs’ in the Controllers folder which is open for editing in Visual Studio as well."
},
{
"code": null,
"e": 49721,
"s": 49614,
"text": "Let’s update the HomeController.cs file, which contains two action methods as shown in the following code."
},
{
"code": null,
"e": 50092,
"s": 49721,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCViewDemo.Controllers {\n public class HomeController : Controller{\n // GET: Home\n public ActionResult Index(){\n return View();\n }\n\t\t\n public string Mycontroller(){\n return \"Hi, I am a controller\";\n }\n }\n}"
},
{
"code": null,
"e": 50233,
"s": 50092,
"text": "Step 9 − Run this application and apend /Home/MyController to the URL in the browser and press enter. You will receive the following output."
},
{
"code": null,
"e": 50345,
"s": 50233,
"text": "As MyController action simply returns the string, to return a View from the action we need to add a View first."
},
{
"code": null,
"e": 50436,
"s": 50345,
"text": "Step 10 − Before adding a view let’s add another action, which will return a default view."
},
{
"code": null,
"e": 50878,
"s": 50436,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCViewDemo.Controllers {\n public class HomeController : Controller{\n // GET: Home\n public ActionResult Index(){\n return View();\n }\n\t\t\n public string Mycontroller(){\n return \"Hi, I am a controller\";\n }\n\t\t\n public ActionResult MyView(){\n return View();\n }\n }\n}"
},
{
"code": null,
"e": 51014,
"s": 50878,
"text": "Step 11 − Run this application and apend /Home/MyView to the URL in the browser and press enter. You will receive the following output."
},
{
"code": null,
"e": 51145,
"s": 51014,
"text": "You can see here that we have an error and this error is actually quite descriptive, which tells us it can't find the MyView view."
},
{
"code": null,
"e": 51228,
"s": 51145,
"text": "Step 12 − To add a view, right-click inside the MyView action and select Add view."
},
{
"code": null,
"e": 51305,
"s": 51228,
"text": "It will display the Add View dialog and it is going to add the default name."
},
{
"code": null,
"e": 51380,
"s": 51305,
"text": "Step 13 − Uncheck the ‘Use a layout page’ checkbox and click ‘Add’ button."
},
{
"code": null,
"e": 51422,
"s": 51380,
"text": "We now have the default code inside view."
},
{
"code": null,
"e": 51485,
"s": 51422,
"text": "Step 14 − Add some text in this view using the following code."
},
{
"code": null,
"e": 51730,
"s": 51485,
"text": "@{\n Layout = null;\n}\n\n<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width\" />\n <title>MyView</title>\n </head>\n\t\n <body>\n <div>\n Hi, I am a view\n </div>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 51866,
"s": 51730,
"text": "Step 15 − Run this application and apend /Home/MyView to the URL in the browser. Press enter and you will receive the following output."
},
{
"code": null,
"e": 51906,
"s": 51866,
"text": "You can now see the text from the View."
},
{
"code": null,
"e": 52113,
"s": 51906,
"text": "In this chapter, we will discuss about building models in an ASP.NET MVC Framework application. A model stores data that is retrieved according to the commands from the Controller and displayed in the View."
},
{
"code": null,
"e": 52383,
"s": 52113,
"text": "Model is a collection of classes wherein you will be working with data and business logic. Hence, basically models are business domain-specific containers. It is used to interact with database. It can also be used to manipulate the data to implement the business logic."
},
{
"code": null,
"e": 52469,
"s": 52383,
"text": "Let’s take a look at a simple example of Model by creating a new ASP.Net MVC project."
},
{
"code": null,
"e": 52542,
"s": 52469,
"text": "Step 1 − Open the Visual Studio. Click File → New → Project menu option."
},
{
"code": null,
"e": 52570,
"s": 52542,
"text": "A new Project dialog opens."
},
{
"code": null,
"e": 52635,
"s": 52570,
"text": "Step 2 − From the left pane, select Templates → Visual C# → Web."
},
{
"code": null,
"e": 52696,
"s": 52635,
"text": "Step 3 − In the middle pane, select ASP.NET Web Application."
},
{
"code": null,
"e": 52888,
"s": 52696,
"text": "Step 4 − Enter the project name ‘MVCSimpleApp’ in the Name field and click Ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project."
},
{
"code": null,
"e": 53038,
"s": 52888,
"text": "Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok."
},
{
"code": null,
"e": 53106,
"s": 53038,
"text": "It will create a basic MVC project with minimal predefined content."
},
{
"code": null,
"e": 53139,
"s": 53106,
"text": "We need to add a controller now."
},
{
"code": null,
"e": 53239,
"s": 53139,
"text": "Step 6 − Right-click on the controller folder in the solution explorer and select Add → Controller."
},
{
"code": null,
"e": 53280,
"s": 53239,
"text": "It will display the Add Scaffold dialog."
},
{
"code": null,
"e": 53496,
"s": 53280,
"text": "Step 7 − Select the MVC 5 Controller – with read/write actions option. This template will create an Index method with default action for Controller. This will also list other methods like Edit/Delete/Create as well."
},
{
"code": null,
"e": 53563,
"s": 53496,
"text": "Step 8 − Click ‘Add’ button and Add Controller dialog will appear."
},
{
"code": null,
"e": 53635,
"s": 53563,
"text": "Step 9 − Set the name to EmployeeController and click the ‘Add’ button."
},
{
"code": null,
"e": 53793,
"s": 53635,
"text": "Step 10 − You will see a new C# file ‘EmployeeController.cs’ in the Controllers folder, which is open for editing in Visual Studio with some default actions."
},
{
"code": null,
"e": 55361,
"s": 53793,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCSimpleApp.Controllers {\n public class EmployeeController : Controller{\n // GET: Employee\n public ActionResult Index(){\n return View();\n }\n\t\t\n // GET: Employee/Details/5\n public ActionResult Details(int id){\n return View();\n }\n\t\t\n // GET: Employee/Create\n public ActionResult Create(){\n return View();\n }\n\t\t\n // POST: Employee/Create\n [HttpPost]\n public ActionResult Create(FormCollection collection){\n try{\n // TODO: Add insert logic here\n return RedirectToAction(\"Index\");\n }catch{\n return View();\n }\n }\n\t\t\n // GET: Employee/Edit/5\n public ActionResult Edit(int id){\n return View();\n }\n\t\t\n // POST: Employee/Edit/5\n [HttpPost]\n public ActionResult Edit(int id, FormCollection collection){\n try{\n // TODO: Add update logic here\n return RedirectToAction(\"Index\");\n }catch{\n return View();\n }\n }\n\t\t\n // GET: Employee/Delete/5\n public ActionResult Delete(int id){\n return View();\n }\n\t\t\n // POST: Employee/Delete/5\n [HttpPost]\n public ActionResult Delete(int id, FormCollection collection){\n try{\n // TODO: Add delete logic here\n return RedirectToAction(\"Index\");\n }catch{\n return View();\n }\n }\n }\n}"
},
{
"code": null,
"e": 55380,
"s": 55361,
"text": "Let’s add a model."
},
{
"code": null,
"e": 55472,
"s": 55380,
"text": "Step 11 − Right-click on the Models folder in the solution explorer and select Add → Class."
},
{
"code": null,
"e": 55510,
"s": 55472,
"text": "You will see the Add New Item dialog."
},
{
"code": null,
"e": 55592,
"s": 55510,
"text": "Step 12 − Select Class in the middle pan and enter Employee.cs in the name field."
},
{
"code": null,
"e": 55666,
"s": 55592,
"text": "Step 13 − Add some properties to Employee class using the following code."
},
{
"code": null,
"e": 55973,
"s": 55666,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\n\nnamespace MVCSimpleApp.Models {\n public class Employee{\n public int ID { get; set; }\n public string Name { get; set; }\n public DateTime JoiningDate { get; set; }\n public int Age { get; set; }\n }\n}"
},
{
"code": null,
"e": 56084,
"s": 55973,
"text": "Let’s update the EmployeeController.cs file by adding one more method, which will return the list of employee."
},
{
"code": null,
"e": 56806,
"s": 56084,
"text": "[NonAction]\npublic List<Employee> GetEmployeeList(){\n return new List<Employee>{\n new Employee{\n ID = 1,\n Name = \"Allan\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 23\n },\n\t\t\n new Employee{\n ID = 2,\n Name = \"Carson\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 45\n },\n\t\t\n new Employee{\n ID = 3,\n Name = \"Carson\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 37\n },\n\t\t\n new Employee{\n ID = 4,\n Name = \"Laura\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 26\n },\n };\n}"
},
{
"code": null,
"e": 56879,
"s": 56806,
"text": "Step 14 − Update the index action method as shown in the following code."
},
{
"code": null,
"e": 57013,
"s": 56879,
"text": "public ActionResult Index(){\n var employees = from e in GetEmployeeList()\n orderby e.ID\n select e;\n return View(employees);\n}"
},
{
"code": null,
"e": 57143,
"s": 57013,
"text": "Step 15 − Run this application and append /employee to the URL in the browser and press Enter. You will see the following output."
},
{
"code": null,
"e": 57284,
"s": 57143,
"text": "As seen in the above screenshot, there is an error and this error is actually quite descriptive which tells us it can't find the Index view."
},
{
"code": null,
"e": 57372,
"s": 57284,
"text": "Step 16 − Hence to add a view, right-click inside the Index action and select Add view."
},
{
"code": null,
"e": 57449,
"s": 57372,
"text": "It will display the Add View dialog and it is going to add the default name."
},
{
"code": null,
"e": 57613,
"s": 57449,
"text": "Step 17 − Select the List from the Template dropdown and Employee in Model class dropdown and also uncheck the ‘Use a layout page’ checkbox and click ‘Add’ button."
},
{
"code": null,
"e": 57665,
"s": 57613,
"text": "It will add some default code for you in this view."
},
{
"code": null,
"e": 59054,
"s": 57665,
"text": "@model IEnumerable<MVCSimpleApp.Models.Employee>\n@{\n Layout = null;\n}\n\n<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width\" />\n <title>Index</title>\n </head>\n\t\n <body>\n <p>@Html.ActionLink(\"Create New\", \"Create\")</p>\n <table class = \"table\">\n <tr>\n <th>\n @Html.DisplayNameFor(model => model.Name)\n </th>\n\t\t\t\t\n <th>\n @Html.DisplayNameFor(model => model.JoiningDate)\n </th>\n\t\t\t\t\n <th>\n @Html.DisplayNameFor(model => model.Age)\n </th>\n\t\t\t\t\n <th></th>\n </tr>\n\t\t\t\n @foreach (var item in Model) {\n <tr>\n <td>\n @Html.DisplayFor(modelItem => item.Name)\n </td>\n\t\t\t\t\t\n <td>\n @Html.DisplayFor(modelItem => item.JoiningDate)\n </td>\n\t\t\t\t\t\n <td>\n @Html.DisplayFor(modelItem => item.Age)\n </td>\n\t\t\t\t\t\n <td>\n @Html.ActionLink(\"Edit\", \"Edit\", new { id = item.ID }) |\n @Html.ActionLink(\"Details\", \"Details\", new { id = item.ID }) |\n @Html.ActionLink(\"Delete\", \"Delete\", new { id = item.ID })\n </td>\n\t\t\t\t\t\n </tr>\n }\n\t\t\t\n </table>\n </body>\n</html>"
},
{
"code": null,
"e": 59128,
"s": 59054,
"text": "Step 18 − Run this application and you will receive the following output."
},
{
"code": null,
"e": 59167,
"s": 59128,
"text": "A list of employees will be displayed."
},
{
"code": null,
"e": 59564,
"s": 59167,
"text": "In ASP.Net web forms, developers are using the toolbox for adding controls on any particular page. However, in ASP.NET MVC application there is no toolbox available to drag and drop HTML controls on the view. In ASP.NET MVC application, if you want to create a view it should contain HTML code. So those developers who are new to MVC especially with web forms background finds this a little hard."
},
{
"code": null,
"e": 59945,
"s": 59564,
"text": "To overcome this problem, ASP.NET MVC provides HtmlHelper class which contains different methods that help you create HTML controls programmatically. All HtmlHelper methods generate HTML and return the result as a string. The final HTML is generated at runtime by these functions. The HtmlHelper class is designed to generate UI and it should not be used in controllers or models."
},
{
"code": null,
"e": 59990,
"s": 59945,
"text": "There are different types of helper methods."
},
{
"code": null,
"e": 60048,
"s": 59990,
"text": "Createinputs − Creates inputs for text boxes and buttons."
},
{
"code": null,
"e": 60106,
"s": 60048,
"text": "Createinputs − Creates inputs for text boxes and buttons."
},
{
"code": null,
"e": 60189,
"s": 60106,
"text": "Createlinks − Creates links that are based on information from the routing tables."
},
{
"code": null,
"e": 60272,
"s": 60189,
"text": "Createlinks − Creates links that are based on information from the routing tables."
},
{
"code": null,
"e": 60393,
"s": 60272,
"text": "Createforms − Create form tags that can post back to our action, or to post back to an action on a different controller."
},
{
"code": null,
"e": 60514,
"s": 60393,
"text": "Createforms − Create form tags that can post back to our action, or to post back to an action on a different controller."
},
{
"code": null,
"e": 60529,
"s": 60514,
"text": "Action(String)"
},
{
"code": null,
"e": 60660,
"s": 60529,
"text": "Overloaded. Invokes the specified child action method and returns the result as an HTML string. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 60683,
"s": 60660,
"text": "Action(String, Object)"
},
{
"code": null,
"e": 60844,
"s": 60683,
"text": "Overloaded. Invokes the specified child action method with the specified parameters and returns the result as an HTML string. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 60881,
"s": 60844,
"text": "Action(String, RouteValueDictionary)"
},
{
"code": null,
"e": 61043,
"s": 60881,
"text": "Overloaded. Invokes the specified child action method using the specified parameters and returns the result as an HTML string. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 61066,
"s": 61043,
"text": "Action(String, String)"
},
{
"code": null,
"e": 61233,
"s": 61066,
"text": "Overloaded. Invokes the specified child action method using the specified controller name and returns the result as an HTML string. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 61264,
"s": 61233,
"text": "Action(String, String, Object)"
},
{
"code": null,
"e": 61446,
"s": 61264,
"text": "Overloaded. Invokes the specified child action method using the specified parameters and controller name and returns the result as an HTML string. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 61491,
"s": 61446,
"text": "Action(String, String, RouteValueDictionary)"
},
{
"code": null,
"e": 61673,
"s": 61491,
"text": "Overloaded. Invokes the specified child action method using the specified parameters and controller name and returns the result as an HTML string. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 61700,
"s": 61673,
"text": "ActionLink(String, String)"
},
{
"code": null,
"e": 61740,
"s": 61700,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 61775,
"s": 61740,
"text": "ActionLink(String, String, Object)"
},
{
"code": null,
"e": 61815,
"s": 61775,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 61858,
"s": 61815,
"text": "ActionLink(String, String, Object, Object)"
},
{
"code": null,
"e": 61898,
"s": 61858,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 61947,
"s": 61898,
"text": "ActionLink(String, String, RouteValueDictionary)"
},
{
"code": null,
"e": 61987,
"s": 61947,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 62065,
"s": 61987,
"text": "ActionLink(String, String, RouteValueDictionary, IDictionary<String, Object>)"
},
{
"code": null,
"e": 62105,
"s": 62065,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 62140,
"s": 62105,
"text": "ActionLink(String, String, String)"
},
{
"code": null,
"e": 62180,
"s": 62140,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 62231,
"s": 62180,
"text": "ActionLink(String, String, String, Object, Object)"
},
{
"code": null,
"e": 62271,
"s": 62231,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 62357,
"s": 62271,
"text": "ActionLink(String, String, String, RouteValueDictionary, IDictionary<String, Object>)"
},
{
"code": null,
"e": 62397,
"s": 62357,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 62472,
"s": 62397,
"text": "ActionLink(String, String, String, String, String, String, Object, Object)"
},
{
"code": null,
"e": 62512,
"s": 62472,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 62622,
"s": 62512,
"text": "ActionLink(String, String, String, String, String, String, RouteValueDictionary, IDictionary<String, Object>)"
},
{
"code": null,
"e": 62662,
"s": 62622,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 62674,
"s": 62662,
"text": "BeginForm()"
},
{
"code": null,
"e": 62855,
"s": 62674,
"text": "Overloaded. Writes an opening <form> tag to the response. The form uses the POST method, and the request is processed by the action method for the view. (Defined by FormExtensions)"
},
{
"code": null,
"e": 62873,
"s": 62855,
"text": "BeginForm(Object)"
},
{
"code": null,
"e": 63108,
"s": 62873,
"text": "Overloaded. Writes an opening <form> tag to the response and includes the route values in the action attribute. The form uses the POST method, and the request is processed by the action method for the view. (Defined by FormExtensions)"
},
{
"code": null,
"e": 63140,
"s": 63108,
"text": "BeginForm(RouteValueDictionary)"
},
{
"code": null,
"e": 63408,
"s": 63140,
"text": "Overloaded. Writes an opening <form> tag to the response and includes the route values from the route value dictionary in the action attribute. The form uses the POST method, and the request is processed by the action method for the view. (Defined by FormExtensions.)"
},
{
"code": null,
"e": 63434,
"s": 63408,
"text": "BeginForm(String, String)"
},
{
"code": null,
"e": 63614,
"s": 63434,
"text": "Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the POST method. (Defined by FormExtensions)"
},
{
"code": null,
"e": 63652,
"s": 63614,
"text": "BeginForm(String, String, FormMethod)"
},
{
"code": null,
"e": 63842,
"s": 63652,
"text": "Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the specified HTTP method. (Defined by FormExtensions)"
},
{
"code": null,
"e": 63909,
"s": 63842,
"text": "BeginForm(String, String, FormMethod, IDictionary<String, Object>)"
},
{
"code": null,
"e": 64150,
"s": 63909,
"text": "Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the specified HTTP method and includes the HTML attributes from a dictionary. (Defined by FormExtensions)"
},
{
"code": null,
"e": 64196,
"s": 64150,
"text": "BeginForm(String, String, FormMethod, Object)"
},
{
"code": null,
"e": 64419,
"s": 64196,
"text": "Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the specified HTTP method and includes the HTML attributes. (Defined by FormExtensions)"
},
{
"code": null,
"e": 64453,
"s": 64419,
"text": "BeginForm(String, String, Object)"
},
{
"code": null,
"e": 64649,
"s": 64453,
"text": "Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values. The form uses the POST method. (Defined by FormExtensions)"
},
{
"code": null,
"e": 64695,
"s": 64649,
"text": "BeginForm(String, String, Object, FormMethod)"
},
{
"code": null,
"e": 64900,
"s": 64695,
"text": "Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller, action, and route values. The form uses the specified HTTP method. (Defined by FormExtensions)"
},
{
"code": null,
"e": 64954,
"s": 64900,
"text": "BeginForm(String, String, Object, FormMethod, Object)"
},
{
"code": null,
"e": 65192,
"s": 64954,
"text": "Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller, action, and route values. The form uses the specified HTTP method and includes the HTML attributes. (Defined by FormExtensions)"
},
{
"code": null,
"e": 65240,
"s": 65192,
"text": "BeginForm(String, String, RouteValueDictionary)"
},
{
"code": null,
"e": 65468,
"s": 65240,
"text": "Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values from the route value dictionary. The form uses the POST method. (Defined by FormExtensions)"
},
{
"code": null,
"e": 65528,
"s": 65468,
"text": "BeginForm(String, String, RouteValueDictionary, FormMethod)"
},
{
"code": null,
"e": 65766,
"s": 65528,
"text": "Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values from the route value dictionary. The form uses the specified HTTP method. (Defined by FormExtensions)"
},
{
"code": null,
"e": 65855,
"s": 65766,
"text": "BeginForm(String, String, RouteValueDictionary, FormMethod, IDictionary<String, Object>)"
},
{
"code": null,
"e": 66147,
"s": 65855,
"text": "Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values from the route value dictionary. The form uses the specified HTTP method, and includes the HTML attributes from the dictionary. (Defined by FormExtensions)"
},
{
"code": null,
"e": 66170,
"s": 66147,
"text": "BeginRouteForm(Object)"
},
{
"code": null,
"e": 66339,
"s": 66170,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 66376,
"s": 66339,
"text": "BeginRouteForm(RouteValueDictionary)"
},
{
"code": null,
"e": 66545,
"s": 66376,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 66568,
"s": 66545,
"text": "BeginRouteForm(String)"
},
{
"code": null,
"e": 66737,
"s": 66568,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 66772,
"s": 66737,
"text": "BeginRouteForm(String, FormMethod)"
},
{
"code": null,
"e": 66941,
"s": 66772,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 67005,
"s": 66941,
"text": "BeginRouteForm(String, FormMethod, IDictionary<String, Object>)"
},
{
"code": null,
"e": 67174,
"s": 67005,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 67217,
"s": 67174,
"text": "BeginRouteForm(String, FormMethod, Object)"
},
{
"code": null,
"e": 67386,
"s": 67217,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 67417,
"s": 67386,
"text": "BeginRouteForm(String, Object)"
},
{
"code": null,
"e": 67586,
"s": 67417,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 67629,
"s": 67586,
"text": "BeginRouteForm(String, Object, FormMethod)"
},
{
"code": null,
"e": 67798,
"s": 67629,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 67849,
"s": 67798,
"text": "BeginRouteForm(String, Object, FormMethod, Object)"
},
{
"code": null,
"e": 68018,
"s": 67849,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 68063,
"s": 68018,
"text": "BeginRouteForm(String, RouteValueDictionary)"
},
{
"code": null,
"e": 68232,
"s": 68063,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 68289,
"s": 68232,
"text": "BeginRouteForm(String, RouteValueDictionary, FormMethod)"
},
{
"code": null,
"e": 68458,
"s": 68289,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 68544,
"s": 68458,
"text": "BeginRouteForm(String, RouteValueDictionary, FormMethod, IDictionary<String, Object>)"
},
{
"code": null,
"e": 68713,
"s": 68544,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 68730,
"s": 68713,
"text": "CheckBox(String)"
},
{
"code": null,
"e": 68871,
"s": 68730,
"text": "Overloaded. Returns a checkbox input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)"
},
{
"code": null,
"e": 68897,
"s": 68871,
"text": "CheckBox(String, Boolean)"
},
{
"code": null,
"e": 69094,
"s": 68897,
"text": "Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, and a value to indicate whether the check box is selected. (Defined by InputExtensions)"
},
{
"code": null,
"e": 69149,
"s": 69094,
"text": "CheckBox(String, Boolean, IDictionary<String, Object>)"
},
{
"code": null,
"e": 69367,
"s": 69149,
"text": "Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, a value to indicate whether the check box is selected, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 69401,
"s": 69367,
"text": "CheckBox(String, Boolean, Object)"
},
{
"code": null,
"e": 69622,
"s": 69401,
"text": "Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, a value that indicates whether the check box is selected, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 69668,
"s": 69622,
"text": "CheckBox(String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 69831,
"s": 69668,
"text": "Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 69856,
"s": 69831,
"text": "CheckBox(String, Object)"
},
{
"code": null,
"e": 70019,
"s": 69856,
"text": "Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 70035,
"s": 70019,
"text": "Display(String)"
},
{
"code": null,
"e": 70174,
"s": 70035,
"text": "Overloaded. Returns HTML markup for each property in the object that is represented by a string expression. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 70198,
"s": 70174,
"text": "Display(String, Object)"
},
{
"code": null,
"e": 70365,
"s": 70198,
"text": "Overloaded. Returns HTML markup for each property in the object that is represented by a string expression, using additional view data. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 70389,
"s": 70365,
"text": "Display(String, String)"
},
{
"code": null,
"e": 70553,
"s": 70389,
"text": "Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 70585,
"s": 70553,
"text": "Display(String, String, Object)"
},
{
"code": null,
"e": 70774,
"s": 70585,
"text": "Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template and additional view data. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 70806,
"s": 70774,
"text": "Display(String, String, String)"
},
{
"code": null,
"e": 70991,
"s": 70806,
"text": "Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template and an HTML field ID. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 71031,
"s": 70991,
"text": "Display(String, String, String, Object)"
},
{
"code": null,
"e": 71236,
"s": 71031,
"text": "Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template, HTML field ID, and additional view data. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 71254,
"s": 71236,
"text": "DisplayForModel()"
},
{
"code": null,
"e": 71349,
"s": 71254,
"text": "Overloaded. Returns HTML markup for each property in the model. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 71373,
"s": 71349,
"text": "DisplayForModel(Object)"
},
{
"code": null,
"e": 71496,
"s": 71373,
"text": "Overloaded. Returns HTML markup for each property in the model, using additional view data. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 71520,
"s": 71496,
"text": "DisplayForModel(String)"
},
{
"code": null,
"e": 71644,
"s": 71520,
"text": "Overloaded. Returns HTML markup for each property in the model using the specified template. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 71676,
"s": 71644,
"text": "DisplayForModel(String, Object)"
},
{
"code": null,
"e": 71826,
"s": 71676,
"text": "Overloaded. Returns HTML markup for each property in the model, using the specified template and additional view data. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 71858,
"s": 71826,
"text": "DisplayForModel(String, String)"
},
{
"code": null,
"e": 72000,
"s": 71858,
"text": "Overloaded. Returns HTML markup for each property in the model using the specified template and HTML field ID. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 72040,
"s": 72000,
"text": "DisplayForModel(String, String, Object)"
},
{
"code": null,
"e": 72209,
"s": 72040,
"text": "Overloaded. Returns HTML markup for each property in the model, using the specified template, an HTML field ID, and additional view data. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 72229,
"s": 72209,
"text": "DisplayName(String)"
},
{
"code": null,
"e": 72287,
"s": 72229,
"text": "Gets the display name. (Defined by DisplayNameExtensions)"
},
{
"code": null,
"e": 72309,
"s": 72287,
"text": "DisplayNameForModel()"
},
{
"code": null,
"e": 72381,
"s": 72309,
"text": "Gets the display name for the model. (Defined by DisplayNameExtensions)"
},
{
"code": null,
"e": 72401,
"s": 72381,
"text": "DisplayText(String)"
},
{
"code": null,
"e": 72537,
"s": 72401,
"text": "Returns HTML markup for each property in the object that is represented by the specified expression. (Defined by DisplayTextExtensions)"
},
{
"code": null,
"e": 72558,
"s": 72537,
"text": "DropDownList(String)"
},
{
"code": null,
"e": 72706,
"s": 72558,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper and the name of the form field. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 72756,
"s": 72706,
"text": "DropDownList(String, IEnumerable<SelectListItem>)"
},
{
"code": null,
"e": 72931,
"s": 72756,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, and the specified list items. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 73010,
"s": 72931,
"text": "DropDownList(String, IEnumerable<SelectListItem>, IDictionary<String, Object>)"
},
{
"code": null,
"e": 73216,
"s": 73010,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HTML attributes. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 73274,
"s": 73216,
"text": "DropDownList(String, IEnumerable<SelectListItem>, Object)"
},
{
"code": null,
"e": 73480,
"s": 73274,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HTML attributes. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 73538,
"s": 73480,
"text": "DropDownList(String, IEnumerable<SelectListItem>, String)"
},
{
"code": null,
"e": 73730,
"s": 73538,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and an option label. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 73817,
"s": 73730,
"text": "DropDownList(String, IEnumerable<SelectListItem>, String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 74040,
"s": 73817,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, an option label, and the specified HTML attributes. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 74106,
"s": 74040,
"text": "DropDownList(String, IEnumerable<SelectListItem>, String, Object)"
},
{
"code": null,
"e": 74329,
"s": 74106,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, an option label, and the specified HTML attributes. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 74358,
"s": 74329,
"text": "DropDownList(String, String)"
},
{
"code": null,
"e": 74524,
"s": 74358,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, and an option label. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 74539,
"s": 74524,
"text": "Editor(String)"
},
{
"code": null,
"e": 74682,
"s": 74539,
"text": "Overloaded. Returns an HTML input element for each property in the object that is represented by the expression. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 74705,
"s": 74682,
"text": "Editor(String, Object)"
},
{
"code": null,
"e": 74876,
"s": 74705,
"text": "Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using additional view data. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 74899,
"s": 74876,
"text": "Editor(String, String)"
},
{
"code": null,
"e": 75072,
"s": 74899,
"text": "Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 75103,
"s": 75072,
"text": "Editor(String, String, Object)"
},
{
"code": null,
"e": 75301,
"s": 75103,
"text": "Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template and additional view data. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 75332,
"s": 75301,
"text": "Editor(String, String, String)"
},
{
"code": null,
"e": 75525,
"s": 75332,
"text": "Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template and HTML field name. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 75564,
"s": 75525,
"text": "Editor(String, String, String, Object)"
},
{
"code": null,
"e": 75780,
"s": 75564,
"text": "Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template, HTML field name, and additional view data. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 75797,
"s": 75780,
"text": "EditorForModel()"
},
{
"code": null,
"e": 75901,
"s": 75797,
"text": "Overloaded. Returns an HTML input element for each property in the model. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 75924,
"s": 75901,
"text": "EditorForModel(Object)"
},
{
"code": null,
"e": 76056,
"s": 75924,
"text": "Overloaded. Returns an HTML input element for each property in the model, using additional view data. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 76079,
"s": 76056,
"text": "EditorForModel(String)"
},
{
"code": null,
"e": 76213,
"s": 76079,
"text": "Overloaded. Returns an HTML input element for each property in the model, using the specified template. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 76244,
"s": 76213,
"text": "EditorForModel(String, Object)"
},
{
"code": null,
"e": 76403,
"s": 76244,
"text": "Overloaded. Returns an HTML input element for each property in the model, using the specified template and additional view data. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 76434,
"s": 76403,
"text": "EditorForModel(String, String)"
},
{
"code": null,
"e": 76593,
"s": 76434,
"text": "Overloaded. Returns an HTML input element for each property in the model, using the specified template name and HTML field name. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 76632,
"s": 76593,
"text": "EditorForModel(String, String, Object)"
},
{
"code": null,
"e": 76804,
"s": 76632,
"text": "Overloaded. Returns an HTML input element for each property in the model, using the template name, HTML field name, and additional view data. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 76814,
"s": 76804,
"text": "EndForm()"
},
{
"code": null,
"e": 76891,
"s": 76814,
"text": "Renders the closing </form> tag to the response. (Defined by FormExtensions)"
},
{
"code": null,
"e": 76906,
"s": 76891,
"text": "Hidden(String)"
},
{
"code": null,
"e": 77045,
"s": 76906,
"text": "Overloaded. Returns a hidden input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)"
},
{
"code": null,
"e": 77068,
"s": 77045,
"text": "Hidden(String, Object)"
},
{
"code": null,
"e": 77219,
"s": 77068,
"text": "Overloaded. Returns a hidden input element by using the specified HTML helper, the name of the form field, and the value. (Defined by InputExtensions)"
},
{
"code": null,
"e": 77271,
"s": 77219,
"text": "Hidden(String, Object, IDictionary<String, Object>)"
},
{
"code": null,
"e": 77443,
"s": 77271,
"text": "Overloaded. Returns a hidden input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 77474,
"s": 77443,
"text": "Hidden(String, Object, Object)"
},
{
"code": null,
"e": 77646,
"s": 77474,
"text": "Overloaded. Returns a hidden input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 77657,
"s": 77646,
"text": "Id(String)"
},
{
"code": null,
"e": 77723,
"s": 77657,
"text": "Gets the ID of the HtmlHelper string. (Defined by NameExtensions)"
},
{
"code": null,
"e": 77736,
"s": 77723,
"text": "IdForModel()"
},
{
"code": null,
"e": 77802,
"s": 77736,
"text": "Gets the ID of the HtmlHelper string. (Defined by NameExtensions)"
},
{
"code": null,
"e": 77816,
"s": 77802,
"text": "Label(String)"
},
{
"code": null,
"e": 77974,
"s": 77816,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 78017,
"s": 77974,
"text": "Label(String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 78175,
"s": 78017,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 78197,
"s": 78175,
"text": "Label(String, Object)"
},
{
"code": null,
"e": 78355,
"s": 78197,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 78377,
"s": 78355,
"text": "Label(String, String)"
},
{
"code": null,
"e": 78556,
"s": 78377,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression using the label text. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 78607,
"s": 78556,
"text": "Label(String, String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 78765,
"s": 78607,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 78795,
"s": 78765,
"text": "Label(String, String, Object)"
},
{
"code": null,
"e": 78953,
"s": 78795,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 78969,
"s": 78953,
"text": "LabelForModel()"
},
{
"code": null,
"e": 79112,
"s": 78969,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the model. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 79155,
"s": 79112,
"text": "LabelForModel(IDictionary<String, Object>)"
},
{
"code": null,
"e": 79313,
"s": 79155,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 79335,
"s": 79313,
"text": "LabelForModel(Object)"
},
{
"code": null,
"e": 79493,
"s": 79335,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 79515,
"s": 79493,
"text": "LabelForModel(String)"
},
{
"code": null,
"e": 79694,
"s": 79515,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression using the label text. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 79745,
"s": 79694,
"text": "LabelForModel(String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 79903,
"s": 79745,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 79933,
"s": 79903,
"text": "LabelForModel(String, Object)"
},
{
"code": null,
"e": 80091,
"s": 79933,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 80107,
"s": 80091,
"text": "ListBox(String)"
},
{
"code": null,
"e": 80251,
"s": 80107,
"text": "Overloaded. Returns a multi-select select element using the specified HTML helper and the name of the form field. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 80296,
"s": 80251,
"text": "ListBox(String, IEnumerable<SelectListItem>)"
},
{
"code": null,
"e": 80467,
"s": 80296,
"text": "Overloaded. Returns a multi-select select element using the specified HTML helper, the name of the form field, and the specified list items. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 80541,
"s": 80467,
"text": "ListBox(String, IEnumerable<SelectListItem>, IDictionary<String, Object>)"
},
{
"code": null,
"e": 80743,
"s": 80541,
"text": "Overloaded. Returns a multi-select select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HMTL attributes. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 80796,
"s": 80743,
"text": "ListBox(String, IEnumerable<SelectListItem>, Object)"
},
{
"code": null,
"e": 80967,
"s": 80796,
"text": "Overloaded. Returns a multi-select select element using the specified HTML helper, the name of the form field, and the specified list items. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 80980,
"s": 80967,
"text": "Name(String)"
},
{
"code": null,
"e": 81092,
"s": 80980,
"text": "Gets the full HTML field name for the object that is represented by the expression. (Defined by NameExtensions)"
},
{
"code": null,
"e": 81107,
"s": 81092,
"text": "NameForModel()"
},
{
"code": null,
"e": 81220,
"s": 81107,
"text": "Gets the full HTML field name for the object that is represented by the expression. (Defined by NameExtensions.)"
},
{
"code": null,
"e": 81236,
"s": 81220,
"text": "Partial(String)"
},
{
"code": null,
"e": 81340,
"s": 81236,
"text": "Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)"
},
{
"code": null,
"e": 81364,
"s": 81340,
"text": "Partial(String, Object)"
},
{
"code": null,
"e": 81468,
"s": 81364,
"text": "Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)"
},
{
"code": null,
"e": 81512,
"s": 81468,
"text": "Partial(String, Object, ViewDataDictionary)"
},
{
"code": null,
"e": 81616,
"s": 81512,
"text": "Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)"
},
{
"code": null,
"e": 81652,
"s": 81616,
"text": "Partial(String, ViewDataDictionary)"
},
{
"code": null,
"e": 81756,
"s": 81652,
"text": "Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)"
},
{
"code": null,
"e": 81773,
"s": 81756,
"text": "Password(String)"
},
{
"code": null,
"e": 81914,
"s": 81773,
"text": "Overloaded. Returns a password input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)"
},
{
"code": null,
"e": 81939,
"s": 81914,
"text": "Password(String, Object)"
},
{
"code": null,
"e": 82092,
"s": 81939,
"text": "Overloaded. Returns a password input element by using the specified HTML helper, the name of the form field, and the value. (Defined by InputExtensions)"
},
{
"code": null,
"e": 82146,
"s": 82092,
"text": "Password(String, Object, IDictionary<String, Object>)"
},
{
"code": null,
"e": 82320,
"s": 82146,
"text": "Overloaded. Returns a password input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 82353,
"s": 82320,
"text": "Password(String, Object, Object)"
},
{
"code": null,
"e": 82527,
"s": 82353,
"text": "Overloaded. Returns a password input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 82555,
"s": 82527,
"text": "RadioButton(String, Object)"
},
{
"code": null,
"e": 82685,
"s": 82555,
"text": "Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)"
},
{
"code": null,
"e": 82722,
"s": 82685,
"text": "RadioButton(String, Object, Boolean)"
},
{
"code": null,
"e": 82852,
"s": 82722,
"text": "Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)"
},
{
"code": null,
"e": 82918,
"s": 82852,
"text": "RadioButton(String, Object, Boolean, IDictionary<String, Object>)"
},
{
"code": null,
"e": 83048,
"s": 82918,
"text": "Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)"
},
{
"code": null,
"e": 83093,
"s": 83048,
"text": "RadioButton(String, Object, Boolean, Object)"
},
{
"code": null,
"e": 83223,
"s": 83093,
"text": "Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)"
},
{
"code": null,
"e": 83280,
"s": 83223,
"text": "RadioButton(String, Object, IDictionary<String, Object>)"
},
{
"code": null,
"e": 83410,
"s": 83280,
"text": "Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)"
},
{
"code": null,
"e": 83446,
"s": 83410,
"text": "RadioButton(String, Object, Object)"
},
{
"code": null,
"e": 83576,
"s": 83446,
"text": "Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)"
},
{
"code": null,
"e": 83597,
"s": 83576,
"text": "RenderAction(String)"
},
{
"code": null,
"e": 83736,
"s": 83597,
"text": "Overloaded. Invokes the specified child action method and renders the result inline in the parent view. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 83765,
"s": 83736,
"text": "RenderAction(String, Object)"
},
{
"code": null,
"e": 83935,
"s": 83765,
"text": "Overloaded. Invokes the specified child action method using the specified parameters and renders the result inline in the parent view. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 83978,
"s": 83935,
"text": "RenderAction(String, RouteValueDictionary)"
},
{
"code": null,
"e": 84148,
"s": 83978,
"text": "Overloaded. Invokes the specified child action method using the specified parameters and renders the result inline in the parent view. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 84177,
"s": 84148,
"text": "RenderAction(String, String)"
},
{
"code": null,
"e": 84352,
"s": 84177,
"text": "Overloaded. Invokes the specified child action method using the specified controller name and renders the result inline in the parent view. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 84389,
"s": 84352,
"text": "RenderAction(String, String, Object)"
},
{
"code": null,
"e": 84579,
"s": 84389,
"text": "Overloaded. Invokes the specified child action method using the specified parameters and controller name and renders the result inline in the parent view. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 84630,
"s": 84579,
"text": "RenderAction(String, String, RouteValueDictionary)"
},
{
"code": null,
"e": 84820,
"s": 84630,
"text": "Overloaded. Invokes the specified child action method using the specified parameters and controller name and renders the result inline in the parent view. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 84842,
"s": 84820,
"text": "RenderPartial(String)"
},
{
"code": null,
"e": 84962,
"s": 84842,
"text": "Overloaded. Renders the specified partial view by using the specified HTML helper. (Defined by RenderPartialExtensions)"
},
{
"code": null,
"e": 84992,
"s": 84962,
"text": "RenderPartial(String, Object)"
},
{
"code": null,
"e": 85193,
"s": 84992,
"text": "Overloaded. Renders the specified partial view, passing it a copy of the current ViewDataDictionary object, but with the Model property set to the specified model. (Defined by RenderPartialExtensions)"
},
{
"code": null,
"e": 85243,
"s": 85193,
"text": "RenderPartial(String, Object, ViewDataDictionary)"
},
{
"code": null,
"e": 85492,
"s": 85243,
"text": "Overloaded. Renders the specified partial view, replacing the partial view's ViewData property with the specified ViewDataDictionary object and setting the Model property of the view data to the specified model. (Defined by RenderPartialExtensions)"
},
{
"code": null,
"e": 85534,
"s": 85492,
"text": "RenderPartial(String, ViewDataDictionary)"
},
{
"code": null,
"e": 85697,
"s": 85534,
"text": "Overloaded. Renders the specified partial view, replacing its ViewData property with the specified ViewDataDictionary object. (Defined by RenderPartialExtensions)"
},
{
"code": null,
"e": 85723,
"s": 85697,
"text": "RouteLink(String, Object)"
},
{
"code": null,
"e": 85763,
"s": 85723,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 85797,
"s": 85763,
"text": "RouteLink(String, Object, Object)"
},
{
"code": null,
"e": 85837,
"s": 85797,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 85877,
"s": 85837,
"text": "RouteLink(String, RouteValueDictionary)"
},
{
"code": null,
"e": 85917,
"s": 85877,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 85986,
"s": 85917,
"text": "RouteLink(String, RouteValueDictionary, IDictionary<String, Object>)"
},
{
"code": null,
"e": 86026,
"s": 85986,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 86052,
"s": 86026,
"text": "RouteLink(String, String)"
},
{
"code": null,
"e": 86092,
"s": 86052,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 86126,
"s": 86092,
"text": "RouteLink(String, String, Object)"
},
{
"code": null,
"e": 86166,
"s": 86126,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 86208,
"s": 86166,
"text": "RouteLink(String, String, Object, Object)"
},
{
"code": null,
"e": 86248,
"s": 86208,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 86296,
"s": 86248,
"text": "RouteLink(String, String, RouteValueDictionary)"
},
{
"code": null,
"e": 86336,
"s": 86296,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 86413,
"s": 86336,
"text": "RouteLink(String, String, RouteValueDictionary, IDictionary<String, Object>)"
},
{
"code": null,
"e": 86453,
"s": 86413,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 86519,
"s": 86453,
"text": "RouteLink(String, String, String, String, String, Object, Object)"
},
{
"code": null,
"e": 86559,
"s": 86519,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 86660,
"s": 86559,
"text": "RouteLink(String, String, String, String, String, RouteValueDictionary, IDictionary<String, Object>)"
},
{
"code": null,
"e": 86700,
"s": 86660,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 86717,
"s": 86700,
"text": "TextArea(String)"
},
{
"code": null,
"e": 86868,
"s": 86717,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper and the name of the form field. (Defined by TextAreaExtensions.)"
},
{
"code": null,
"e": 86914,
"s": 86868,
"text": "TextArea(String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 87096,
"s": 86914,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, and the specified HTML attributes. (Defined by TextAreaExtensions)"
},
{
"code": null,
"e": 87121,
"s": 87096,
"text": "TextArea(String, Object)"
},
{
"code": null,
"e": 87260,
"s": 87121,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper and HTML attributes. (Defined by TextAreaExtensions)"
},
{
"code": null,
"e": 87285,
"s": 87260,
"text": "TextArea(String, String)"
},
{
"code": null,
"e": 87454,
"s": 87285,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, and the text content. (Defined by TextAreaExtensions)"
},
{
"code": null,
"e": 87508,
"s": 87454,
"text": "TextArea(String, String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 87708,
"s": 87508,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, and the specified HTML attributes. (Defined by TextAreaExtensions)"
},
{
"code": null,
"e": 87776,
"s": 87708,
"text": "TextArea(String, String, Int32, Int32, IDictionary<String, Object>)"
},
{
"code": null,
"e": 88008,
"s": 87776,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, the number of rows and columns, and the specified HTML attributes. (Defined by TextAreaExtensions)"
},
{
"code": null,
"e": 88055,
"s": 88008,
"text": "TextArea(String, String, Int32, Int32, Object)"
},
{
"code": null,
"e": 88287,
"s": 88055,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, the number of rows and columns, and the specified HTML attributes. (Defined by TextAreaExtensions)"
},
{
"code": null,
"e": 88320,
"s": 88287,
"text": "TextArea(String, String, Object)"
},
{
"code": null,
"e": 88520,
"s": 88320,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, and the specified HTML attributes. (Defined by TextAreaExtensions)"
},
{
"code": null,
"e": 88536,
"s": 88520,
"text": "TextBox(String)"
},
{
"code": null,
"e": 88673,
"s": 88536,
"text": "Overloaded. Returns a text input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)"
},
{
"code": null,
"e": 88697,
"s": 88673,
"text": "TextBox(String, Object)"
},
{
"code": null,
"e": 88846,
"s": 88697,
"text": "Overloaded. Returns a text input element by using the specified HTML helper, the name of the form field, and the value. (Defined by InputExtensions)"
},
{
"code": null,
"e": 88899,
"s": 88846,
"text": "TextBox(String, Object, IDictionary<String, Object>)"
},
{
"code": null,
"e": 89069,
"s": 88899,
"text": "Overloaded. Returns a text input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 89101,
"s": 89069,
"text": "TextBox(String, Object, Object)"
},
{
"code": null,
"e": 89271,
"s": 89101,
"text": "Overloaded. Returns a text input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 89303,
"s": 89271,
"text": "TextBox(String, Object, String)"
},
{
"code": null,
"e": 89374,
"s": 89303,
"text": "Overloaded. Returns a text input element. (Defined by InputExtensions)"
},
{
"code": null,
"e": 89435,
"s": 89374,
"text": "TextBox(String, Object, String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 89506,
"s": 89435,
"text": "Overloaded. Returns a text input element. (Defined by InputExtensions)"
},
{
"code": null,
"e": 89546,
"s": 89506,
"text": "TextBox(String, Object, String, Object)"
},
{
"code": null,
"e": 89617,
"s": 89546,
"text": "Overloaded. Returns a text input element. (Defined by InputExtensions)"
},
{
"code": null,
"e": 89634,
"s": 89617,
"text": "Validate(String)"
},
{
"code": null,
"e": 89767,
"s": 89634,
"text": "Retrieves the validation metadata for the specified model and applies each rule to the data field. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 89793,
"s": 89767,
"text": "ValidationMessage(String)"
},
{
"code": null,
"e": 89948,
"s": 89793,
"text": "Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 90003,
"s": 89948,
"text": "ValidationMessage(String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 90159,
"s": 90003,
"text": "Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions.)"
},
{
"code": null,
"e": 90222,
"s": 90159,
"text": "ValidationMessage(String, IDictionary<String, Object>, String)"
},
{
"code": null,
"e": 90377,
"s": 90222,
"text": "Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 90411,
"s": 90377,
"text": "ValidationMessage(String, Object)"
},
{
"code": null,
"e": 90566,
"s": 90411,
"text": "Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 90608,
"s": 90566,
"text": "ValidationMessage(String, Object, String)"
},
{
"code": null,
"e": 90763,
"s": 90608,
"text": "Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 90797,
"s": 90763,
"text": "ValidationMessage(String, String)"
},
{
"code": null,
"e": 90952,
"s": 90797,
"text": "Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 91015,
"s": 90952,
"text": "ValidationMessage(String, String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 91170,
"s": 91015,
"text": "Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 91241,
"s": 91170,
"text": "ValidationMessage(String, String, IDictionary<String, Object>, String)"
},
{
"code": null,
"e": 91396,
"s": 91241,
"text": "Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 91438,
"s": 91396,
"text": "ValidationMessage(String, String, Object)"
},
{
"code": null,
"e": 91591,
"s": 91438,
"text": "Overloaded. Displays a validation message if an error exists forthe specified field in the ModelStateDictionary object. (Definedby ValidationExtensions)"
},
{
"code": null,
"e": 91641,
"s": 91591,
"text": "ValidationMessage(String, String, Object, String)"
},
{
"code": null,
"e": 91796,
"s": 91641,
"text": "Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 91838,
"s": 91796,
"text": "ValidationMessage(String, String, String)"
},
{
"code": null,
"e": 91993,
"s": 91838,
"text": "Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 92013,
"s": 91993,
"text": "ValidationSummary()"
},
{
"code": null,
"e": 92166,
"s": 92013,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 92193,
"s": 92166,
"text": "ValidationSummary(Boolean)"
},
{
"code": null,
"e": 92394,
"s": 92193,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 92429,
"s": 92394,
"text": "ValidationSummary(Boolean, String)"
},
{
"code": null,
"e": 92630,
"s": 92429,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 92694,
"s": 92630,
"text": "ValidationSummary(Boolean, String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 92895,
"s": 92694,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 92967,
"s": 92895,
"text": "ValidationSummary(Boolean, String, IDictionary<String, Object>, String)"
},
{
"code": null,
"e": 93013,
"s": 92967,
"text": "Overloaded. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 93056,
"s": 93013,
"text": "ValidationSummary(Boolean, String, Object)"
},
{
"code": null,
"e": 93257,
"s": 93056,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 93308,
"s": 93257,
"text": "ValidationSummary(Boolean, String, Object, String)"
},
{
"code": null,
"e": 93354,
"s": 93308,
"text": "Overloaded. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 93397,
"s": 93354,
"text": "ValidationSummary(Boolean, String, String)"
},
{
"code": null,
"e": 93443,
"s": 93397,
"text": "Overloaded. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 93469,
"s": 93443,
"text": "ValidationSummary(String)"
},
{
"code": null,
"e": 93622,
"s": 93469,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 93677,
"s": 93622,
"text": "ValidationSummary(String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 93830,
"s": 93677,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 93893,
"s": 93830,
"text": "ValidationSummary(String, IDictionary<String, Object>, String)"
},
{
"code": null,
"e": 93939,
"s": 93893,
"text": "Overloaded. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 93973,
"s": 93939,
"text": "ValidationSummary(String, Object)"
},
{
"code": null,
"e": 94117,
"s": 93973,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 94159,
"s": 94117,
"text": "ValidationSummary(String, Object, String)"
},
{
"code": null,
"e": 94205,
"s": 94159,
"text": "Overloaded. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 94239,
"s": 94205,
"text": "ValidationSummary(String, String)"
},
{
"code": null,
"e": 94285,
"s": 94239,
"text": "Overloaded. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 94299,
"s": 94285,
"text": "Value(String)"
},
{
"code": null,
"e": 94451,
"s": 94299,
"text": "Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)"
},
{
"code": null,
"e": 94473,
"s": 94451,
"text": "Value(String, String)"
},
{
"code": null,
"e": 94625,
"s": 94473,
"text": "Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)"
},
{
"code": null,
"e": 94641,
"s": 94625,
"text": "ValueForModel()"
},
{
"code": null,
"e": 94793,
"s": 94641,
"text": "Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)"
},
{
"code": null,
"e": 94815,
"s": 94793,
"text": "ValueForModel(String)"
},
{
"code": null,
"e": 94967,
"s": 94815,
"text": "Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)"
},
{
"code": null,
"e": 95220,
"s": 94967,
"text": "If you look at the view from the last chapter which we have generated from EmployeeController index action, you will see the number of operations that started with Html, like Html.ActionLink and Html.DisplayNameFor, etc. as shown in the following code."
},
{
"code": null,
"e": 96621,
"s": 95220,
"text": "@model IEnumerable<MVCSimpleApp.Models.Employee>\n@{\n Layout = null;\n} \n\n<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width\" />\n <title>Index</title>\n </head>\n\t\n <body>\n <p>\n @Html.ActionLink(\"Create New\", \"Create\")\n </p>\n\t\t\n <table class = \"table\">\n <tr>\n <th>\n @Html.DisplayNameFor(model => model.Name)\n </th>\n\t\t\t\t\n <th>\n @Html.DisplayNameFor(model => model.JoiningDate)\n </th>\n\t\t\t\t\n <th>\n @Html.DisplayNameFor(model => model.Age)\n </th>\n\t\t\t\t\n <th></th>\n </tr>\n\t\t\t\n @foreach (var item in Model) {\n <tr>\n <td>\n @Html.DisplayFor(modelItem => item.Name)\n </td>\n\t\t\t\t\t\n <td>\n @Html.DisplayFor(modelItem => item.JoiningDate)\n </td>\n\t\t\t\t\t\n <td>\n @Html.DisplayFor(modelItem => item.Age)\n </td>\n\t\t\t\t\t\n <td>\n @Html.ActionLink(\"Edit\", \"Edit\", new { id = item.ID }) |\n @Html.ActionLink(\"Details\", \"Details\", new { id = item.ID }) |\n @Html.ActionLink(\"Delete\", \"Delete\", new { id = item.ID })\n </td>\n </tr>\n }\n\t\t\t\n </table>\n </body>\n</html>"
},
{
"code": null,
"e": 96787,
"s": 96621,
"text": "This HTML is a property that we inherit from the ViewPage base class. So, it's available in all of our views and it returns an instance of a type called HTML Helper."
},
{
"code": null,
"e": 96965,
"s": 96787,
"text": "Let’s take a look at a simple example in which we will enable the user to edit the employee. Hence, this edit action will be using significant numbers of different HTML Helpers."
},
{
"code": null,
"e": 97054,
"s": 96965,
"text": "If you look at the above code, you will see at the end the following HTML Helper methods"
},
{
"code": null,
"e": 97110,
"s": 97054,
"text": "@Html.ActionLink(\"Edit\", \"Edit\", new { id = item.ID })\n"
},
{
"code": null,
"e": 97346,
"s": 97110,
"text": "In the ActionLink helper, the first parameter is of the link which is “Edit”, the second parameter is the action method in the Controller, which is also “Edit”, and the third parameter ID is of any particular employee you want to edit."
},
{
"code": null,
"e": 97471,
"s": 97346,
"text": "Let’s change the EmployeeController class by adding a static list and also change the index action using the following code."
},
{
"code": null,
"e": 98216,
"s": 97471,
"text": "public static List<Employee> empList = new List<Employee>{\n new Employee{\n ID = 1,\n Name = \"Allan\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 23\n },\n\t\n new Employee{\n ID = 2,\n Name = \"Carson\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 45\n },\n\t\n new Employee{\n ID = 3,\n Name = \"Carson\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 37\n },\n\t\n new Employee{\n ID = 4,\n Name = \"Laura\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 26\n },\n\t\n};\n\npublic ActionResult Index(){\n var employees = from e in empList\n orderby e.ID\n select e;\n return View(employees);\n}"
},
{
"code": null,
"e": 98411,
"s": 98216,
"text": "Let’s update the Edit action. You will see two Edit actions one for GET and one for POST. Let’s update the Edit action for Get, which has only Id in the parameter as shown in the following code."
},
{
"code": null,
"e": 98595,
"s": 98411,
"text": "// GET: Employee/Edit/5\npublic ActionResult Edit(int id){\n List<Employee> empList = GetEmployeeList();\n var employee = empList.Single(m => m.ID == id);\n return View(employee);\n}"
},
{
"code": null,
"e": 98781,
"s": 98595,
"text": "Now, we know that we have action for Edit but we don’t have any view for these actions. So we need to add a View as well. To do this, right-click on the Edit action and select Add View."
},
{
"code": null,
"e": 98904,
"s": 98781,
"text": "You will see the default name for view. Select Edit from the Template dropdown and Employee from the Model class dropdown."
},
{
"code": null,
"e": 98962,
"s": 98904,
"text": "Following is the default implementation in the Edit view."
},
{
"code": null,
"e": 101632,
"s": 98962,
"text": "@model MVCSimpleApp.Models.Employee\n@{\n Layout = null;\n}\n\n<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width\" />\n <title>Edit</title>\n </head>\n\t\n <body>\n @using (Html.BeginForm()){\n @Html.AntiForgeryToken()\n <div class = \"form-horizontal\">\n <h4>Employee</h4>\n <hr />\n @Html.ValidationSummary(\n true, \"\", new { @class = \"text-danger\" })\n\t\t\t\t\t\n @Html.HiddenFor(model => model.ID)\n\t\t\t\t\n <div class = \"form-group\">\n @Html.LabelFor(\n model => model.Name, htmlAttributes: new{\n @class = \"control-label col-md-2\" })\n\t\t\t\t\t\t\t\n <div class = \"col-md-10\">\n @Html.EditorFor(model => model.Name, new{\n htmlAttributes = new {\n @class = \"form-control\" } })\n\t\t\t\t\t\t\t\t\n @Html.ValidationMessageFor(model => model.Name, \"\", new{\n @class = \"text-danger\" })\n </div>\n\t\t\t\t\t\n </div>\n\t\t\t\t\n <div class = \"form-group\">\n @Html.LabelFor(\n model => model.JoiningDate, htmlAttributes: new{\n @class = \"control-label col-md-2\" })\n\t\t\t\t\t\t\t\n <div class = \"col-md-10\">\n @Html.EditorFor(\n model => model.JoiningDate, new{\n htmlAttributes = new{ @class = \"form-control\" } })\n\t\t\t\t\t\t\t\t\n @Html.ValidationMessageFor(\n model => model.JoiningDate, \"\", new{\n @class = \"text-danger\" })\n </div>\n\t\t\t\t\t\n </div>\n\t\t\t\t\n <div class = \"form-group\">\n @Html.LabelFor(\n model => model.Age, htmlAttributes: new{\n @class = \"control-label col-md-2\" })\n\t\t\t\t\t\t\t\n <div class = \"col-md-10\">\n @Html.EditorFor(\n model => model.Age, new{\n htmlAttributes = new{ @class = \"form-control\" } })\n\t\t\t\t\t\t\t\t\n @Html.ValidationMessageFor(\n model => model.Age, \"\", new{\n @class = \"text-danger\" })\n </div>\n\t\t\t\t\t\n </div>\n\t\t\t\t\n <div class = \"form-group\">\n <div class = \"col-md-offset-2 col-md-10\">\n <input type = \"submit\" value = \"Save\" class = \"btn btn-default\"/>\n </div>\n </div>\n\t\t\t\t\n </div>\n }\n\t\t\n <div>\n @Html.ActionLink(\"Back to List\", \"Index\")\n </div>\n\t\t\n </body>\n</html>"
},
{
"code": null,
"e": 101840,
"s": 101632,
"text": "As you can see that there are many helper methods used. So, here “HTML.BeginForm” writes an opening Form Tag. It also ensures that the method is going to be “Post”, when the user clicks on the “Save” button."
},
{
"code": null,
"e": 101937,
"s": 101840,
"text": "Html.BeginForm is very useful, because it enables you to change the URL, change the method, etc."
},
{
"code": null,
"e": 102051,
"s": 101937,
"text": "In the above code, you will see one more HTML helper and that is “@HTML.HiddenFor”, which emits the hidden field."
},
{
"code": null,
"e": 102238,
"s": 102051,
"text": "MVC Framework is smart enough to figure out that this ID field is mentioned in the model class and hence it needs to be prevented from getting edited, that is why it is marked as hidden."
},
{
"code": null,
"e": 102425,
"s": 102238,
"text": "The Html.LabelFor HTML Helper creates the labels on the screen. The Html.ValidationMessageFor helper displays proper error message if anything is wrongly entered while making the change."
},
{
"code": null,
"e": 102541,
"s": 102425,
"text": "We also need to change the Edit action for POST because once you update the employee then it will call this action."
},
{
"code": null,
"e": 102889,
"s": 102541,
"text": "// POST: Employee/Edit/5\n[HttpPost]\npublic ActionResult Edit(int id, FormCollection collection){\n try{\n var employee = empList.Single(m => m.ID == id);\n if (TryUpdateModel(employee)){\n //To Do:- database code\n return RedirectToAction(\"Index\");\n }\n return View(employee);\n }catch{\n return View();\n }\n}"
},
{
"code": null,
"e": 103022,
"s": 102889,
"text": "Let’s run this application and request for the following URL http://localhost:63004/employee. You will receive the following output."
},
{
"code": null,
"e": 103142,
"s": 103022,
"text": "Click on the edit link on any particular employee, let’s say click on Allan edit link. You will see the following view."
},
{
"code": null,
"e": 103255,
"s": 103142,
"text": "Let’s change the age from 23 to 29 and click ‘Save’ button, then you will see the updated age on the Index View."
},
{
"code": null,
"e": 103674,
"s": 103255,
"text": "ASP.NET MVC model binding allows you to map HTTP request data with a model. It is the process of creating .NET objects using the data sent by the browser in an HTTP request. The ASP.NET Web Forms developers who are new to ASP.Net MVC are mostly confused how the values from View get converted to the Model class when it reaches the Action method of the Controller class, so this conversion is done by the Model binder."
},
{
"code": null,
"e": 103983,
"s": 103674,
"text": "Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene."
},
{
"code": null,
"e": 104185,
"s": 103983,
"text": "Let’s take a look at a simple example in which we add a ‘Create View’ in our project from the last chapter and we will see how we get these values from the View to the EmployeeController action method."
},
{
"code": null,
"e": 104233,
"s": 104185,
"text": "Following is the Create Action method for POST."
},
{
"code": null,
"e": 104448,
"s": 104233,
"text": "// POST: Employee/Create\n[HttpPost]\npublic ActionResult Create(FormCollection collection){\n try{\n // TODO: Add insert logic here\n return RedirectToAction(\"Index\");\n }catch{\n return View();\n }\n}"
},
{
"code": null,
"e": 104511,
"s": 104448,
"text": "Right-click on the Create Action method and select Add View..."
},
{
"code": null,
"e": 104548,
"s": 104511,
"text": "It will display the Add View dialog."
},
{
"code": null,
"e": 104716,
"s": 104548,
"text": "As you can see in the above screenshot, the default name is already mentioned. Now select Create from the Template dropdown and Employee from the Model class dropdown."
},
{
"code": null,
"e": 104773,
"s": 104716,
"text": "You will see the default code in the Create.cshtml view."
},
{
"code": null,
"e": 107145,
"s": 104773,
"text": "@model MVCSimpleApp.Models.Employee\n@{\n Layout = null;\n}\n\n<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width\" />\n <title>Create</title>\n </head>\n\t\n <body>\n @using (Html.BeginForm()){\n @Html.AntiForgeryToken()\n <div class = \"form-horizontal\">\n <h4>Employee</h4>\n <hr />\n @Html.ValidationSummary(true, \"\", new { @class = \"text-danger\" })\n\t\t\t\t\n <div class = \"form-group\">\n @Html.LabelFor(model => model.Name, htmlAttributes:\n new{ @class = \"control-label col-md-2\" })\n\t\t\t\t\t\t\n <div class = \"col-md-10\">\n @Html.EditorFor(model => model.Name, new{ htmlAttributes =\n new { @class = \"form-control\" } })\n\t\t\t\t\t\t\t\n @Html.ValidationMessageFor(model => model.Name, \"\",\n new{ @class = \"text-danger\" })\n </div>\n </div>\n\t\t\t\t\n <div class = \"form-group\">\n @Html.LabelFor(model => model.JoiningDate, htmlAttributes:\n new{ @class = \"control-label col-md-2\" })\n\t\t\t\t\t\t\n <div class = \"col-md-10\">\n @Html.EditorFor(model => model.JoiningDate, new{ htmlAttributes =\n new { @class = \"form-control\" } })\n\t\t\t\t\t\t\t\n @Html.ValidationMessageFor(model => model.JoiningDate, \"\",\n new { @class = \"text-danger\" })\n </div>\n </div>\n\t\t\t\t\n <div class = \"form-group\">\n @Html.LabelFor(model => model.Age, htmlAttributes:\n new { @class = \"control-label col-md-2\" })\n\t\t\t\t\t\t\n <div class = \"col-md-10\">\n @Html.EditorFor(model => model.Age, new { htmlAttributes =\n new { @class = \"form-control\" } })\n\t\t\t\t\t\t\t\n @Html.ValidationMessageFor(model => model.Age, \"\", new{ @class = \"text-danger\" })\n </div>\n </div>\n\t\t\t\t\n <div class = \"form-group\">\n <div class = \"col-md-offset-2 col-md-10\">\n <input type = \"submit\" value = \"Create\" class = \"btn btn-default\"/>\n </div>\n </div>\n\t\t\t\t\n </div>\n }\n\t\t\n <div>\n @Html.ActionLink(\"Back to List\", \"Index\")\n </div>\n\t\t\n </body>\n</html>"
},
{
"code": null,
"e": 107328,
"s": 107145,
"text": "When the user enters values on Create View then it is available in FormCollection as well as Request.Form. We can use any of these values to populate the employee info from the view."
},
{
"code": null,
"e": 107402,
"s": 107328,
"text": "Let’s use the following code to create the Employee using FormCollection."
},
{
"code": null,
"e": 107860,
"s": 107402,
"text": "// POST: Employee/Create\n[HttpPost]\npublic ActionResult Create(FormCollection collection){\n try {\n Employee emp = new Employee();\n emp.Name = collection[\"Name\"];\n DateTime jDate;\n DateTime.TryParse(collection[\"DOB\"], out jDate);\n emp.JoiningDate = jDate;\n string age = collection[\"Age\"];\n emp.Age = Int32.Parse(age);\n empList.Add(emp);\n return RedirectToAction(\"Index\");\n }catch {\n return View();\n }\n}"
},
{
"code": null,
"e": 107979,
"s": 107860,
"text": "Run this application and request for this URL http://localhost:63004/Employee/. You will receive the following output."
},
{
"code": null,
"e": 108064,
"s": 107979,
"text": "Click the ‘Create New’ link on top of the page and it will go to the following view."
},
{
"code": null,
"e": 108119,
"s": 108064,
"text": "Let’s enter data for another employee you want to add."
},
{
"code": null,
"e": 108208,
"s": 108119,
"text": "Click on the create button and you will see that the new employee is added in your list."
},
{
"code": null,
"e": 108374,
"s": 108208,
"text": "In the above example, we are getting all the posted values from the HTML view and then mapping these values to the Employee properties and assigning them one by one."
},
{
"code": null,
"e": 108507,
"s": 108374,
"text": "In this case, we will also be doing the type casting wherever the posted values are not of the same format as of the Model property."
},
{
"code": null,
"e": 108776,
"s": 108507,
"text": "This is also known as manual binding and this type of implementation might not be that bad for simple and small data model. However, if you have huge data models and need a lot of type casting then we can utilize the power and ease-of-use of ASP.NET MVC Model binding."
},
{
"code": null,
"e": 108840,
"s": 108776,
"text": "Let’s take a look at the same example we did for Model binding."
},
{
"code": null,
"e": 108984,
"s": 108840,
"text": "We need to change the parameter of Create Method to accept the Employee Model object rather than FormCollection as shown in the following code."
},
{
"code": null,
"e": 109173,
"s": 108984,
"text": "// POST: Employee/Create\n[HttpPost]\npublic ActionResult Create(Employee emp){\n try{\n empList.Add(emp);\n return RedirectToAction(\"Index\");\n }catch{\n return View();\n }\n}"
},
{
"code": null,
"e": 109271,
"s": 109173,
"text": "Now the magic of Model Binding depends on the id of HTML variables that are supplying the values."
},
{
"code": null,
"e": 109494,
"s": 109271,
"text": "For our Employee Model, the id of the HTML input fields should be the same as the Property names of the Employee Model and you can see that Visual Studio is using the same property names of the model while creating a view."
},
{
"code": null,
"e": 109590,
"s": 109494,
"text": "@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = \"form-control\" } })\n"
},
{
"code": null,
"e": 109822,
"s": 109590,
"text": "The mapping will be based on the Property name by default. This is where we will find HTML helper methods very helpful because these helper methods will generate the HTML, which will have proper Names for the Model Binding to work."
},
{
"code": null,
"e": 109936,
"s": 109822,
"text": "Run this application and request for the URL http://localhost:63004/Employee/. You will see the following output."
},
{
"code": null,
"e": 110032,
"s": 109936,
"text": "Let’s click on the Create New link on the top of the page and it will go to the following view."
},
{
"code": null,
"e": 110091,
"s": 110032,
"text": "Let’s enter data for another employee that we want to add."
},
{
"code": null,
"e": 110217,
"s": 110091,
"text": "Now click the create button and you will see that the new employee is added to your list using the ASP.Net MVC model binding."
},
{
"code": null,
"e": 110568,
"s": 110217,
"text": "In all ASP.NET MVC applications created in this tutorial we have been passing hard-coded data from the Controllers to the View templates. But, in order to build a real Web application, you might want to use a real database. In this chapter, we will see how to use a database engine in order to store and retrieve the data needed for your application."
},
{
"code": null,
"e": 110710,
"s": 110568,
"text": "To store and retrieve data, we will use a .NET Framework data-access technology known as the Entity Framework to define and work with Models."
},
{
"code": null,
"e": 110961,
"s": 110710,
"text": "The Entity Framework (EF) supports Code First technique, which allows you to create model objects by writing simple classes and then the database will be created on the fly from your classes, which enables a very clean and rapid development workflow."
},
{
"code": null,
"e": 111065,
"s": 110961,
"text": "Let’s take a look at a simple example in which we will add support for Entity framework in our example."
},
{
"code": null,
"e": 111208,
"s": 111065,
"text": "Step 1 − To install the Entity Framework, right-click on your project and select NuGet Package Manager → Manage NuGet Packages for Solution..."
},
{
"code": null,
"e": 111295,
"s": 111208,
"text": "It will open the NuGet Package Manager. Search for Entity framework in the search box."
},
{
"code": null,
"e": 111384,
"s": 111295,
"text": "Select the Entity Framework and click ‘Install’ button. It will open the Preview dialog."
},
{
"code": null,
"e": 111406,
"s": 111384,
"text": "Click Ok to continue."
},
{
"code": null,
"e": 111457,
"s": 111406,
"text": "Click the ‘I Accept’ button to start installation."
},
{
"code": null,
"e": 111568,
"s": 111457,
"text": "Once the Entity Framework is installed you will see the message in out window as seen in the above screenshot."
},
{
"code": null,
"e": 111721,
"s": 111568,
"text": "We need to add another class to the Employee Model, which will communicate with Entity Framework to retrieve and save the data using the following code."
},
{
"code": null,
"e": 112194,
"s": 111721,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Data.Entity;\nusing System.Linq;\n\nusing System.Web;\n\nnamespace MVCSimpleApp.Models{\n public class Employee{\n public int ID { get; set; }\n public string Name { get; set; }\n public DateTime JoiningDate { get; set; }\n public int Age { get; set; }\n }\n\t\n public class EmpDBContext : DbContext{\n public EmpDBContext()\n { }\n public DbSet<Employee> Employees { get; set; }\n }\n}"
},
{
"code": null,
"e": 112393,
"s": 112194,
"text": "As seen above, EmpDBContext is derived from an EF class known as DbContext. In this class, we have one property with the name DbSet, which basically represents the entity you want to query and save."
},
{
"code": null,
"e": 112501,
"s": 112393,
"text": "We need to specify the connection string under <configuration> tag for our database in the Web.config file."
},
{
"code": null,
"e": 112775,
"s": 112501,
"text": "<connectionStrings>\n <add name = \"EmpDBContext\" connectionString = \"Data\n Source = (LocalDb)\\v14.0;AttachDbFilename = |DataDirectory|\\EmpDB.mdf;Initial\n Catalog = EmployeeDB;Integrated Security = SSPI;\"\n providerName = \"System.Data.SqlClient\"/>\n</connectionStrings>"
},
{
"code": null,
"e": 113084,
"s": 112775,
"text": "You don't actually need to add the EmpDBContext connection string. If you don't specify a connection string, Entity Framework will create localDB database in the user’s directory with the fully qualified name of the DbContext class. For this demo, we will not add the connection string to make things simple."
},
{
"code": null,
"e": 113235,
"s": 113084,
"text": "Now we need to update the EmployeeController.cs file so that we can actually save and retrieve data from the database instead of using hardcoded data."
},
{
"code": null,
"e": 113381,
"s": 113235,
"text": "First we add create a private EmpDBContext class object and then update the Index, Create and Edit action methods as shown in the following code."
},
{
"code": null,
"e": 114822,
"s": 113381,
"text": "using MVCSimpleApp.Models;\nusing System.Linq;\nusing System.Web.Mvc;\n\nnamespace MVCSimpleApp.Controllers {\n public class EmployeeController : Controller{\n private EmpDBContext db = new EmpDBContext();\n // GET: Employee\n\t\t\n public ActionResult Index(){\n var employees = from e in db.Employees\n orderby e.ID\n select e;\n return View(employees);\n }\n\t\t\n // GET: Employee/Create\n public ActionResult Create(){\n return View();\n }\n\t\t\n // POST: Employee/Create\n [HttpPost]\n public ActionResult Create(Employee emp){\n try{\n db.Employees.Add(emp);\n db.SaveChanges();\n return RedirectToAction(\"Index\");\n }catch{\n return View();\n }\n }\n\t\t\n // GET: Employee/Edit/5\n public ActionResult Edit(int id){\n var employee = db.Employees.Single(m => m.ID == id);\n return View(employee);\n }\n\t\t\n // POST: Employee/Edit/5\n [HttpPost]\n public ActionResult Edit(int id, FormCollection collection){\n try{\n var employee = db.Employees.Single(m => m.ID == id);\n if (TryUpdateModel(employee)){\n //To Do:- database code\n db.SaveChanges();\n return RedirectToAction(\"Index\");\n }\n return View(employee);\n }catch{\n return View();\n }\n }\n }\n}"
},
{
"code": null,
"e": 114942,
"s": 114822,
"text": "Then we run this application with the following URL http://localhost:63004/Employee. You will see the following output."
},
{
"code": null,
"e": 115090,
"s": 114942,
"text": "As you can see that there is no data on the view, this is because we have not added any records in our database, which is created by Visual Studio."
},
{
"code": null,
"e": 115225,
"s": 115090,
"text": "Let’s go to the SQL Server Object Explorer, you will see the database is created with the same name as we have in our DBContext class."
},
{
"code": null,
"e": 115358,
"s": 115225,
"text": "Let’s expand this database and you will see that it has one table which contains all the fields we have in our Employee model class."
},
{
"code": null,
"e": 115446,
"s": 115358,
"text": "To see the data in this table, right-click on the Employees table and select View Data."
},
{
"code": null,
"e": 115498,
"s": 115446,
"text": "You will see that we have no records at the moment."
},
{
"code": null,
"e": 115584,
"s": 115498,
"text": "Let’s add some records in the database directly as shown in the following screenshot."
},
{
"code": null,
"e": 115677,
"s": 115584,
"text": "Refresh the browser and you will see that data is now updated to the view from the database."
},
{
"code": null,
"e": 115783,
"s": 115677,
"text": "Let’s add one record from the browser by clicking the ‘Create New’ link. It will display the Create view."
},
{
"code": null,
"e": 115827,
"s": 115783,
"text": "Let’s add some data in the following field."
},
{
"code": null,
"e": 115933,
"s": 115827,
"text": "Click on the Create button and it will update the Index view as well add this new record to the database."
},
{
"code": null,
"e": 116131,
"s": 115933,
"text": "Now let’s go the SQL Server Object Explorer and refresh the database. Right-click on the Employees table and select the View data menu option. You will see that the record is added in the database."
},
{
"code": null,
"e": 116425,
"s": 116131,
"text": "Validation is an important aspect in ASP.NET MVC applications. It is used to check whether the user input is valid. ASP.NET MVC provides a set of validation that is easy-to-use and at the same time, it is also a powerful way to check for errors and, if necessary, display messages to the user."
},
{
"code": null,
"e": 116694,
"s": 116425,
"text": "DRY stands for Don't Repeat Yourself and is one of the core design principles of ASP.NET MVC. From the development point of view, it is encouraged to specify functionality or behavior only at one place and then it is used in the entire application from that one place."
},
{
"code": null,
"e": 116817,
"s": 116694,
"text": "This reduces the amount of code you need to write and makes the code you do write less error prone and easier to maintain."
},
{
"code": null,
"e": 117195,
"s": 116817,
"text": "Let’s take a look at a simple example of validation in our project from the last chapter. In this example, we will add data annotations to our model class, which provides some builtin set of validation attributes that can be applied to any model class or property directly in your application, such as Required, StringLength, RegularExpression, and Range validation attributes."
},
{
"code": null,
"e": 117421,
"s": 117195,
"text": "It also contains formatting attributes like DataType that help with formatting and don't provide any validation. The validation attributes specify behavior that you want to enforce on the model properties they are applied to."
},
{
"code": null,
"e": 117669,
"s": 117421,
"text": "The Required and MinimumLength attributes indicates that a property must have a value; but nothing prevents a user from entering white space to satisfy this validation. The RegularExpression attribute is used to limit what characters can be input."
},
{
"code": null,
"e": 117771,
"s": 117669,
"text": "Let’s update Employee class by adding different annotation attributes as shown in the following code."
},
{
"code": null,
"e": 118316,
"s": 117771,
"text": "using System;\nusing System.ComponentModel.DataAnnotations;\nusing System.Data.Entity;\n\nnamespace MVCSimpleApp.Models {\n public class Employee{\n public int ID { get; set; }\n [StringLength(60, MinimumLength = 3)]\n\t\t\n public string Name { get; set; }\n [Display(Name = \"Joining Date\")]\n [DataType(DataType.Date)]\n [DisplayFormat(DataFormatString = \"{0:yyyy-MM-dd}\",\n\t\t\n ApplyFormatInEditMode = true)]\n public DateTime JoiningDate { get; set; }\n [Range(22, 60)]\n public int Age { get; set; }\n }\n}"
},
{
"code": null,
"e": 118502,
"s": 118316,
"text": "Now we also need to set limits to the database. However, the database in SQL Server Object Explorer shows the name property is set to NVARCHAR (MAX) as seen in the following screenshot."
},
{
"code": null,
"e": 118587,
"s": 118502,
"text": "To set this limitation on the database, we will use migrations to update the schema."
},
{
"code": null,
"e": 118689,
"s": 118587,
"text": "Open the Package Manager Console window from Tools → NuGet Package Manager → Package Manager Console."
},
{
"code": null,
"e": 118768,
"s": 118689,
"text": "Enter the following commands one by one in the Package Manager Console window."
},
{
"code": null,
"e": 118833,
"s": 118768,
"text": "Enable-Migrations\nadd-migration DataAnnotations\nupdate-database\n"
},
{
"code": null,
"e": 118920,
"s": 118833,
"text": "Following is the log after executing these commands in Package Manager Console window."
},
{
"code": null,
"e": 119083,
"s": 118920,
"text": "Visual Studio will also open the class which is derived from the DbMIgration class in which you can see the code that updates the schema constraints in Up method."
},
{
"code": null,
"e": 119468,
"s": 119083,
"text": "namespace MVCSimpleApp.Migrations {\n using System;\n using System.Data.Entity.Migrations;\n\t\n public partial class DataAnnotations : DbMigration{\n public override void Up(){\n AlterColumn(\"dbo.Employees\", \"Name\", c => c.String(maxLength: 60));\n }\n\t\t\n public override void Down(){\n AlterColumn(\"dbo.Employees\", \"Name\", c => c.String());\n }\n }\n}"
},
{
"code": null,
"e": 119594,
"s": 119468,
"text": "The Name field has a maximum length of 60, which is the new length limits in the database as shown in the following snapshot."
},
{
"code": null,
"e": 119709,
"s": 119594,
"text": "Run this application and go to Create view by specifying the following URL http://localhost:63004/Employees/Create"
},
{
"code": null,
"e": 119817,
"s": 119709,
"text": "Let’s enter some invalid data in these fields and click Create Button as shown in the following screenshot."
},
{
"code": null,
"e": 119923,
"s": 119817,
"text": "You will see that jQuery client side validation detects the error, and it also displays an error message."
},
{
"code": null,
"e": 120207,
"s": 119923,
"text": "In this chapter, we will discuss how to implement security features in the application. We will also look at the new membership features included with ASP.NET and available for use from ASP.NET MVC. In the latest release of ASP.NET, we can manage user identities with the following −"
},
{
"code": null,
"e": 120213,
"s": 120207,
"text": "Cloud"
},
{
"code": null,
"e": 120226,
"s": 120213,
"text": "SQL database"
},
{
"code": null,
"e": 120257,
"s": 120226,
"text": "Local Windows active directory"
},
{
"code": null,
"e": 120417,
"s": 120257,
"text": "In this chapter, we will also take a look at the new identity components that is a part of ASP.NET and see how to customize membership for our users and roles."
},
{
"code": null,
"e": 120604,
"s": 120417,
"text": "Authentication of user means verifying the identity of the user. This is really important. You might need to present your application only to the authenticated users for obvious reasons."
},
{
"code": null,
"e": 120648,
"s": 120604,
"text": "Let’s create a new ASP.Net MVC application."
},
{
"code": null,
"e": 120670,
"s": 120648,
"text": "Click OK to continue."
},
{
"code": null,
"e": 120810,
"s": 120670,
"text": "When you start a new ASP.NET application, one of the steps in the process is configuring the authentication services for application needs."
},
{
"code": null,
"e": 120901,
"s": 120810,
"text": "Select MVC template and you will see that the Change Authentication button is now enabled."
},
{
"code": null,
"e": 121049,
"s": 120901,
"text": "This is done with the Change Authentication button that appears in the New Project dialog. The default authentication is, Individual User Accounts."
},
{
"code": null,
"e": 121146,
"s": 121049,
"text": "When you click the Change button, you will see a dialog with four options, which are as follows."
},
{
"code": null,
"e": 121281,
"s": 121146,
"text": "The first option is No Authentication and this option is used when you want to build a website that doesn't care who the visitors are."
},
{
"code": null,
"e": 121495,
"s": 121281,
"text": "It is open to anyone and every person connects as every single page. You can always change that later, but the No Authentication option means there will not be any features to identify users coming to the website."
},
{
"code": null,
"e": 121792,
"s": 121495,
"text": "The second option is Individual User Accounts and this is the traditional forms-based authentication where users can visit a website. They can register, create a login, and by default their username is stored in a SQL Server database using some new ASP.NET identity features, which we'll look at."
},
{
"code": null,
"e": 121965,
"s": 121792,
"text": "The password is also stored in the database, but it is hashed first. Since the password is hashed, you don't have to worry about plain-text passwords sitting in a database."
},
{
"code": null,
"e": 122241,
"s": 121965,
"text": "This option is typically used for internet sites where you want to establish the identity of a user. In addition to letting a user create a local login with a password for your site, you can also enable logins from third parties like Microsoft, Google, Facebook, and Twitter."
},
{
"code": null,
"e": 122413,
"s": 122241,
"text": "This allows a user to log into your site using their Live account or their Twitter account and they can select a local username, but you don't need to store any passwords."
},
{
"code": null,
"e": 122517,
"s": 122413,
"text": "This is the option that we'll spend some time with in this module; the individual user accounts option."
},
{
"code": null,
"e": 122683,
"s": 122517,
"text": "The third option is to use organizational accounts and this is typically used for business applications where you will be using active directory federation services."
},
{
"code": null,
"e": 122821,
"s": 122683,
"text": "You will either set up Office 365 or use Azure Active Directory Services, and you have a single sign-on for internal apps and Cloud apps."
},
{
"code": null,
"e": 123075,
"s": 122821,
"text": "You will also need to provide an app ID so your app will need to be registered with the Windows Azure management portal if this is Azure based, and the app ID will uniquely identify this application amongst all the applications that might be registered."
},
{
"code": null,
"e": 123164,
"s": 123075,
"text": "The fourth option is Windows authentication, which works well for intranet applications."
},
{
"code": null,
"e": 123506,
"s": 123164,
"text": "A user logs into Windows desktop and can launch a browser to the application that sits inside the same firewall. ASP.NET can automatically pick up the user's identity, the one that was established by active directory. This option does not allow any anonymous access to the site, but again that is a configuration setting that can be changed."
},
{
"code": null,
"e": 123795,
"s": 123506,
"text": "Let's take a look into the forms-based authentication, the one that goes by the name, Individual User Accounts. This application will store usernames and passwords, old passwords in a local SQL Server database, and when this project is created, Visual Studio will also add NuGet packages."
},
{
"code": null,
"e": 123895,
"s": 123795,
"text": "Now run this application and when you first come to this application you will be an anonymous user."
},
{
"code": null,
"e": 123990,
"s": 123895,
"text": "You won't have an account that you can log into yet so you will need to register on this site."
},
{
"code": null,
"e": 124054,
"s": 123990,
"text": "Click on the Register link and you will see the following view."
},
{
"code": null,
"e": 124088,
"s": 124054,
"text": "Enter your email id and password."
},
{
"code": null,
"e": 124145,
"s": 124088,
"text": "Click Register. Now, the application will recognize you."
},
{
"code": null,
"e": 124356,
"s": 124145,
"text": "It will be able to display your name. In the following screenshot, you can see Hello, [email protected]! is displayed. You can click on that and it's a link to a page where you can change the password."
},
{
"code": null,
"e": 124570,
"s": 124356,
"text": "You can also log off, shut down, reboot, come back a week later, and you should be able to log in with the credentials that you used earlier. Now click on the log off button and it will display the following page."
},
{
"code": null,
"e": 124640,
"s": 124570,
"text": "Click again on the Log in link and you will go to the following page."
},
{
"code": null,
"e": 124687,
"s": 124640,
"text": "You can login again with the same credentials."
},
{
"code": null,
"e": 124939,
"s": 124687,
"text": "A lot of work goes on behind the scene to get to this point. However, what we want to do is examine each of the features and see how this UI is built. What is managing the logoff and the login process? Where is this information sorted in the database?"
},
{
"code": null,
"e": 125116,
"s": 124939,
"text": "Let's just start with a couple of simple basics. First we will see how is this username displayed. Open the _Layout.cshtml from the View/Shared folder in the Solution explorer."
},
{
"code": null,
"e": 126869,
"s": 125116,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"utf-8\" />\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\">\n <title>@ViewBag.Title - My ASP.NET Application</title>\n @Styles.Render(\"~/Content/css\")\n @Scripts.Render(\"~/bundles/modernizr\")\n </head>\n\t\n <body>\n <div class = \"navbar navbar-inverse navbar-fixed-top\">\n <div class = \"container\">\n\t\t\t\n <div class = \"navbar-header\">\n <button type = \"button\" class = \"navbar-toggle\" datatoggle = \"collapse\"\n data-target = \".navbar-collapse\">\n <span class = \"icon-bar\"></span>\n <span class = \"icon-bar\"></span>\n <span class = \"icon-bar\"></span>\n </button>\n\t\t\t\t\t\n @Html.ActionLink(\"Application name\", \"Index\", \"Home\", new\n { area = \"\" }, new { @class = \"navbar-brand\" })\n </div>\n\t\t\t\t\n <div class = \"navbar-collapse collapse\">\n <ul class = \"nav navbar-nav\">\n <li>@Html.ActionLink(\"Home\", \"Index\", \"Home\")</li>\n <li>@Html.ActionLink(\"About\", \"About\", \"Home\")</li>\n <li>@Html.ActionLink(\"Contact\", \"Contact\", \"Home\")</li>\n </ul>\n\t\t\t\t\t\n @Html.Partial(\"_LoginPartial\")\n </div>\n\t\t\t\t\n </div>\n\t\t\t\n </div>\n <div class = \"container body-content\">\n @RenderBody()\n <hr />\n <footer>\n <p>© @DateTime.Now.Year - My ASP.NET Application</p>\n </footer>\n </div>\n\t\t\n @Scripts.Render(\"~/bundles/jquery\")\n @Scripts.Render(\"~/bundles/bootstrap\")\n @RenderSection(\"scripts\", required: false)\n\t\t\n </body>\n</html>"
},
{
"code": null,
"e": 127145,
"s": 126869,
"text": "There is a common navigation bar, the application name, the menu, and there is a partial view that's being rendered called _loginpartial. That's actually the view that displays the username or the register and login name. So _loginpartial.cshtml is also in the shared folder."
},
{
"code": null,
"e": 128131,
"s": 127145,
"text": "@using Microsoft.AspNet.Identity\n@if (Request.IsAuthenticated) {\n using (Html.BeginForm(\"LogOff\", \"Account\", FormMethod.Post,\n new { id = \"logoutForm\", @class = \"navbar-right\" })){\n @Html.AntiForgeryToken()\n <ul class = \"nav navbar-nav navbar-right\">\n <li>\n @Html.ActionLink(\"Hello \" + User.Identity.GetUserName() + \"!\",\n \"Index\", \"Manage\", routeValues: null, htmlAttributes: new { title = \"Manage\" })\n </li>\n\t\t\t\t\n <li>\n <a href = \"javascript:document.getElementById('logoutForm').submit()\">Logoff</a>\n </li>\n\t\t\t\t\n </ul>\n }\n}else{\n <ul class = \"nav navbar-nav navbar-right\">\n <li>@Html.ActionLink(\"Register\", \"Register\", \"Account\", routeValues:\n null, htmlAttributes: new { id = \"registerLink\" })</li>\n\t\t\t\n <li>@Html.ActionLink(\"Log in\", \"Login\", \"Account\", routeValues: null,\n htmlAttributes: new { id = \"loginLink\" })</li>\n </ul>\n}"
},
{
"code": null,
"e": 128407,
"s": 128131,
"text": "As you can see above, there are if/else statements. If we do not know who the user is, because the request is not authenticated, this view will display register and login links. The user can click on the link to log in or register. All this is done by the account controller."
},
{
"code": null,
"e": 128632,
"s": 128407,
"text": "For now, we want to see how to get the username, and that's inside Request.IsAuthenticated. You can see a call to User.Identity.GetUserName. That will retrieve the username, which in this case is ‘[email protected]’"
},
{
"code": null,
"e": 128834,
"s": 128632,
"text": "Let's suppose that we have some sort of information which we want to protect from unauthenticated users. So let’s create a new controller to display that information, but only when a user is logged in."
},
{
"code": null,
"e": 128900,
"s": 128834,
"text": "Right-click on the controller folder and select Add → Controller."
},
{
"code": null,
"e": 128963,
"s": 128900,
"text": "Select an MVC 5 controller - Empty controller and click ‘Add’."
},
{
"code": null,
"e": 129019,
"s": 128963,
"text": "Enter the name SecretController and click ‘Add’ button."
},
{
"code": null,
"e": 129083,
"s": 129019,
"text": "It will have two actions inside as shown in the following code."
},
{
"code": null,
"e": 129423,
"s": 129083,
"text": "using System.Web.Mvc;\n\nnamespace MVCSecurityDemo.Controllers{\n public class SecretController : Controller{\n // GET: Secret\n public ContentResult Secret(){\n return Content(\"Secret informations here\");\n }\n\t\t\n public ContentResult PublicInfo(){\n return Content(\"Public informations here\");\n }\n }\n}"
},
{
"code": null,
"e": 129551,
"s": 129423,
"text": "When you run this application, you can access this information without any authentication as shown in the following screenshot."
},
{
"code": null,
"e": 129694,
"s": 129551,
"text": "So only authenticated users should be able to get to Secret action method and the PublicInfo can be used by anyone without any authentication."
},
{
"code": null,
"e": 129958,
"s": 129694,
"text": "To protect this particular action and keep unauthenticated users from arriving here, you can use the Authorize attribute. The Authorize attribute without any other parameters will make sure that the identity of the user is known and they're not an anonymous user."
},
{
"code": null,
"e": 130065,
"s": 129958,
"text": "// GET: Secret\n[Authorize]\npublic ContentResult Secret(){\n return Content(\"Secret informations here\");\n}"
},
{
"code": null,
"e": 130437,
"s": 130065,
"text": "Now run this application again and specify the same URL http://localhost:54232/Secret/Secret. The MVC application will detect that you do not have access to that particular area of the application and it will redirect you automatically to the login page, where it will give you a chance to log in and try to get back to that area of the application where you were denied."
},
{
"code": null,
"e": 130600,
"s": 130437,
"text": "You can see that it is specified in the return URL, which essentially tells this page that if the user logs in successfully, redirect them back to /secret/secret."
},
{
"code": null,
"e": 130699,
"s": 130600,
"text": "Enter your credentials and click ‘Log in’ button. You will see that it goes directly to that page."
},
{
"code": null,
"e": 130909,
"s": 130699,
"text": "If you come back to the home page and log off, you cannot get to the secret page. You will be asked again to log in, but if go to /Secret/PublicInfo, you can see that page, even when you are not authenticated."
},
{
"code": null,
"e": 131223,
"s": 130909,
"text": "So, when you don't want to be placing authorization on every action when you're inside a controller where pretty much everything requires authorization. In that case you can always apply this filter to the controller itself and now every action inside of this controller will require the user to be authenticated."
},
{
"code": null,
"e": 131578,
"s": 131223,
"text": "using System.Web.Mvc;\n\nnamespace MVCSecurityDemo.Controllers{\n [Authorize]\n public class SecretController : Controller{\n // GET: Secret\n public ContentResult Secret(){\n return Content(\"Secret informations here\");\n }\n\t\t\n public ContentResult PublicInfo(){\n return Content(\"Public informations here\");\n }\n }\n}"
},
{
"code": null,
"e": 131720,
"s": 131578,
"text": "But if you really want any action to be open, you can come override this authorization rule with another attribute, which is, AllowAnonymous."
},
{
"code": null,
"e": 132098,
"s": 131720,
"text": "using System.Web.Mvc;\n\nnamespace MVCSecurityDemo.Controllers{\n [Authorize]\n public class SecretController : Controller{\n // GET: Secret\n public ContentResult Secret(){\n return Content(\"Secret informations here\");\n }\n\t\t\n [AllowAnonymous]\n public ContentResult PublicInfo(){\n return Content(\"Public informations here\");\n }\n }\n}"
},
{
"code": null,
"e": 132223,
"s": 132098,
"text": "Run this application and you can access the /Secret/PublicInfo with logging in but other action will require authentication."
},
{
"code": null,
"e": 132280,
"s": 132223,
"text": "It will allow anonymous users into this one action only."
},
{
"code": null,
"e": 132397,
"s": 132280,
"text": "With the Authorize attribute, you can also specify some parameters, like allow some specific users into this action."
},
{
"code": null,
"e": 132807,
"s": 132397,
"text": "using System.Web.Mvc;\n\nnamespace MVCSecurityDemo.Controllers{\n [Authorize(Users = \"[email protected]\")]\n public class SecretController : Controller{\n // GET: Secret\n public ContentResult Secret(){\n return Content(\"Secret informations here\");\n }\n\t\t\n [AllowAnonymous]\n public ContentResult PublicInfo(){\n return Content(\"Public informations here\");\n }\n }\n}"
},
{
"code": null,
"e": 132944,
"s": 132807,
"text": "When you run this application and go to /secret/secret, it will ask you to log in because it is not the proper user for this controller."
},
{
"code": null,
"e": 133322,
"s": 132944,
"text": "In this chapter, we will be focusing on one of the most common ASP.NET techniques like Caching to improve the performance of the application. Caching means to store something in memory that is being used frequently to provide better performance. We will see how you can dramatically improve the performance of an ASP.NET MVC application by taking advantage of the output cache."
},
{
"code": null,
"e": 133542,
"s": 133322,
"text": "In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is the same concept as output caching in web forms. The output cache enables you to cache the content returned by a controller action."
},
{
"code": null,
"e": 133869,
"s": 133542,
"text": "Output caching basically allows you to store the output of a particular controller in the memory. Hence, any future request coming for the same action in that controller will be returned from the cached result. That way, the same content does not need to be generated each and every time the same controller action is invoked."
},
{
"code": null,
"e": 134211,
"s": 133869,
"text": "We need caching in many different scenarios to improve the performance of an application. For example, you have an ASP.NET MVC application, which displays a list employees. Now when these records are retrieved from the database by executing a database query each and every time a user invokes the controller action it returns the Index view."
},
{
"code": null,
"e": 134463,
"s": 134211,
"text": "Hence you can take advantage of the output cache to avoid executing a database query every time a user invokes the same controller action. In this case, the view will be retrieved from the cache instead of being regenerated from the controller action."
},
{
"code": null,
"e": 134533,
"s": 134463,
"text": "Caching enables you to avoid performing redundant work on the server."
},
{
"code": null,
"e": 134598,
"s": 134533,
"text": "Let’s take a look at a simple example of caching in our project."
},
{
"code": null,
"e": 134756,
"s": 134598,
"text": "[OutputCache(Duration = 60)]\npublic ActionResult Index(){\n var employees = from e in db.Employees\n orderby e.ID\n select e;\n return View(employees);\n}"
},
{
"code": null,
"e": 134991,
"s": 134756,
"text": "As you can see, we have added “OutputCache” attribute on the index action of the EmployeeController. Now to understand this concept, let us run this application in debugger mode and also insert a breakpoint in the Index action method."
},
{
"code": null,
"e": 135137,
"s": 134991,
"text": "Specify the following URL http://localhost:63004/employee, and press ‘Enter’. You will see that the breakpoint is hit in the Index action method."
},
{
"code": null,
"e": 135259,
"s": 135137,
"text": "Press ‘F5’ button to continue and you will see the list of employees on your view, which are retrieved from the database."
},
{
"code": null,
"e": 135603,
"s": 135259,
"text": "Refresh the browser again within 60 seconds and you will see that the breakpoint is not hit this time. This is because we have used output cache with duration of seconds. So it will cache this result for 60 seconds and when you refresh the browser, it will get the result from the cache, and it won’t load the content from the database server."
},
{
"code": null,
"e": 135804,
"s": 135603,
"text": "In addition to duration parameter, there are other settings options as well which you can use with output cache. These settings are not only for MVC framework but it is inherited from ASP.Net Caching."
},
{
"code": null,
"e": 135990,
"s": 135804,
"text": "In some cases, you might want different cached versions, such as, when you create a detail page, then when you click on the detailed link you will get details for the selected employee."
},
{
"code": null,
"e": 136137,
"s": 135990,
"text": "But first we need to create the detail view. For this, right-click on the Details action method from the EmployeeController and select Add View..."
},
{
"code": null,
"e": 136281,
"s": 136137,
"text": "You will see the Details name is selected by default. Now select Details from the Template dropdown and Employee from the Model class dropdown."
},
{
"code": null,
"e": 136342,
"s": 136281,
"text": "Click ‘Add’ to continue and you will see the Details.cshtml."
},
{
"code": null,
"e": 137420,
"s": 136342,
"text": "@model MVCSimpleApp.Models.Employee\n@{\n Layout = null;\n}\n\n<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width\" />\n <title>Details</title>\n </head>\n\t\n <body>\n <div>\n <h4>Employee</h4>\n <hr />\n <dl class = \"dl-horizontal\">\n <dt>\n @Html.DisplayNameFor(model => model.Name)\n </dt>\n\t\t\t\t\n <dd>\n @Html.DisplayFor(model => model.Name)\n </dd>\n\t\t\t\t\n <dt>\n @Html.DisplayNameFor(model => model.JoiningDate)\n </dt>\n\t\t\t\t\n <dd>\n @Html.DisplayFor(model => model.JoiningDate)\n </dd>\n\t\t\t\t\n <dt>\n @Html.DisplayNameFor(model => model.Age)\n </dt>\n\t\t\t\t\n <dd>\n @Html.DisplayFor(model => model.Age)\n </dd>\n\t\t\t\t\n </dl>\n </div>\n\t\t\n <p>\n @Html.ActionLink(\"Edit\", \"Edit\", new { id = Model.ID }) |\n @Html.ActionLink(\"Back to List\", \"Index\")\n </p>\n\t\t\n </body>\n</html>"
},
{
"code": null,
"e": 137697,
"s": 137420,
"text": "You can take advantage of the VaryByParam property of the [OutputCache] attribute. This property enables you to create different cached versions of the very same content when a form parameter or query string parameter varies. Following is the implementation of Details action."
},
{
"code": null,
"e": 137914,
"s": 137697,
"text": "// GET: Employee/Details/5\n[OutputCache(Duration = int.MaxValue, VaryByParam = \"id\")]\n\npublic ActionResult Details(int id){\n var employee = db.Employees.SingleOrDefault(e => e.ID == id);\n return View(employee);\n}"
},
{
"code": null,
"e": 138053,
"s": 137914,
"text": "When the above code is compiled and executed, you will receive the following output by specifying the URL http://localhost:63004/employee."
},
{
"code": null,
"e": 138154,
"s": 138053,
"text": "Click on the Details link of any link and you will see the details view of that particular employee."
},
{
"code": null,
"e": 138368,
"s": 138154,
"text": "The Details() action includes a VaryByParam property with the value “Id”. When different values of the Id parameter are passed to the controller action, different cached versions of the Details view are generated."
},
{
"code": null,
"e": 138565,
"s": 138368,
"text": "It is important to understand that using the VaryByParam property results in more caching. A different cached version of the Details view is created for each different version of the Id parameter."
},
{
"code": null,
"e": 138801,
"s": 138565,
"text": "You can create a cache profile in the web.config file. It is an alternative to configuring output cache properties by modifying properties of the [OutputCache] attribute. It offers a couple of important advantages which are as follows."
},
{
"code": null,
"e": 138872,
"s": 138801,
"text": "Controls how controller actions cache content in one central location."
},
{
"code": null,
"e": 138943,
"s": 138872,
"text": "Controls how controller actions cache content in one central location."
},
{
"code": null,
"e": 139037,
"s": 138943,
"text": "Creates one cache profile and apply the profile to several controllers or controller actions."
},
{
"code": null,
"e": 139131,
"s": 139037,
"text": "Creates one cache profile and apply the profile to several controllers or controller actions."
},
{
"code": null,
"e": 139205,
"s": 139131,
"text": "Modifies the web configuration file without recompiling your application."
},
{
"code": null,
"e": 139279,
"s": 139205,
"text": "Modifies the web configuration file without recompiling your application."
},
{
"code": null,
"e": 139361,
"s": 139279,
"text": "Disables caching for an application that has already been deployed to production."
},
{
"code": null,
"e": 139443,
"s": 139361,
"text": "Disables caching for an application that has already been deployed to production."
},
{
"code": null,
"e": 139615,
"s": 139443,
"text": "Let’s take a look at a simple example of cache profile by creating the cache profile in web.config file. The <caching> section must appear within the <system.web> section."
},
{
"code": null,
"e": 139818,
"s": 139615,
"text": "<caching>\n <outputCacheSettings>\n <outputCacheProfiles>\n <add name = \"Cache10Min\" duration = \"600\" varyByParam = \"none\"/>\n </outputCacheProfiles>\n </outputCacheSettings>\n</caching>"
},
{
"code": null,
"e": 139932,
"s": 139818,
"text": "You can apply the Cache10Min profile to a controller action with the [OutputCache] attribute which is as follows."
},
{
"code": null,
"e": 140105,
"s": 139932,
"text": "[OutputCache(CacheProfile = \"Cache10Min\")]\n\npublic ActionResult Index(){\n var employees = from e in db.Employees\n orderby e.ID\n select e;\n return View(employees);\n}"
},
{
"code": null,
"e": 140188,
"s": 140105,
"text": "Run this application and specify the following URL http://localhost:63004/employee"
},
{
"code": null,
"e": 140284,
"s": 140188,
"text": "If you invoke the Index() action as shown above then the same time will be returned for 10 Min."
},
{
"code": null,
"e": 140579,
"s": 140284,
"text": "In this chapter, we will look at the Razor view engine in ASP.NET MVC applications and some of the reasons why Razor exists. Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language."
},
{
"code": null,
"e": 140851,
"s": 140579,
"text": "Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine. You can use it anywhere to generate output like HTML. It's just that ASP.NET MVC has implemented a view engine that allows us to use Razor inside of an MVC application to produce HTML."
},
{
"code": null,
"e": 141127,
"s": 140851,
"text": "You will have a template file that's a mix of some literal text and some blocks of code. You combine that template with some data or a specific model where the template specifies where the data is supposed to appear, and then you execute the template to generate your output."
},
{
"code": null,
"e": 141348,
"s": 141127,
"text": "Razor is very similar to how ASPX files work. ASPX files are templates, which contain literal text and some C# code that specifies where your data should appear. We execute those to generate the HTML for our application."
},
{
"code": null,
"e": 141569,
"s": 141348,
"text": "Razor is very similar to how ASPX files work. ASPX files are templates, which contain literal text and some C# code that specifies where your data should appear. We execute those to generate the HTML for our application."
},
{
"code": null,
"e": 141708,
"s": 141569,
"text": "ASPX files have a dependency on the ASP.NET runtime to be available to parse and execute those ASPX files. Razor has no such dependencies."
},
{
"code": null,
"e": 141847,
"s": 141708,
"text": "ASPX files have a dependency on the ASP.NET runtime to be available to parse and execute those ASPX files. Razor has no such dependencies."
},
{
"code": null,
"e": 141905,
"s": 141847,
"text": "Unlike ASPX files, Razor has some different design goals."
},
{
"code": null,
"e": 141963,
"s": 141905,
"text": "Unlike ASPX files, Razor has some different design goals."
},
{
"code": null,
"e": 142222,
"s": 141963,
"text": "Microsoft wanted Razor to be easy to use and easy to learn, and work inside of tools like Visual Studio so that IntelliSense is available, the debugger is available, but they wanted Razor to have no ties to a specific technology, like ASP.NET or ASP.NET MVC."
},
{
"code": null,
"e": 142479,
"s": 142222,
"text": "If you're familiar with the life cycle of an ASPX file, then you're probably aware that there's a dependency on the ASP.NET runtime to be available to parse and execute those ASPX files. Microsoft wanted Razor to be smart, to make a developer's job easier."
},
{
"code": null,
"e": 142633,
"s": 142479,
"text": "Let’s take a look at a sample code from an ASPX file, which contains some literal text. This is our HTML markup. It also contains little bits of C# code."
},
{
"code": null,
"e": 143074,
"s": 142633,
"text": "<% foreach (var item in Model) { %>\n <tr>\n <td>\n <%: Html.ActionLink(\"Edit\", \"Edit\", new { id = item.ID })%> |\n <%: Html.ActionLink(\"Details\", \"Details\", new { id = item.ID }) %>|\n <%: Html.ActionLink(\"Delete\", \"Delete\", new { id = item.ID })%>\n </td>\n\t\t\n <td>\n <%: item.Name %>\n </td>\n\t\t\n <td>\n <%: String.Format(\"{0,g}\", item.JoiningDate) %>\n </td>\n\t\t\n </tr>\n<%}%>"
},
{
"code": null,
"e": 143230,
"s": 143074,
"text": "But these Web forms were basically repurposed by Microsoft to work with the earlier releases of MVC, meaning ASPX files were never a perfect match for MVC."
},
{
"code": null,
"e": 143522,
"s": 143230,
"text": "The syntax is a bit clunky when you need to transition from C# code back to HTML and from HTML code back into C# code. You are also prompted by IntelliSense to do things that just don't make sense in an MVC project, like add directives for output caching and user controls into an ASPX view."
},
{
"code": null,
"e": 143627,
"s": 143522,
"text": "Now look at this code which produces the same output, the difference being it is using the Razor syntax."
},
{
"code": null,
"e": 144029,
"s": 143627,
"text": "@foreach (var item in Model) {\n <tr>\n <td>\n @Html.ActionLink(\"Edit\", \"Edit\", new { id = item.ID }) |\n @Html.ActionLink(\"Details\", \"Details\", new { id = item.ID }) |\n @Html.ActionLink(\"Delete\", \"Delete\", new { id = item.ID })\n </td>\n\t\t\n <td>\n @item.Name\n </td>\n\t\t\n <td>\n @String.Format(\"{0,g}\", item.JoiningDate)\n </td>\n </tr>\n}"
},
{
"code": null,
"e": 144220,
"s": 144029,
"text": "With Razor syntax you can begin a bit of C# code by using the ‘@’ sign and the Razor parse will automatically switch into parsing this statement, this foreach statement, as a bit of C# code."
},
{
"code": null,
"e": 144438,
"s": 144220,
"text": "But when we're finished with the foreach statement and we have our opening curly brace, we can transition from C# code into HTML without putting an explicit token in there, like the percent in the angle bracket signs."
},
{
"code": null,
"e": 144721,
"s": 144438,
"text": "The Razor parser is smart enough to switch between C# code and HTML and again, from HTML back into C# code when we need to place our closing curly brace here. If you compare these two blocks of code, I think you'll agree that the Razor version is easier to read and easier to write."
},
{
"code": null,
"e": 144761,
"s": 144721,
"text": "Let's create a new ASP.Net MVC project."
},
{
"code": null,
"e": 144819,
"s": 144761,
"text": "Enter the name of project in the name field and click Ok."
},
{
"code": null,
"e": 145028,
"s": 144819,
"text": "To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok. It will create a basic MVC project with minimal predefined content."
},
{
"code": null,
"e": 145408,
"s": 145028,
"text": "Once the project is created by Visual Studio, you will see a number of files and folders displayed in the Solution Explorer window. As we have created ASP.Net MVC project from an empty project template, so at the moment the application does not contain anything to run. Since we start with an empty application and don't even have a single controller, let’s add a HomeController."
},
{
"code": null,
"e": 145560,
"s": 145408,
"text": "To add a controller right-click on the controller folder in the solution explorer and select Add → Controller. It will display the Add Scaffold dialog."
},
{
"code": null,
"e": 145672,
"s": 145560,
"text": "Select the MVC 5 Controller – Empty option and click Add button and then the Add Controller dialog will appear."
},
{
"code": null,
"e": 145853,
"s": 145672,
"text": "Set the name to HomeController and click ‘Add’ button. You will see a new C# file ‘HomeController.cs’ in the Controllers folder, which is open for editing in Visual Studio as well."
},
{
"code": null,
"e": 145908,
"s": 145853,
"text": "Right-click on the Index action and select Add View..."
},
{
"code": null,
"e": 146046,
"s": 145908,
"text": "Select Empty from the Template dropdown and click Add button. Visual Studio will create an Index.cshtml file inside the View/Home folder."
},
{
"code": null,
"e": 146280,
"s": 146046,
"text": "Notice that Razor view has a cshtml extension. If you're building your MVC application using Visual Basic it will be a VBHTML extension. At the top of this file is a code block that is explicitly setting this Layout property to null."
},
{
"code": null,
"e": 146396,
"s": 146280,
"text": "When you run this application you will see the blank webpage because we have created a View from an Empty template."
},
{
"code": null,
"e": 146615,
"s": 146396,
"text": "Let's add some C# code to make things more interesting. To write some C# code inside a Razor view, the first thing we will do is type the ‘@’ symbol that tells the parser that it is going to be doing something in code."
},
{
"code": null,
"e": 146735,
"s": 146615,
"text": "Let's create a FOR loop specify ‘@i’ inside the curly braces, which is essentially telling Razor to put the value of i."
},
{
"code": null,
"e": 147049,
"s": 146735,
"text": "@{\n Layout = null;\n} \n\n<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width\" />\n <title>Index</title>\n </head>\n\t\n <body>\n <div>\n @for (int index = 0; index < 12; index++){\n <div>@index </div>\n }\n </div>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 147109,
"s": 147049,
"text": "Run this application and you will see the following output."
},
{
"code": null,
"e": 147480,
"s": 147109,
"text": "DataAnnotations is used to configure your model classes, which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of .NET applications, such as ASP.NET MVC, which allows these applications to leverage the same annotations for client-side validations. DataAnnotation attributes override default Code-First conventions."
},
{
"code": null,
"e": 147604,
"s": 147480,
"text": "System.ComponentModel.DataAnnotations includes the following attributes that impacts the nullability or size of the column."
},
{
"code": null,
"e": 147608,
"s": 147604,
"text": "Key"
},
{
"code": null,
"e": 147618,
"s": 147608,
"text": "Timestamp"
},
{
"code": null,
"e": 147635,
"s": 147618,
"text": "ConcurrencyCheck"
},
{
"code": null,
"e": 147644,
"s": 147635,
"text": "Required"
},
{
"code": null,
"e": 147654,
"s": 147644,
"text": "MinLength"
},
{
"code": null,
"e": 147664,
"s": 147654,
"text": "MaxLength"
},
{
"code": null,
"e": 147677,
"s": 147664,
"text": "StringLength"
},
{
"code": null,
"e": 147807,
"s": 147677,
"text": "System.ComponentModel.DataAnnotations.Schema namespace includes the following attributes that impacts the schema of the database."
},
{
"code": null,
"e": 147813,
"s": 147807,
"text": "Table"
},
{
"code": null,
"e": 147820,
"s": 147813,
"text": "Column"
},
{
"code": null,
"e": 147826,
"s": 147820,
"text": "Index"
},
{
"code": null,
"e": 147837,
"s": 147826,
"text": "ForeignKey"
},
{
"code": null,
"e": 147847,
"s": 147837,
"text": "NotMapped"
},
{
"code": null,
"e": 147863,
"s": 147847,
"text": "InverseProperty"
},
{
"code": null,
"e": 148087,
"s": 147863,
"text": "Entity Framework relies on every entity having a key value that it uses for tracking entities. One of the conventions that Code First depends on is how it implies which property is the key in each of the Code First classes."
},
{
"code": null,
"e": 148336,
"s": 148087,
"text": "The convention is to look for a property named “Id” or one that combines the class name and “Id”, such as “StudentId”. The property will map to a primary key column in the database. The Student, Course and Enrollment classes follow this convention."
},
{
"code": null,
"e": 148579,
"s": 148336,
"text": "Now let’s suppose Student class used the name StdntID instead of ID. When Code First does not find a property that matches this convention it will throw an exception because of Entity Framework’s requirement that you must have a key property."
},
{
"code": null,
"e": 148668,
"s": 148579,
"text": "You can use the key annotation to specify which property is to be used as the EntityKey."
},
{
"code": null,
"e": 148860,
"s": 148668,
"text": "Let’s take a look at the Student class which contains StdntID. It doesn’t follow the default Code First convention so to handle this, Key attribute is added, which will make it a primary key."
},
{
"code": null,
"e": 149130,
"s": 148860,
"text": "public class Student{\n [Key]\n public int StdntID { get; set; }\n public string LastName { get; set; }\n public string FirstMidName { get; set; }\n public DateTime EnrollmentDate { get; set; }\n\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}"
},
{
"code": null,
"e": 149278,
"s": 149130,
"text": "When you run the application and look into the database in SQL Server Explorer, you will see that the primary key is now StdntID in Students table."
},
{
"code": null,
"e": 149514,
"s": 149278,
"text": "Entity Framework also supports composite keys. Composite keys are primary keys that consist of more than one property. For example, you have a DrivingLicense class whose primary key is a combination of LicenseNumber and IssuingCountry."
},
{
"code": null,
"e": 149772,
"s": 149514,
"text": "public class DrivingLicense{\n [Key, Column(Order = 1)]\n public int LicenseNumber { get; set; }\n\t\n [Key, Column(Order = 2)]\n public string IssuingCountry { get; set; }\n public DateTime Issued { get; set; }\n public DateTime Expires { get; set; }\n}"
},
{
"code": null,
"e": 149939,
"s": 149772,
"text": "When you have composite keys, Entity Framework requires you to define an order of the key properties. You can do this using the Column annotation to specify an order."
},
{
"code": null,
"e": 150112,
"s": 149939,
"text": "Code First will treat Timestamp properties the same as ConcurrencyCheck properties, but it will also ensure that the database field generated by Code First is non-nullable."
},
{
"code": null,
"e": 150409,
"s": 150112,
"text": "It's more common to use rowversion or timestamp fields for concurrency checking. But rather than using the ConcurrencyCheck annotation, you can use the more specific TimeStamp annotation as long as the type of the property is byte array. You can only have one timestamp property in a given class."
},
{
"code": null,
"e": 150501,
"s": 150409,
"text": "Let’s take a look at a simple example by adding the TimeStamp property to the Course class."
},
{
"code": null,
"e": 150756,
"s": 150501,
"text": "public class Course{\n public int CourseID { get; set; }\n public string Title { get; set; }\n public int Credits { get; set; }\n [Timestamp]\n public byte[] TStamp { get; set; }\n\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}"
},
{
"code": null,
"e": 150939,
"s": 150756,
"text": "As you can see in the above example, Timestamp attribute is applied to Byte[] property of the Course class. So, Code First will create a timestamp column TStamp in the Courses table."
},
{
"code": null,
"e": 151215,
"s": 150939,
"text": "The ConcurrencyCheck annotation allows you to flag one or more properties to be used for concurrency checking in the database, when a user edits or deletes an entity. If you've been working with the EF Designer, this aligns with setting a property's ConcurrencyMode to Fixed."
},
{
"code": null,
"e": 151340,
"s": 151215,
"text": "Let’s take a look at a simple example and see how ConcurrencyCheck works by adding it to the Title property in Course class."
},
{
"code": null,
"e": 151647,
"s": 151340,
"text": "public class Course{\n public int CourseID { get; set; }\n\t\n [ConcurrencyCheck]\n public string Title { get; set; }\n public int Credits { get; set; }\n\t\n [Timestamp, DataType(\"timestamp\")]\n public byte[] TimeStamp { get; set; }\n\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}"
},
{
"code": null,
"e": 151867,
"s": 151647,
"text": "In the above Course class, ConcurrencyCheck attribute is applied to the existing Title property. Code First will include Title column in update command to check for optimistic concurrency as shown in the following code."
},
{
"code": null,
"e": 152072,
"s": 151867,
"text": "exec sp_executesql N'UPDATE [dbo].[Courses]\n SET [Title] = @0\n WHERE (([CourseID] = @1) AND ([Title] = @2))\n ',N'@0 nvarchar(max) ,@1 int,@2 nvarchar(max)\n',@0 = N'Maths',@1 = 1,@2 = N'Calculus'\ngo\n"
},
{
"code": null,
"e": 152331,
"s": 152072,
"text": "The Required annotation tells EF that a particular property is required. Let’s have a look at the following Student class in which Required id is added to the FirstMidName property. Required attribute will force EF to ensure that the property has data in it."
},
{
"code": null,
"e": 152633,
"s": 152331,
"text": "public class Student{\n [Key]\n public int StdntID { get; set; }\n\t\n [Required]\n public string LastName { get; set; }\n\t\n [Required]\n public string FirstMidName { get; set; }\n public DateTime EnrollmentDate { get; set; }\n\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}"
},
{
"code": null,
"e": 152874,
"s": 152633,
"text": "You can see in the above example of Student class Required attribute is applied to FirstMidName and LastName. So, Code First will create a NOT NULL FirstMidName and LastName column in the Students table as shown in the following screenshot."
},
{
"code": null,
"e": 153106,
"s": 152874,
"text": "The MaxLength attribute allows you to specify additional property validations. It can be applied to a string or array type property of a domain class. EF Code First will set the size of a column as specified in MaxLength attribute."
},
{
"code": null,
"e": 153217,
"s": 153106,
"text": "Let’s take a look at the following Course class in which MaxLength(24) attribute is applied to Title property."
},
{
"code": null,
"e": 153462,
"s": 153217,
"text": "public class Course{\n public int CourseID { get; set; }\n [ConcurrencyCheck]\n [MaxLength(24)]\n\t\n public string Title { get; set; }\n public int Credits { get; set; }\n\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}"
},
{
"code": null,
"e": 153608,
"s": 153462,
"text": "When you run the above application, Code-First will create a nvarchar(24) column Title in the Coursed table as shown in the following screenshot."
},
{
"code": null,
"e": 153718,
"s": 153608,
"text": "Now when the user sets the Title which contains more than 24 characters, EF will throw EntityValidationError."
},
{
"code": null,
"e": 153923,
"s": 153718,
"text": "The MinLength attribute allows you to specify additional property validations, just as you did with MaxLength. MinLength attribute can also be used with MaxLength attribute as shown in the following code."
},
{
"code": null,
"e": 154181,
"s": 153923,
"text": "public class Course{\n public int CourseID { get; set; }\n [ConcurrencyCheck]\n [MaxLength(24) , MinLength(5)]\n public string Title { get; set; }\n public int Credits { get; set; }\n\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}"
},
{
"code": null,
"e": 154370,
"s": 154181,
"text": "EF will throw EntityValidationError, if you set a value of Title property less than the specified length in MinLength attribute or greater than the specified length in MaxLength attribute."
},
{
"code": null,
"e": 154567,
"s": 154370,
"text": "StringLength also allows you to specify additional property validations like MaxLength. The difference being StringLength attribute can only be applied to a string type property of Domain classes."
},
{
"code": null,
"e": 154792,
"s": 154567,
"text": "public class Course{\n public int CourseID { get; set; }\n [StringLength (24)]\n public string Title { get; set; }\n public int Credits { get; set; }\n\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}"
},
{
"code": null,
"e": 154991,
"s": 154792,
"text": "Entity Framework also validates the value of a property for StringLength attribute. Now, if the user sets the Title, which contains more than 24 characters, then EF will throw EntityValidationError."
},
{
"code": null,
"e": 155333,
"s": 154991,
"text": "Default Code First convention creates a table name same as the class name. If you are letting Code First create the database, you can also change the name of the tables it is creating. You can use Code First with an existing database. But it's not always the case that the names of the classes match the names of the tables in your database."
},
{
"code": null,
"e": 155485,
"s": 155333,
"text": "Table attribute overrides this default convention. EF Code First will create a table with a specified name in Table attribute for a given domain class."
},
{
"code": null,
"e": 155752,
"s": 155485,
"text": "Let’s take a look at an example in which the class is named Student, and by convention, Code First presumes this will map to a table named Students. If that's not the case you can specify the name of the table with the Table attribute as shown in the following code."
},
{
"code": null,
"e": 156078,
"s": 155752,
"text": "[Table(\"StudentsInfo\")]\npublic class Student{\n [Key]\n public int StdntID { get; set; }\n\t\n [Required]\n public string LastName { get; set; }\n\t\n [Required]\n public string FirstMidName { get; set; }\n public DateTime EnrollmentDate { get; set; }\n\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}"
},
{
"code": null,
"e": 156264,
"s": 156078,
"text": "You can now see that the Table attribute specifies the table as StudentsInfo. When the table is generated, you will see the table name StudentsInfo as shown in the following screenshot."
},
{
"code": null,
"e": 156403,
"s": 156264,
"text": "You cannot only specify the table name but you can also specify a schema for the table using the Table attribute using the following code."
},
{
"code": null,
"e": 156748,
"s": 156403,
"text": "[Table(\"StudentsInfo\", Schema = \"Admin\")]\n\npublic class Student{\n [Key]\n public int StdntID { get; set; }\n\t\n [Required]\n public string LastName { get; set; }\n\t\n [Required]\n public string FirstMidName { get; set; }\n public DateTime EnrollmentDate { get; set; }\n\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}"
},
{
"code": null,
"e": 156912,
"s": 156748,
"text": "In the above example, the table is specified with admin schema. Now Code First will create StudentsInfo table in Admin schema as shown in the following screenshot."
},
{
"code": null,
"e": 157134,
"s": 156912,
"text": "It is also the same as Table attribute, but Table attribute overrides the table behavior while Column attribute overrides the column behavior. Default Code First convention creates a column name same as the property name."
},
{
"code": null,
"e": 157408,
"s": 157134,
"text": "If you are letting Code First create the database, and you also want to change the name of the columns in your tables. Column attribute overrides this default convention. EF Code First will create a column with a specified name in the Column attribute for a given property."
},
{
"code": null,
"e": 157708,
"s": 157408,
"text": "Let’s take a look at the following example again in which the property is named FirstMidName, and by convention, Code First presumes this will map to a column named FirstMidName. If that's not the case, you can specify the name of the column with the Column attribute as shown in the following code."
},
{
"code": null,
"e": 157991,
"s": 157708,
"text": "public class Student{\n public int ID { get; set; }\n public string LastName { get; set; }\n\t\n [Column(\"FirstName\")]\n public string FirstMidName { get; set; }\n public DateTime EnrollmentDate { get; set; }\n\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}"
},
{
"code": null,
"e": 158174,
"s": 157991,
"text": "You can now see that the Column attribute specifies the column as FirstName. When the table is generated, you will see the column name FirstName as shown in the following screenshot."
},
{
"code": null,
"e": 158326,
"s": 158174,
"text": "The Index attribute was introduced in Entity Framework 6.1. Note − If you are using an earlier version, the information in this section does not apply."
},
{
"code": null,
"e": 158540,
"s": 158326,
"text": "You can create an index on one or more columns using the IndexAttribute. Adding the attribute to one or more properties will cause EF to create the corresponding index in the database when it creates the database."
},
{
"code": null,
"e": 158752,
"s": 158540,
"text": "Indexes make the retrieval of data faster and efficient, in most cases. However, overloading a table or view with indexes could unpleasantly affect the performance of other operations such as inserts or updates."
},
{
"code": null,
"e": 158932,
"s": 158752,
"text": "Indexing is the new feature in Entity Framework where you can improve the performance of your Code First application by reducing the time required to query data from the database."
},
{
"code": null,
"e": 159153,
"s": 158932,
"text": "You can add indexes to your database using the Index attribute, and override the default Unique and Clustered settings to get the index best suited to your scenario. By default, the index will be named IX_<property name>"
},
{
"code": null,
"e": 159256,
"s": 159153,
"text": "Let’s take a look at the following code in which Index attribute is added in Course class for Credits."
},
{
"code": null,
"e": 159468,
"s": 159256,
"text": "public class Cours{\n public int CourseID { get; set; }\n public string Title { get; set; }\n [Index]\n public int Credits { get; set; }\n\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}"
},
{
"code": null,
"e": 159610,
"s": 159468,
"text": "You can see that the Index attribute is applied to the Credits property. Now when the table is generated, you will see IX_Credits in Indexes."
},
{
"code": null,
"e": 159814,
"s": 159610,
"text": "By default, indexes are non-unique, but you can use the IsUnique named parameter to specify that an index should be unique. The following example introduces a unique index as shown in the following code."
},
{
"code": null,
"e": 160059,
"s": 159814,
"text": "public class Course{\n public int CourseID { get; set; }\n [Index(IsUnique = true)]\n\t\n public string Title { get; set; }\n [Index]\n\t\n public int Credits { get; set; }\n\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}"
},
{
"code": null,
"e": 160326,
"s": 160059,
"text": "Code First convention will take care of the most common relationships in your model, but there are some cases where it needs help. For example, by changing the name of the key property in the Student class created a problem with its relationship to Enrollment class."
},
{
"code": null,
"e": 160871,
"s": 160326,
"text": "public class Enrollment{\n public int EnrollmentID { get; set; }\n public int CourseID { get; set; }\n public int StudentID { get; set; }\n public Grade? Grade { get; set; }\n public virtual Course Course { get; set; }\n public virtual Student Student { get; set; }\n}\n\npublic class Student{\n [Key]\n public int StdntID { get; set; }\n public string LastName { get; set; }\n public string FirstMidName { get; set; }\n public DateTime EnrollmentDate { get; set; }\n\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}"
},
{
"code": null,
"e": 161186,
"s": 160871,
"text": "While generating the database, Code First sees the StudentID property in the Enrollment class and recognizes it, by the convention that it matches a class name plus “ID”, as a foreign key to the Student class. But there is no StudentID property in the Student class, rather it is StdntID property in Student class."
},
{
"code": null,
"e": 161415,
"s": 161186,
"text": "The solution for this is to create a navigation property in the Enrollment and use the ForeignKey DataAnnotation to help Code First understand how to build the relationship between the two classes as shown in the following code."
},
{
"code": null,
"e": 161720,
"s": 161415,
"text": "public class Enrollment{\n public int EnrollmentID { get; set; }\n public int CourseID { get; set; }\n public int StudentID { get; set; }\n public Grade? Grade { get; set; }\n public virtual Course Course { get; set; }\n\t\n [ForeignKey(\"StudentID\")]\n public virtual Student Student { get; set; }\n}"
},
{
"code": null,
"e": 161801,
"s": 161720,
"text": "You can see now that the ForeignKey attribute is applied to navigation property."
},
{
"code": null,
"e": 162316,
"s": 161801,
"text": "By default conventions of Code First, every property that is of a supported data type and which includes getters and setters are represented in the database. But this isn’t always the case in applications. NotMapped attribute overrides this default convention. For example, you might have a property in the Student class such as FatherName, but it does not need to be stored. You can apply NotMapped attribute to a FatherName property, which you do not want to create a column in a database. Following is the code."
},
{
"code": null,
"e": 162640,
"s": 162316,
"text": "public class Student{\n [Key]\n public int StdntID { get; set; }\n public string LastName { get; set; }\n public string FirstMidName { get; set; }\n public DateTime EnrollmentDate { get; set; }\n [NotMapped]\n public int FatherName { get; set; }\n\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}"
},
{
"code": null,
"e": 162856,
"s": 162640,
"text": "You can see that NotMapped attribute is applied to the FatherName property. Now when the table is generated, you will see that FatherName column will not be created in a database, but it is present in Student class."
},
{
"code": null,
"e": 162954,
"s": 162856,
"text": "Code First will not create a column for a property which does not have either getters or setters."
},
{
"code": null,
"e": 163157,
"s": 162954,
"text": "The InverseProperty is used when you have multiple relationships between classes. In the Enrollment class, you may want to keep track of who enrolled a Current Course and who enrolled a Previous Course."
},
{
"code": null,
"e": 163219,
"s": 163157,
"text": "Let’s add two navigation properties for the Enrollment class."
},
{
"code": null,
"e": 163549,
"s": 163219,
"text": "public class Enrollment{\n public int EnrollmentID { get; set; }\n public int CourseID { get; set; }\n public int StudentID { get; set; }\n public Grade? Grade { get; set; }\n\t\n public virtual Course CurrCourse { get; set; }\n public virtual Course PrevCourse { get; set; }\n public virtual Student Student { get; set; }\n}"
},
{
"code": null,
"e": 163766,
"s": 163549,
"text": "Similarly, you’ll also need to add in the Course class referenced by these properties. The Course class has navigation properties back to the Enrollment class, which contains all the current and previous enrollments."
},
{
"code": null,
"e": 164056,
"s": 163766,
"text": "public class Course{\n public int CourseID { get; set; }\n public string Title { get; set; }\n [Index]\n\t\n public int Credits { get; set; }\n public virtual ICollection<Enrollment> CurrEnrollments { get; set; }\n public virtual ICollection<Enrollment> PrevEnrollments { get; set; }\n}"
},
{
"code": null,
"e": 164324,
"s": 164056,
"text": "Code First creates {Class Name}_{Primary Key} foreign key column if the foreign key property is not included in a particular class as shown in the above classes. When the database is generated you will see a number of foreign keys as seen in the following screenshot."
},
{
"code": null,
"e": 164596,
"s": 164324,
"text": "As you can see that Code First is not able to match up the properties in the two classes on its own. The database table for Enrollments should have one foreign key for the CurrCourse and one for the PrevCourse, but Code First will create four foreign key properties, i.e."
},
{
"code": null,
"e": 164616,
"s": 164596,
"text": "CurrCourse_CourseID"
},
{
"code": null,
"e": 164636,
"s": 164616,
"text": "PrevCourse_CourseID"
},
{
"code": null,
"e": 164652,
"s": 164636,
"text": "Course_CourseID"
},
{
"code": null,
"e": 164669,
"s": 164652,
"text": "Course_CourseID1"
},
{
"code": null,
"e": 164779,
"s": 164669,
"text": "To fix these problems, you can use the InverseProperty annotation to specify the alignment of the properties."
},
{
"code": null,
"e": 165143,
"s": 164779,
"text": "public class Course{\n public int CourseID { get; set; }\n public string Title { get; set; }\n\t\n [Index]\n public int Credits { get; set; }\n\t\n [InverseProperty(\"CurrCourse\")]\n public virtual ICollection<Enrollment> CurrEnrollments { get; set; }\n\t\n [InverseProperty(\"PrevCourse\")]\n public virtual ICollection<Enrollment> PrevEnrollments { get; set; }\n}"
},
{
"code": null,
"e": 165438,
"s": 165143,
"text": "As you can see now, when InverseProperty attribute is applied in the above Course class by specifying which reference property of Enrollment class it belongs to, Code First will generate database and create only two foreign key columns in Enrollments table as shown in the following screenshot."
},
{
"code": null,
"e": 165510,
"s": 165438,
"text": "We recommend you to execute the above example for better understanding."
},
{
"code": null,
"e": 165744,
"s": 165510,
"text": "In this chapter, we will talk about NuGet which is a package manager for .NET and Visual Studio. NuGet can be used to find and install packages, that is, software pieces and assemblies and things that you want to use in your project."
},
{
"code": null,
"e": 165952,
"s": 165744,
"text": "NuGet is not a tool that is specific to ASP.NET MVC projects. This is a tool that you can use inside of Visual Studio for console applications, WPF applications, Azure applications, any types of application."
},
{
"code": null,
"e": 166258,
"s": 165952,
"text": "NuGet is a package manager, and is responsible for downloading, installing, updating, and configuring software in your system. From the term software we don’t mean end users software like Microsoft Word or Notepad 2, etc. but pieces of software, which you want to use in your project, assembly references."
},
{
"code": null,
"e": 166612,
"s": 166258,
"text": "For example, assemblies you want to use might be mock, for mock object unit testing, or NHibernate for data access, and components you use when building your application. The above-mentioned components are open source software, but some NuGet packages you find are closed source software. Some of the packages you'll find are even produced by Microsoft."
},
{
"code": null,
"e": 166814,
"s": 166612,
"text": "The common theme along all the packages mentioned above, like mock and NHibernate, and Microsoft packages like a preview for the Entity Framework, is that they don't come with Visual Studio by default."
},
{
"code": null,
"e": 166899,
"s": 166814,
"text": "To install any of these components without NuGet, you will need the following steps."
},
{
"code": null,
"e": 167132,
"s": 166899,
"text": "If you want to use one of those components, you need to find the home page for some particular project and look for a download link. Then once the project is downloaded, it's typically in a ZIP format so you will need to extract it."
},
{
"code": null,
"e": 167341,
"s": 167132,
"text": "If you didn't download binaries, then you will first need to build the software and then reference it in your project. And many components at that point still require some configuration to get up and running."
},
{
"code": null,
"e": 167632,
"s": 167341,
"text": "NuGet replaces all of the steps discussed earlier and you just need to say Add Package. NuGet knows where to download the latest version, it knows how to extract it, how to establish a reference to that component, and even configure it. This leaves you more time to just build the software."
},
{
"code": null,
"e": 167760,
"s": 167632,
"text": "Let’s take a look at a simple example in which we will add support for Entity framework in our ASP.NET MVC project using NuGet."
},
{
"code": null,
"e": 167899,
"s": 167760,
"text": "Step 1 − Install the Entity Framework. Right-click on the project and select NuGet Package Manager → Manage NuGet Packages for Solution..."
},
{
"code": null,
"e": 167939,
"s": 167899,
"text": "It will open the NuGet Package Manager."
},
{
"code": null,
"e": 167995,
"s": 167939,
"text": "Step 2 − Search for Entity framework in the search box."
},
{
"code": null,
"e": 168093,
"s": 167995,
"text": "Step 3 − Select the Entity Framework and click ‘Install’ button. It will open the Preview dialog."
},
{
"code": null,
"e": 168124,
"s": 168093,
"text": "Step 4 − Click Ok to continue."
},
{
"code": null,
"e": 168188,
"s": 168124,
"text": "Step 5 − Click the ‘I Accept’ button to start the installation."
},
{
"code": null,
"e": 168282,
"s": 168188,
"text": "Once the Entity Framework is installed you will see the message in out window as shown above."
},
{
"code": null,
"e": 168536,
"s": 168282,
"text": "When you install a package with NuGet, you will see a new packages directory in the same folder as the solution file hosting your project. This package directory contains all the packages that you have installed for any of the projects in that solution."
},
{
"code": null,
"e": 168654,
"s": 168536,
"text": "In other words, NuGet is not downloading packages into a central location, it's storing them on a per solution basis."
},
{
"code": null,
"e": 168897,
"s": 168654,
"text": "ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework."
},
{
"code": null,
"e": 169123,
"s": 168897,
"text": "When you're building APIs on the Web, there are several ways you can build APIs on the Web. These include HTTP/RPC, and what this means is using HTTP in Remote Procedure Call to call into things, like Methods, across the Web."
},
{
"code": null,
"e": 169285,
"s": 169123,
"text": "The verbs themselves are included in the APIs, like Get Customers, Insert Invoice, Delete Customer, and that each of these endpoints end up being a separate URI."
},
{
"code": null,
"e": 169377,
"s": 169285,
"text": "Let’s take a look at a simple example of Web API by creating a new ASP.NET Web Application."
},
{
"code": null,
"e": 169453,
"s": 169377,
"text": "Step 1 − Open the Visual Studio and click File → New → Project menu option."
},
{
"code": null,
"e": 169481,
"s": 169453,
"text": "A new Project dialog opens."
},
{
"code": null,
"e": 169546,
"s": 169481,
"text": "Step 2 − From the left pane, select Templates → Visual C# → Web."
},
{
"code": null,
"e": 169606,
"s": 169546,
"text": "Step 3 − In the middle pane, select ASP.NET Web Application"
},
{
"code": null,
"e": 169782,
"s": 169606,
"text": "Enter project name WebAPIDemo in the Name field and click Ok to continue. You will see the following dialog, which asks you to set the initial content for the ASP.NET project."
},
{
"code": null,
"e": 169936,
"s": 169782,
"text": "Step 4 − To keep things simple, select the Empty option and check the Web API checkbox in the ‘Add folders and core references for’ section and click Ok."
},
{
"code": null,
"e": 170013,
"s": 169936,
"text": "Step 5 − It will create a basic MVC project with minimal predefined content."
},
{
"code": null,
"e": 170145,
"s": 170013,
"text": "Once the project is created by Visual Studio, you will see a number of files and folders displayed in the Solution Explorer window."
},
{
"code": null,
"e": 170264,
"s": 170145,
"text": "Step 6 − Now we need to add a model. Right-click on the Models folder in the solution explorer and select Add → Class."
},
{
"code": null,
"e": 170306,
"s": 170264,
"text": "You will now see the Add New Item dialog."
},
{
"code": null,
"e": 170387,
"s": 170306,
"text": "Step 7 − Select Class in the middle pan and enter Employee.cs in the name field."
},
{
"code": null,
"e": 170460,
"s": 170387,
"text": "Step 8 − Add some properties to Employee class using the following code."
},
{
"code": null,
"e": 170765,
"s": 170460,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\n\nnamespace WebAPIDemo.Models {\n public class Employee{\n public int ID { get; set; }\n public string Name { get; set; }\n public DateTime JoiningDate { get; set; }\n public int Age { get; set; }\n }\n}"
},
{
"code": null,
"e": 170891,
"s": 170765,
"text": "Step 9 − Let’s add the controller. Right-click on the controller folder in the solution explorer and select Add → Controller."
},
{
"code": null,
"e": 170932,
"s": 170891,
"text": "It will display the Add Scaffold dialog."
},
{
"code": null,
"e": 171068,
"s": 170932,
"text": "Step 10 − Select the Web API 2 Controller - Empty option. This template will create an Index method with default action for controller."
},
{
"code": null,
"e": 171140,
"s": 171068,
"text": "Step 11 − Click ‘Add’ button and the Add Controller dialog will appear."
},
{
"code": null,
"e": 171210,
"s": 171140,
"text": "Step 12 − Set the name to EmployeesController and click ‘Add’ button."
},
{
"code": null,
"e": 171358,
"s": 171210,
"text": "You will see a new C# file ‘EmployeeController.cs’ in the Controllers folder, which is open for editing in Visual Studio with some default actions."
},
{
"code": null,
"e": 172336,
"s": 171358,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web.Http;\nusing WebAPIDemo.Models;\n\nnamespace WebAPIDemo.Controllers{\n public class EmployeesController : ApiController{\n Employee[] employees = new Employee[]{\n new Employee { ID = 1, Name = \"Mark\", JoiningDate =\n DateTime.Parse(DateTime.Today.ToString()), Age = 30 },\n new Employee { ID = 2, Name = \"Allan\", JoiningDate =\n DateTime.Parse(DateTime.Today.ToString()), Age = 35 },\n new Employee { ID = 3, Name = \"Johny\", JoiningDate =\n DateTime.Parse(DateTime.Today.ToString()), Age = 21 }\n };\n\t\t\n public IEnumerable<Employee> GetAllEmployees(){\n return employees;\n }\n\t\t\n public IHttpActionResult GetEmployee(int id){\n var employee = employees.FirstOrDefault((p) => p.ID == id);\n if (employee == null){\n return NotFound();\n }\n return Ok(employee);\n }\n }\n}"
},
{
"code": null,
"e": 172471,
"s": 172336,
"text": "Step 13 − Run this application and specify /api/employees/ at the end of the URL and press ‘Enter’. You will see the following output."
},
{
"code": null,
"e": 172592,
"s": 172471,
"text": "Step 14 − Let us specify the following URL http://localhost:63457/api/employees/1 and you will see the following output."
},
{
"code": null,
"e": 172965,
"s": 172592,
"text": "ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Visual Studio 2013 includes pre-installed code generators for MVC and Web API projects. You add scaffolding to your project when you want to quickly add code that interacts with data models. Using scaffolding can reduce the amount of time to develop standard data operations in your project."
},
{
"code": null,
"e": 173201,
"s": 172965,
"text": "As you have seen that we have created the views for Index, Create, Edit actions and also need to update the actions methods as well. But ASP.Net MVC provides an easier way to create all these Views and action methods using scaffolding."
},
{
"code": null,
"e": 173350,
"s": 173201,
"text": "Let’s take a look at a simple example. We will create the same example which contains a model class Employee, but this time we will use scaffolding."
},
{
"code": null,
"e": 173429,
"s": 173350,
"text": "Step 1 − Open the Visual Studio and click on File → New → Project menu option."
},
{
"code": null,
"e": 173457,
"s": 173429,
"text": "A new Project dialog opens."
},
{
"code": null,
"e": 173522,
"s": 173457,
"text": "Step 2 − From the left pane, select Templates → Visual C# → Web."
},
{
"code": null,
"e": 173583,
"s": 173522,
"text": "Step 3 − In the middle pane, select ASP.NET Web Application."
},
{
"code": null,
"e": 173781,
"s": 173583,
"text": "Step 4 − Enter the project name ‘MVCScaffoldingDemo’ in the Name field and click Ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project."
},
{
"code": null,
"e": 173930,
"s": 173781,
"text": "Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’section and click Ok."
},
{
"code": null,
"e": 173998,
"s": 173930,
"text": "It will create a basic MVC project with minimal predefined content."
},
{
"code": null,
"e": 174130,
"s": 173998,
"text": "Once the project is created by Visual Studio, you will see a number of files and folders displayed in the Solution Explorer window."
},
{
"code": null,
"e": 174277,
"s": 174130,
"text": "First step is to install the Entity Framework. Right-click on the project and select NuGet Package Manager → Manage NuGet Packages for Solution..."
},
{
"code": null,
"e": 174366,
"s": 174277,
"text": "It will open the ‘NuGet Package Manager’. Search for Entity framework in the search box."
},
{
"code": null,
"e": 174455,
"s": 174366,
"text": "Select the Entity Framework and click ‘Install’ button. It will open the Preview dialog."
},
{
"code": null,
"e": 174477,
"s": 174455,
"text": "Click Ok to continue."
},
{
"code": null,
"e": 174524,
"s": 174477,
"text": "Click ‘I Accept’ button to start installation."
},
{
"code": null,
"e": 174640,
"s": 174524,
"text": "Once the Entity Framework is installed you will see the message in the out window as shown in the above screenshot."
},
{
"code": null,
"e": 174778,
"s": 174640,
"text": "To add a model, right-click on the Models folder in the solution explorer and select Add → Class. You will see the ‘Add New Item’ dialog."
},
{
"code": null,
"e": 174850,
"s": 174778,
"text": "Select Class in the middle pan and enter Employee.cs in the name field."
},
{
"code": null,
"e": 174914,
"s": 174850,
"text": "Add some properties to Employee class using the following code."
},
{
"code": null,
"e": 175156,
"s": 174914,
"text": "using System;\n\nnamespace MVCScaffoldingDemo.Models {\n public class Employee{\n public int ID { get; set; }\n public string Name { get; set; }\n public DateTime JoiningDate { get; set; }\n public int Age { get; set; }\n }\n}"
},
{
"code": null,
"e": 175345,
"s": 175156,
"text": "We have an Employee Model, now we need to add another class, which will communicate with Entity Framework to retrieve and save the data. Following is the complete code in Employee.cs file."
},
{
"code": null,
"e": 175714,
"s": 175345,
"text": "using System;\nusing System.Data.Entity;\n\nnamespace MVCScaffoldingDemo.Models{\n public class Employee{\n public int ID { get; set; }\n public string Name { get; set; }\n public DateTime JoiningDate { get; set; }\n public int Age { get; set; }\n }\n\t\n public class EmpDBContext : DbContext{\n public DbSet<Employee> Employees { get; set; }\n }\n}"
},
{
"code": null,
"e": 175923,
"s": 175714,
"text": "As you can see ‘EmpDBContext’ is derived from an EF class known as ‘DbContext’. In this class, we have one property with the name DbSet, which basically represents the entity which you want to query and save."
},
{
"code": null,
"e": 176019,
"s": 175923,
"text": "Now let’s build a solution and you will see the message when the project is successfully build."
},
{
"code": null,
"e": 176135,
"s": 176019,
"text": "To add a scaffold, right-click on Controllers folder in the Solution Explorer and select Add → New Scaffolded Item."
},
{
"code": null,
"e": 176176,
"s": 176135,
"text": "It will display the Add Scaffold dialog."
},
{
"code": null,
"e": 176324,
"s": 176176,
"text": "Select MVC 5 Controller with views, using Entity Framework in the middle pane and click ‘Add’ button, which will display the Add Controller dialog."
},
{
"code": null,
"e": 176492,
"s": 176324,
"text": "Select Employee from the Model class dropdown and EmpDBContext from the Data context class dropdown. You will also see that the controller name is selected by default."
},
{
"code": null,
"e": 176640,
"s": 176492,
"text": "Click ‘Add’ button to continue and you will see the following code in the EmployeesController, which is created by Visual Studio using Scaffolding."
},
{
"code": null,
"e": 179928,
"s": 176640,
"text": "using System.Data.Entity;\nusing System.Linq;\nusing System.Net;\nusing System.Web.Mvc;\nusing MVCScaffoldingDemo.Models;\n\nnamespace MVCScaffoldingDemo.Controllers {\n public class EmployeesController : Controller{\n private EmpDBContext db = new EmpDBContext();\n \n // GET: Employees\n public ActionResult Index(){\n return View(db.Employees.ToList());\n }\n \n // GET: Employees/Details/5\n public ActionResult Details(int? id){\n if (id == null){\n return new HttpStatusCodeResult(HttpStatusCode.BadRequest);\n }\n\t\t\t\n Employee employee = db.Employees.Find(id);\n\t\t\t\n if (employee == null){\n return HttpNotFound();\n }\n return View(employee);\n }\n \n // GET: Employees/Create\n public ActionResult Create(){\n return View();\n }\n \n // POST: Employees/Create\n // To protect from overposting attacks, please enable the specific\n properties you want to bind to, for\n // more details see http://go.microsoft.com/fwlink/?LinkId=317598.\n [HttpPost]\n [ValidateAntiForgeryToken]\n\t\t\n public ActionResult Create([Bind(Include = \"ID,Name,JoiningDate,Age\")]\n Employee employee){\n if (ModelState.IsValid){\n db.Employees.Add(employee);\n db.SaveChanges();\n return RedirectToAction(\"Index\");\n }\n return View(employee);\n }\n \n // GET: Employees/Edit/5\n public ActionResult Edit(int? id){\n if (id == null){\n return new HttpStatusCodeResult(HttpStatusCode.BadRequest);\n }\n\t\t\t\n Employee employee = db.Employees.Find(id);\n\t\t\t\n if (employee == null){\n return HttpNotFound();\n }\n return View(employee);\n }\n \n // POST: Employees/Edit/5\n // To protect from overposting attacks, please enable the specific\n properties you want to bind to, for\n // more details see http://go.microsoft.com/fwlink/?LinkId=317598.\n [HttpPost]\n [ValidateAntiForgeryToken]\n public ActionResult Edit([Bind(Include = \"ID,Name,JoiningDate,Age\")]Employee employee){\n if (ModelState.IsValid){\n db.Entry(employee).State = EntityState.Modified;\n db.SaveChanges();\n return RedirectToAction(\"Index\");\n }\n return View(employee);\n }\n \n // GET: Employees/Delete/5\n public ActionResult Delete(int? id){\n if (id == null){\n return new HttpStatusCodeResult(HttpStatusCode.BadRequest);\n }\n\t\t\t\n Employee employee = db.Employees.Find(id);\n\t\t\t\n if (employee == null){\n return HttpNotFound();\n }\n return View(employee);\n }\n \n // POST: Employees/Delete/5\n [HttpPost, ActionName(\"Delete\")]\n [ValidateAntiForgeryToken]\n\t\t\n public ActionResult DeleteConfirmed(int id){\n Employee employee = db.Employees.Find(id);\n db.Employees.Remove(employee);\n db.SaveChanges();\n return RedirectToAction(\"Index\");\n }\n \n protected override void Dispose(bool disposing){\n if (disposing){\n db.Dispose();\n }\n\t\t\t\n base.Dispose(disposing);\n }\n }\n}"
},
{
"code": null,
"e": 180048,
"s": 179928,
"text": "Run your application and specify the following URL http://localhost:59359/employees. You will see the following output."
},
{
"code": null,
"e": 180180,
"s": 180048,
"text": "You can see there is no data in the View, because we have not added any records to the database, which is created by Visual Studio."
},
{
"code": null,
"e": 180286,
"s": 180180,
"text": "Let’s add one record from the browser by clicking the ‘Create New’ link, it will display the Create view."
},
{
"code": null,
"e": 180330,
"s": 180286,
"text": "Let’s add some data in the following field."
},
{
"code": null,
"e": 180391,
"s": 180330,
"text": "Click the ‘Create’ button and it will update the Index view."
},
{
"code": null,
"e": 180454,
"s": 180391,
"text": "You can see that the new record is also added to the database."
},
{
"code": null,
"e": 180623,
"s": 180454,
"text": "As you can see that we have implemented the same example by using Scaffolding, which is a much easier way to create your Views and Action methods from your model class."
},
{
"code": null,
"e": 180862,
"s": 180623,
"text": "In this chapter, we will look at Bootstrap which is a front-end framework now included with ASP.NET and MVC. It is a popular front-end tool kit for web applications, and will help you build a user interface with HTML, CSS, and JavaScript."
},
{
"code": null,
"e": 181067,
"s": 180862,
"text": "It was originally created by web developers at Twitter for personal use, however, it is now an open source and has become popular with designers and developers because of its flexiblility and ease of use."
},
{
"code": null,
"e": 181320,
"s": 181067,
"text": "You can use Bootstrap to create an interface that looks good on everything from large desktop displays to small mobile screens. In this chapter, we will also look at how Bootstrap can work with your layout views to structure the look of an application."
},
{
"code": null,
"e": 181736,
"s": 181320,
"text": "Bootstrap provides all the pieces you need for layout, buttons, forms, menus, widgets, picture carousels, labels, badges, typography, and all sorts of features. Since Bootstrap is all HTML, CSS and JavaScript, all open standards, you can use it with any framework including ASP.NET MVC. When you start a new MVC project, Bootstrap will be present, meaning you'll find Bootstrap.css and Bootstrap.js in your project."
},
{
"code": null,
"e": 181780,
"s": 181736,
"text": "Let’s create a new ASP.NET Web Application."
},
{
"code": null,
"e": 181885,
"s": 181780,
"text": "Enter the name of the project, let’s say ‘MVCBootstrap’ and click Ok. You will see the following dialog."
},
{
"code": null,
"e": 182078,
"s": 181885,
"text": "In this dialog, if you select the empty template, you will get an empty web application and there will be no Bootstrap present. There won't be any controllers or any other script files either."
},
{
"code": null,
"e": 182362,
"s": 182078,
"text": "Now select the MVC template and click Ok. When Visual Studio creates this solution, one of the packages that it will download and install into the project will be the Bootstrap NuGet package. You can verify by going to packages.config and you can see the Bootstrap version 3 package."
},
{
"code": null,
"e": 182434,
"s": 182362,
"text": "You can also see the Content folder which contains different css files."
},
{
"code": null,
"e": 182492,
"s": 182434,
"text": "Run this application and you will see the following page."
},
{
"code": null,
"e": 182835,
"s": 182492,
"text": "When this page appears, most of the layout and styling that you see is layout and styling that has been applied by Bootstrap. It includes the navigation bar at the top with the links as well as the display that is advertising ASP.NET. It also includes all of these pieces down about getting started and getting more libraries and web hosting."
},
{
"code": null,
"e": 182985,
"s": 182835,
"text": "If you expand the browser just a little bit more, those will actually lay out side by side and that's part of Bootstrap's responsive design features."
},
{
"code": null,
"e": 183061,
"s": 182985,
"text": "If you look under the content folder, you will find the Bootstrap.css file."
},
{
"code": null,
"e": 183251,
"s": 183061,
"text": "The NuGet package also gives a minified version of that file that's a little bit smaller. Under scripts, you will find Bootstrap.js, that's required for some of the components of Bootstrap."
},
{
"code": null,
"e": 183409,
"s": 183251,
"text": "It does have a dependency on jQuery and fortunately jQuery is also installed in this project and there's a minified version of the Bootstrap JavaScript file."
},
{
"code": null,
"e": 183611,
"s": 183409,
"text": "Now the question is, where are all these added in the application? You might expect, that it would be in the layout template, the layout view for this project which is under View/Shared/_layout.cshtml."
},
{
"code": null,
"e": 183716,
"s": 183611,
"text": "The layout view controls the structure of the UI. Following is the complete code in _layout.cshtml file."
},
{
"code": null,
"e": 185463,
"s": 183716,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"utf-8\" />\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\">\n <title>@ViewBag.Title - My ASP.NET Application</title>\n @Styles.Render(\"~/Content/css\")\n @Scripts.Render(\"~/bundles/modernizr\")\n </head>\n\t\n <body>\n <div class = \"navbar navbar-inverse navbar-fixed-top\">\n <div class = \"container\">\n\t\t\t\n <div class = \"navbar-header\">\n <button type = \"button\" class = \"navbar-toggle\" datatoggle =\n \"collapse\" data-target = \".navbar-collapse\">\n <span class = \"icon-bar\"></span>\n <span class = \"icon-bar\"></span>\n <span class = \"icon-bar\"></span>\n </button>\n\t\t\t\t\t\n @Html.ActionLink(\"Application name\", \"Index\", \"Home\", new\n { area = \"\" }, new { @class = \"navbar-brand\" })\n </div>\n\t\t\t\t\n <div class = \"navbar-collapse collapse\">\n <ul class = \"nav navbar-nav\">\n <li>@Html.ActionLink(\"Home\", \"Index\", \"Home\")</li>\n <li>@Html.ActionLink(\"About\", \"About\", \"Home\")</li>\n <li>@Html.ActionLink(\"Contact\", \"Contact\", \"Home\")</li>\n </ul>\n\t\t\t\t\t\n @Html.Partial(\"_LoginPartial\")\n </div>\n\t\t\t\t\n </div>\n\t\t\t\n </div>\n <div class = \"container body-content\">\n @RenderBody()\n <hr />\n <footer>\n <p>© @DateTime.Now.Year - My ASP.NET Application</p>\n </footer>\n </div>\n\t\t\n @Scripts.Render(\"~/bundles/jquery\")\n @Scripts.Render(\"~/bundles/bootstrap\")\n @RenderSection(\"scripts\", required: false)\n\t\t\n </body>\n</html>"
},
{
"code": null,
"e": 185584,
"s": 185463,
"text": "In the above code there are two things to note. First at the top, after <title> you will see the following line of code."
},
{
"code": null,
"e": 185617,
"s": 185584,
"text": "@Styles.Render(\"~/Content/css\")\n"
},
{
"code": null,
"e": 185777,
"s": 185617,
"text": "The Styles.Render for Content/css is actually where the Bootstrap.css file is going to be included, and at the bottom, you will see the following line of code."
},
{
"code": null,
"e": 185817,
"s": 185777,
"text": "@Scripts.Render(\"~/bundles/bootstrap\")\n"
},
{
"code": null,
"e": 185995,
"s": 185817,
"text": "It is rendering the Bootstrap script. So in order to find out what exactly is inside of these bundles, we'll have to go into the BundleConfig file, which is in App_Start folder."
},
{
"code": null,
"e": 186111,
"s": 185995,
"text": "In BundleConfig, you can see at the bottom that the CSS bundle includes both Bootstrap.css and our custom site.css."
},
{
"code": null,
"e": 186223,
"s": 186111,
"text": "bundles.Add(new StyleBundle(\"~/Content/css\").Include(\n \"~/Content/bootstrap.css\",\n \"~/Content/site.css\"));\n"
},
{
"code": null,
"e": 186459,
"s": 186223,
"text": "It is a place where we can add our own style sheets to customize the look of the application. You can also see the Bootstrap bundle that appears before the CSS bundle that includes Bootstrap.js, and another JavaScript file, respond.js."
},
{
"code": null,
"e": 186579,
"s": 186459,
"text": "bundles.Add(new ScriptBundle(\"~/bundles/bootstrap\").Include(\n \"~/Scripts/bootstrap.js\",\n \"~/Scripts/respond.js\"));\n"
},
{
"code": null,
"e": 186639,
"s": 186579,
"text": "Let’s comment Bootstrap.css as shown in the following code."
},
{
"code": null,
"e": 186753,
"s": 186639,
"text": "bundles.Add(new StyleBundle(\"~/Content/css\").Include(\n //\"~/Content/bootstrap.css\",\n \"~/Content/site.css\"));\n"
},
{
"code": null,
"e": 186918,
"s": 186753,
"text": "Run this application again, just to give you an idea of what Bootstrap is doing, because now the only styles that are available are the styles that are in site.css."
},
{
"code": null,
"e": 187038,
"s": 186918,
"text": "As you can see we lost the layout, the navigation bar at the top of the page. Now everything looks ordinary and boring."
},
{
"code": null,
"e": 187367,
"s": 187038,
"text": "Let us now see what Bootstrap is all about. There's a couple of things that Bootstrap just does automatically and there's a couple of things that Bootstrap can do for you when you add classes and have the right HTML structure. If you look at the _layout.cshtml file, you will see the navbar class as shown in the following code."
},
{
"code": null,
"e": 188382,
"s": 187367,
"text": "<div class = \"navbar navbar-inverse navbar-fixed-top\">\n <div class = \"container\">\n\t\n <div class = \"navbar-header\">\n <button type = \"button\" class = \"navbar-toggle\" datatoggle =\n \"collapse\" data-target = \".navbar-collapse\">\n <span class = \"icon-bar\"></span>\n <span class = \"icon-bar\"></span>\n <span class = \"icon-bar\"></span>\n </button>\n <a class = \"navbar-brand\" href = \"/\">Application name</a>\n </div>\n\t\t\n <div class = \"navbar-collapse collapse\">\n <ul class = \"nav navbar-nav\">\n <li><a href = \"/\">Home</a></li>\n <li><a href = \"/Home/About\">About</a></li>\n <li><a href = \"/Home/Contact\">Contact</a></li>\n </ul>\n\t\t\t\n <ul class = \"nav navbar-nav navbar-right\">\n <li><a href = \"/Account/Register\" id = \"registerLink\">Register</a></li>\n <li><a href = \"/Account/Login\" id = \"loginLink\">Log in</a></li>\n </ul>\n\t\t\t\n </div>\n\t\t\n </div>\n\t\n</div>"
},
{
"code": null,
"e": 188650,
"s": 188382,
"text": "It is CSS classes from Bootstrap like navbar, navbar inverse, and navbar fixed top. If you remove a few of these classes like navbar inverse, navbar fixed top and also uncomment the Bootstrap.css and then run your application again, you will see the following output."
},
{
"code": null,
"e": 188888,
"s": 188650,
"text": "You will see that we still have a navbar, but now it's not using inverse colors so it's white. It also doesn't stick to the top of the page. When you scroll down, the navigation bar scrolls off the top and you can no longer see it again."
},
{
"code": null,
"e": 189242,
"s": 188888,
"text": "In computer programming, unit testing is a software testing method by which individual units of source code are tested to determine whether they are fit for use. In other words, it is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation."
},
{
"code": null,
"e": 189485,
"s": 189242,
"text": "In procedural programming, a unit could be an entire module, but it is more commonly an individual function or procedure. In object-oriented programming, a unit is often an entire interface, such as a class, but could be an individual method."
},
{
"code": null,
"e": 189551,
"s": 189485,
"text": "Unit testing is often automated but it can also be done manually."
},
{
"code": null,
"e": 189818,
"s": 189551,
"text": "The primary goal of unit testing is to take the smallest piece of testable software in the application and determine whether it behaves exactly as you expect. Each unit is tested separately before integrating them into modules to test the interfaces between modules."
},
{
"code": null,
"e": 189940,
"s": 189818,
"text": "Let’s take a look at a simple example of unit testing in which we create a new ASP.NET MVC application with Unit Testing."
},
{
"code": null,
"e": 190016,
"s": 189940,
"text": "Step 1 − Open the Visual Studio and click File → New → Project menu option."
},
{
"code": null,
"e": 190044,
"s": 190016,
"text": "A new Project dialog opens."
},
{
"code": null,
"e": 190109,
"s": 190044,
"text": "Step 2 − From the left pane, select Templates > Visual C# > Web."
},
{
"code": null,
"e": 190170,
"s": 190109,
"text": "Step 3 − In the middle pane, select ASP.NET Web Application."
},
{
"code": null,
"e": 190368,
"s": 190170,
"text": "Step 4 − Enter the project name ‘MVCUnitTestingDemo’ in the Name field and click Ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project."
},
{
"code": null,
"e": 190611,
"s": 190368,
"text": "Step 5 − Select the MVC as template and don’t forget to check the Add unit tests checkbox which is at the bottom of dialog. You can also change the test project name as well, but in this example we leave it as is since it is the default name."
},
{
"code": null,
"e": 190743,
"s": 190611,
"text": "Once the project is created by Visual Studio, you will see a number of files and folders displayed in the Solution Explorer window."
},
{
"code": null,
"e": 190892,
"s": 190743,
"text": "Step 6 − You can see that two projects are there in the solution explorer. One is the ASP.NET Web project and the other is the unit testing project."
},
{
"code": null,
"e": 190961,
"s": 190892,
"text": "Step 7 − Run this application and you will see the following output."
},
{
"code": null,
"e": 191117,
"s": 190961,
"text": "As seen in the above screenshot, there are Home, About and Contact buttons on the navigation bar. Let’s select ‘About’ and you will see the following view."
},
{
"code": null,
"e": 191172,
"s": 191117,
"text": "Let’s select Contact and the following screen pops up."
},
{
"code": null,
"e": 191296,
"s": 191172,
"text": "Now let’s expand the ‘MVCUnitTestingDemo’ project and you will see the HomeController.cs file under the Controllers folder."
},
{
"code": null,
"e": 191377,
"s": 191296,
"text": "The HomeController contains three action methods as shown in the following code."
},
{
"code": null,
"e": 191905,
"s": 191377,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCUnitTestingDemo.Controllers {\n public class HomeController : Controller{\n public ActionResult Index(){\n return View();\n } \n\t\t\n public ActionResult About(){\n ViewBag.Message = \"Your application description page.\";\n return View();\n }\n\t\t\n public ActionResult Contact(){\n ViewBag.Message = \"Your contact page.\";\n return View();\n }\n }\n}"
},
{
"code": null,
"e": 192033,
"s": 191905,
"text": "Let’s expand the MVCUnitTestingDemo.Tests project and you will see the HomeControllerTest.cs file under the Controllers folder."
},
{
"code": null,
"e": 192126,
"s": 192033,
"text": "In this HomeControllerTest class, you will see three methods as shown in the following code."
},
{
"code": null,
"e": 193322,
"s": 192126,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing System.Web.Mvc;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n\nusing MVCUnitTestingDemo;\nusing MVCUnitTestingDemo.Controllers;\n\nnamespace MVCUnitTestingDemo.Tests.Controllers{\n [TestClass]\n public class HomeControllerTest{\n\t\n [TestMethod]\n public void Index(){\n // Arrange\n HomeController controller = new HomeController();\n // Act\n ViewResult result = controller.Index() as ViewResult;\n // Assert\n Assert.IsNotNull(result);\n }\n\t\t\n [TestMethod]\n public void About(){\n // Arrange\n HomeController controller = new HomeController();\n // Act\n ViewResult result = controller.About() as ViewResult;\n // Assert\n Assert.AreEqual(\"Your application description page.\", result.ViewBag.Message);\n }\n\t\t\n [TestMethod]\n public void Contact(){\n // Arrange\n HomeController controller = new HomeController();\n // Act\n ViewResult result = controller.Contact() as ViewResult;\n // Assert\n Assert.IsNotNull(result);\n }\n }\n}"
},
{
"code": null,
"e": 193483,
"s": 193322,
"text": "These three methods will test whether the Index, About and Contact action methods are working properly. To test these three action methods, go to the Test menu."
},
{
"code": null,
"e": 193536,
"s": 193483,
"text": "Select Run → All Tests to test these action methods."
},
{
"code": null,
"e": 193771,
"s": 193536,
"text": "Now you will see the Test Explorer on the left side in which you can see that all the tests are passed. Let us add one more action method, which will list all the employees. First we need to add an employee class in the Models folder."
},
{
"code": null,
"e": 193819,
"s": 193771,
"text": "Following is the Employee class implementation."
},
{
"code": null,
"e": 194132,
"s": 193819,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\n\nnamespace MVCUnitTestingDemo.Models{\n public class Employee{\n public int ID { get; set; }\n public string Name { get; set; }\n public DateTime JoiningDate { get; set; }\n public int Age { get; set; }\n }\n}"
},
{
"code": null,
"e": 194258,
"s": 194132,
"text": "We need to add EmployeeController. Right-click on the controller folder in the solution explorer and select Add → Controller."
},
{
"code": null,
"e": 194299,
"s": 194258,
"text": "It will display the Add Scaffold dialog."
},
{
"code": null,
"e": 194408,
"s": 194299,
"text": "Select the MVC 5 Controller – Empty option and click ‘Add’ button and the Add Controller dialog will appear."
},
{
"code": null,
"e": 194467,
"s": 194408,
"text": "Set the name to EmployeeController and click ‘Add’ button."
},
{
"code": null,
"e": 194650,
"s": 194467,
"text": "You will see a new C# file ‘EmployeeController.cs’ in the Controllers folder which is open for editing in Visual Studio. Let’s update the EmployeeController using the following code."
},
{
"code": null,
"e": 196070,
"s": 194650,
"text": "using MVCUnitTestingDemo.Models;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCUnitTestingDemo.Controllers {\n public class EmployeeController : Controller{\n [NonAction]\n\t\t\n public List<Employee> GetEmployeeList(){\n return new List<Employee>{\n new Employee{\n ID = 1,\n Name = \"Allan\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 23\n },\n\t\t\t\t\n new Employee{\n ID = 2,\n Name = \"Carson\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 45\n },\n\t\t\t\t\n new Employee{\n ID = 3,\n Name = \"Carson\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 37\n },\n\t\t\t\t\n new Employee{\n ID = 4,\n Name = \"Laura\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 26\n },\n };\n }\n \n // GET: Employee\n public ActionResult Index(){\n return View();\n }\n\t\t\n public ActionResult Employees(){\n var employees = from e in GetEmployeeList()\n orderby e.ID\n select e;\n return View(employees);\n }\n }\n}"
},
{
"code": null,
"e": 196166,
"s": 196070,
"text": "To add View for Employees action method, right-click on Employees action and select Add View..."
},
{
"code": null,
"e": 196306,
"s": 196166,
"text": "You will see the default name for view. Select ‘List’ from the Template dropdown and ‘Employee’ from the Model class dropdown and click Ok."
},
{
"code": null,
"e": 196480,
"s": 196306,
"text": "Now we need to add the link Employees list, let’s open the _layout.cshtml file which is under Views/Shared folder and add the link for employees list below the Contact link."
},
{
"code": null,
"e": 196550,
"s": 196480,
"text": "<li>@Html.ActionLink(\"Employees List\", \"Employees\", \"Employee\")</li>\n"
},
{
"code": null,
"e": 196610,
"s": 196550,
"text": "Following is the complete implementation of _layout.cshtml."
},
{
"code": null,
"e": 198447,
"s": 196610,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"utf-8\" />\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\">\n <title>@ViewBag.Title - My ASP.NET Application</title>\n @Styles.Render(\"~/Content/css\")\n @Scripts.Render(\"~/bundles/modernizr\")\n </head>\n\t\n <body>\n <div class = \"navbar navbar-inverse navbar-fixed-top\">\n <div class = \"container\">\n\t\t\t\n <div class = \"navbar-header\">\n <button type = \"button\" class = \"navbar-toggle\" datatoggle =\n \"collapse\" data-target = \".navbar-collapse\">\n <span class = \"icon-bar\"></span>\n <span class = \"icon-bar\"></span>\n <span class = \"icon-bar\"></span>\n </button>\n\t\t\t\t\t\n @Html.ActionLink(\"Application name\", \"Index\", \"Home\", new\n { area = \"\" }, new { @class = \"navbar-brand\" })\n </div>\n\t\t\t\t\n <div class = \"navbar-collapse collapse\">\n <ul class = \"nav navbar-nav\">\n <li>@Html.ActionLink(\"Home\", \"Index\", \"Home\")</li>\n <li>@Html.ActionLink(\"About\", \"About\", \"Home\")</li>\n <li>@Html.ActionLink(\"Contact\", \"Contact\", \"Home\")</li>\n <li>@Html.ActionLink(\"Employees List\", \"Employees\", \"Employee\")</li>\n </ul>\n\t\t\t\t\t\n @Html.Partial(\"_LoginPartial\")\n </div>\n\t\t\t\t\n </div>\n\t\t\t\n </div>\n\t\t\n <div class = \"container body-content\">\n @RenderBody()\n <hr />\n <footer>\n <p>© @DateTime.Now.Year - My ASP.NET Application</p>\n </footer>\n </div>\n\t\t\n @Scripts.Render(\"~/bundles/jquery\")\n @Scripts.Render(\"~/bundles/bootstrap\")\n @RenderSection(\"scripts\", required: false)\n\t\t\n </body>\n</html>"
},
{
"code": null,
"e": 198669,
"s": 198447,
"text": "To test Employees action method from the Employee controller, we need to add another test method in our unit testing project. Following s the EmployeeControllerTest class in which we will test the Employees action method."
},
{
"code": null,
"e": 198977,
"s": 198669,
"text": "[TestClass]\npublic class EmployeeControllerTest{\n [TestMethod]\n public void Employees(){\n // Arrange\n EmployeeController controller = new EmployeeController();\n\t\t\n // Act\n ViewResult result = controller.Index() as ViewResult;\n\t\t\n // Assert\n Assert.IsNotNull(result);\n }\n}"
},
{
"code": null,
"e": 199049,
"s": 198977,
"text": "Select Run → All Tests from the Test menu to test these action methods."
},
{
"code": null,
"e": 199177,
"s": 199049,
"text": "You can see that the Employees test method is also passed now. When you run the application, you will see the following output."
},
{
"code": null,
"e": 199269,
"s": 199177,
"text": "Click ‘Employees List’ option in the navigation bar and you will see the list of employees."
},
{
"code": null,
"e": 199719,
"s": 199269,
"text": "In this chapter, we will be covering how to deploy ASP.NET MVC application. After understating different concepts in ASP.NET MVC applications, now it’s time to understand the deployment process. So, whenever we are building any MVC application we are basically producing a dll file associated for the same with all the application settings and logic inside and these dlls are in the bin directory of the project as shown in the following screenshot."
},
{
"code": null,
"e": 199813,
"s": 199719,
"text": "Let’s take a look at a simple example in which we will deploy our example to Microsoft Azure."
},
{
"code": null,
"e": 199931,
"s": 199813,
"text": "Step 1 − Right-click on the project in the Solution Explorer and select Publish as shown in the following screenshot."
},
{
"code": null,
"e": 200016,
"s": 199931,
"text": "Step 2 − You will see the Publish Web dialog. Click on the Microsoft Azure Web Apps."
},
{
"code": null,
"e": 200052,
"s": 200016,
"text": "It will display the ‘Sign in’ page."
},
{
"code": null,
"e": 200117,
"s": 200052,
"text": "Step 3 − Enter credentials for the Microsoft Azure Subscription."
},
{
"code": null,
"e": 200210,
"s": 200117,
"text": "Once you’re successfully connected to your Azure account, you will see the following dialog."
},
{
"code": null,
"e": 200239,
"s": 200210,
"text": "Step 4 − Click ‘New’ button."
},
{
"code": null,
"e": 200440,
"s": 200239,
"text": "Step 5 − Enter the desired information on the above dialog such as Web App name, which must be a unique name. You will also need to enter App service plan, resource group, and then select your region."
},
{
"code": null,
"e": 200482,
"s": 200440,
"text": "Step 6 − Click ‘Next’ button to continue."
},
{
"code": null,
"e": 200554,
"s": 200482,
"text": "Step 7 − Click the ellipsis mark ‘...’ to select the connection string."
},
{
"code": null,
"e": 200737,
"s": 200554,
"text": "Step 8 − Select the server name and then choose the Windows Authentication option. Select the database name as well. Now you will see that the connection string is generated for you."
},
{
"code": null,
"e": 200772,
"s": 200737,
"text": "Step 9 − Click ‘Next’ to continue."
},
{
"code": null,
"e": 200929,
"s": 200772,
"text": "Step 10 − To check all the files and dlls which we will be publishing to Azure, click the Start Preview. Click ‘Publish’ button to publish your application."
},
{
"code": null,
"e": 201033,
"s": 200929,
"text": "Once the application is successfully published to Azure, you will see the message in the output window."
},
{
"code": null,
"e": 201183,
"s": 201033,
"text": "Step 11 − Now open your browser and enter the following URL ‘http://mymvcdemoapp.azurewebsites.net/employees’ and you will see the list of employees."
},
{
"code": null,
"e": 201311,
"s": 201183,
"text": "Step 12 − Now if you go to your Azure portal and click ‘App Services’, then you see that your application is deployed to Azure."
},
{
"code": null,
"e": 201445,
"s": 201311,
"text": "Step 13 − Click the name of your app and you will see the information related to that application such as URL, Status, Location, etc."
},
{
"code": null,
"e": 201615,
"s": 201445,
"text": "We have seen so far how to publish a web application to Azure app, after the application is created. You can also create an application, which will be deployed to Azure."
},
{
"code": null,
"e": 201659,
"s": 201615,
"text": "Let’s create a new ASP.NET MVC application."
},
{
"code": null,
"e": 201716,
"s": 201659,
"text": "Step 1 − Click Ok and you will see the following dialog."
},
{
"code": null,
"e": 201798,
"s": 201716,
"text": "Step 2 − Select MVC template and also check Host in the Cloud checkbox. Click Ok."
},
{
"code": null,
"e": 201909,
"s": 201798,
"text": "When the Configure Microsoft Azure Web App Settings dialog appears, make sure that you are signed in to Azure."
},
{
"code": null,
"e": 201981,
"s": 201909,
"text": "You can see the default name, but you can also change the Web App name."
},
{
"code": null,
"e": 202058,
"s": 201981,
"text": "Step 3 − Enter the desired information as shown in the following screenshot."
},
{
"code": null,
"e": 202171,
"s": 202058,
"text": "Step 4 − Select the ‘Create new server’ from the Database server dropdown and you will see the additional field."
},
{
"code": null,
"e": 202241,
"s": 202171,
"text": "Step 5 − Enter the Database server, username, and password. Click Ok."
},
{
"code": null,
"e": 202353,
"s": 202241,
"text": "Step 6 − Once the project is created, run the application and you will see that it is running on the localhost."
},
{
"code": null,
"e": 202475,
"s": 202353,
"text": "Step 7 − To deploy these applications to Azure, right-click on the project in the solution explorer and select ‘Publish’."
},
{
"code": null,
"e": 202510,
"s": 202475,
"text": "You will see the following dialog."
},
{
"code": null,
"e": 202557,
"s": 202510,
"text": "Step 8 − Click the ‘Microsoft Azure Web Apps’."
},
{
"code": null,
"e": 202636,
"s": 202557,
"text": "Step 9 − Select your application name from the Existing Web Apps and click Ok."
},
{
"code": null,
"e": 202723,
"s": 202636,
"text": "Step 10 − Click the ‘Validate Connection’ button to check for the connection on Azure."
},
{
"code": null,
"e": 202759,
"s": 202723,
"text": "Step 11 − Click ‘Next’ to continue."
},
{
"code": null,
"e": 202836,
"s": 202759,
"text": "Now you will see that the connection string is already generated by default."
},
{
"code": null,
"e": 202872,
"s": 202836,
"text": "Step 12 − Click ‘Next’ to continue."
},
{
"code": null,
"e": 202975,
"s": 202872,
"text": "Step 13 − To check all the files and dlls which will be published to Azure, click the ‘Start Preview’."
},
{
"code": null,
"e": 203141,
"s": 202975,
"text": "Step 14 − Click ‘Publish’ button to publish your application. Once the application is successfully published to Azure, you will see the message in the output window."
},
{
"code": null,
"e": 203211,
"s": 203141,
"text": "You will also see that the application is now running from the cloud."
},
{
"code": null,
"e": 203278,
"s": 203211,
"text": "Let’s go to Azure portal again. You will see the app here as well."
},
{
"code": null,
"e": 203500,
"s": 203278,
"text": "In this chapter, we will cover Self-Hosting. Self-Hosting creates a runtime environment for the application to run in any environment say MAC, or in Linux box, etc. Self-Hosting also means it will have a mini CLR version."
},
{
"code": null,
"e": 203555,
"s": 203500,
"text": "Let’s take a look at a simple example of self-hosting."
},
{
"code": null,
"e": 203697,
"s": 203555,
"text": "Step 1 − Once your ASP.NET MVC application is completed and you want to use selfhosting, right-click on the Project in the solution explorer."
},
{
"code": null,
"e": 203732,
"s": 203697,
"text": "You will see the following dialog."
},
{
"code": null,
"e": 203818,
"s": 203732,
"text": "Step 2 − Click the ‘Custom’ option, which will display the New Custom Profile dialog."
},
{
"code": null,
"e": 203864,
"s": 203818,
"text": "Step 3 − Enter the profile name and click Ok."
},
{
"code": null,
"e": 203993,
"s": 203864,
"text": "Step 4 − Select the File System from the Publish method dropdown list and also specify the target location. Click ‘Next’ button."
},
{
"code": null,
"e": 204035,
"s": 203993,
"text": "Step 5 − Expand the File Publish Options."
},
{
"code": null,
"e": 204175,
"s": 204035,
"text": "Step 6 − Check the ‘Delete all existing files prior to publish’ and ‘Precompile during publishing’ checkboxes and click ‘Next’ to continue."
},
{
"code": null,
"e": 204259,
"s": 204175,
"text": "Step 7 − Click ‘Publish’ button, it will publish the files at the desired location."
},
{
"code": null,
"e": 204337,
"s": 204259,
"text": "You will see all the files and folders in the target location on your system."
},
{
"code": null,
"e": 204407,
"s": 204337,
"text": "It will have all the files required to get deployed on the localhost."
},
{
"code": null,
"e": 204563,
"s": 204407,
"text": "Step 8 − Now open the Turn Windows Feature on or off and Expand Internet Information Services → World Wide Web Services → Application Development Features."
},
{
"code": null,
"e": 204640,
"s": 204563,
"text": "Step 9 − Check the checkboxes as shown in the above screenshot and click Ok."
},
{
"code": null,
"e": 204715,
"s": 204640,
"text": "Step 10 − Let’s open the IIS Manager as shown in the following screenshot."
},
{
"code": null,
"e": 204818,
"s": 204715,
"text": "Step 11 − You will see different connections on the left side of the screen, right-click on MyWebSite."
},
{
"code": null,
"e": 204872,
"s": 204818,
"text": "Step 12 − Select the ‘Convert to Application’ option."
},
{
"code": null,
"e": 204986,
"s": 204872,
"text": "As you can see, its physical path is the same as we have mentioned above while publishing, using the File system."
},
{
"code": null,
"e": 205018,
"s": 204986,
"text": "Step 13 − Click Ok to continue."
},
{
"code": null,
"e": 205061,
"s": 205018,
"text": "Now you can see that its icon has changed."
},
{
"code": null,
"e": 205146,
"s": 205061,
"text": "Step 14 − Open your browser and specify the following URL http://localhost/MyWebSite"
},
{
"code": null,
"e": 205236,
"s": 205146,
"text": "You can see that it is running from the folder which we have specified during deployment."
},
{
"code": null,
"e": 205271,
"s": 205236,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 205285,
"s": 205271,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 205320,
"s": 205285,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 205343,
"s": 205320,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 205377,
"s": 205343,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 205397,
"s": 205377,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 205432,
"s": 205397,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 205449,
"s": 205432,
"text": " University Code"
},
{
"code": null,
"e": 205484,
"s": 205449,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 205501,
"s": 205484,
"text": " University Code"
},
{
"code": null,
"e": 205535,
"s": 205501,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 205550,
"s": 205535,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 205557,
"s": 205550,
"text": " Print"
},
{
"code": null,
"e": 205568,
"s": 205557,
"text": " Add Notes"
}
] |
PreparedStatementSetter Interface | The org.springframework.jdbc.core.PreparedStatementSetter interface acts as a general callback interface used by the JdbcTemplate class. This interface sets values on a PreparedStatement provided by the JdbcTemplate class, for each of a number of updates in a batch using the same SQL.
Implementations are responsible for setting any necessary parameters. SQL with placeholders will already have been supplied. It's easier to use this interface than PreparedStatementCreator. The JdbcTemplate will create the PreparedStatement, with the callback only being responsible for setting parameter values.
Following is the declaration for org.springframework.jdbc.core.PreparedStatementSetter interface −
public interface PreparedStatementSetter
Step 1 − Create a JdbcTemplate object using a configured datasource.
Step 1 − Create a JdbcTemplate object using a configured datasource.
Step 2 − Use JdbcTemplate object methods to make database operations while passing PreparedStatementSetter object to replace place holders in query.
Step 2 − Use JdbcTemplate object methods to make database operations while passing PreparedStatementSetter object to replace place holders in query.
Following example will demonstrate how to read a query using JdbcTemplate class and PreparedStatementSetter interface. We'll read available record of a student in Student Table.
final String SQL = "select * from Student where id = ? ";
List <Student> students = jdbcTemplateObject.query(
SQL, new PreparedStatementSetter() {
public void setValues(PreparedStatement preparedStatement) throws SQLException {
preparedStatement.setInt(1, id);
}
},
new StudentMapper());
Where,
SQL − Select query to read students.
SQL − Select query to read students.
jdbcTemplateObject − StudentJDBCTemplate object to read student object from database.
jdbcTemplateObject − StudentJDBCTemplate object to read student object from database.
PreparedStatementSetter − PreparedStatementSetter object to set parameters in query.
PreparedStatementSetter − PreparedStatementSetter object to set parameters in query.
StudentMapper − StudentMapper is a RowMapper object to map each fetched record to student object.
StudentMapper − StudentMapper is a RowMapper object to map each fetched record to student object.
To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will select a query. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
Following is the content of the Data Access Object interface file StudentDAO.java.
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
public interface StudentDAO {
/**
* This is the method to be used to initialize
* database resources ie. connection.
*/
public void setDataSource(DataSource ds);
/**
* This is the method to be used to list down
* a record from the Student table corresponding
* to a passed student id.
*/
public Student getStudent(Integer id);
}
Following is the content of the Student.java file.
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
Following is the content of the StudentMapper.java file.
package com.tutorialspoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class StudentMapper implements RowMapper<Student> {
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
return student;
}
}
Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO.
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class StudentJDBCTemplate implements StudentDAO {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public Student getStudent(final Integer id) {
final String SQL = "select * from Student where id = ? ";
List <Student> students = jdbcTemplateObject.query(
SQL, new PreparedStatementSetter() {
public void setValues(PreparedStatement preparedStatement) throws SQLException {
preparedStatement.setInt(1, id);
}
},
new StudentMapper()
);
return students.get(0);
}
}
Following is the content of the MainApp.java file.
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
Student student = studentJDBCTemplate.getStudent(1);
System.out.print("ID : " + student.getId() );
System.out.println(", Age : " + student.getAge());
}
}
Following is the configuration file Beans.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
<!-- Initialization for data source -->
<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.cj.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
<property name = "username" value = "root"/>
<property name = "password" value = "admin"/>
</bean>
<!-- Definition for studentJDBCTemplate bean -->
<bean id = "studentJDBCTemplate"
class = "com.tutorialspoint.StudentJDBCTemplate">
<property name = "dataSource" ref = "dataSource" />
</bean>
</beans>
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message.
ID : 1, Age : 17
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2682,
"s": 2396,
"text": "The org.springframework.jdbc.core.PreparedStatementSetter interface acts as a general callback interface used by the JdbcTemplate class. This interface sets values on a PreparedStatement provided by the JdbcTemplate class, for each of a number of updates in a batch using the same SQL."
},
{
"code": null,
"e": 2995,
"s": 2682,
"text": "Implementations are responsible for setting any necessary parameters. SQL with placeholders will already have been supplied. It's easier to use this interface than PreparedStatementCreator. The JdbcTemplate will create the PreparedStatement, with the callback only being responsible for setting parameter values."
},
{
"code": null,
"e": 3094,
"s": 2995,
"text": "Following is the declaration for org.springframework.jdbc.core.PreparedStatementSetter interface −"
},
{
"code": null,
"e": 3136,
"s": 3094,
"text": "public interface PreparedStatementSetter\n"
},
{
"code": null,
"e": 3205,
"s": 3136,
"text": "Step 1 − Create a JdbcTemplate object using a configured datasource."
},
{
"code": null,
"e": 3274,
"s": 3205,
"text": "Step 1 − Create a JdbcTemplate object using a configured datasource."
},
{
"code": null,
"e": 3423,
"s": 3274,
"text": "Step 2 − Use JdbcTemplate object methods to make database operations while passing PreparedStatementSetter object to replace place holders in query."
},
{
"code": null,
"e": 3572,
"s": 3423,
"text": "Step 2 − Use JdbcTemplate object methods to make database operations while passing PreparedStatementSetter object to replace place holders in query."
},
{
"code": null,
"e": 3750,
"s": 3572,
"text": "Following example will demonstrate how to read a query using JdbcTemplate class and PreparedStatementSetter interface. We'll read available record of a student in Student Table."
},
{
"code": null,
"e": 4058,
"s": 3750,
"text": "final String SQL = \"select * from Student where id = ? \";\nList <Student> students = jdbcTemplateObject.query(\n SQL, new PreparedStatementSetter() {\n \n public void setValues(PreparedStatement preparedStatement) throws SQLException {\n preparedStatement.setInt(1, id);\n }\n},\nnew StudentMapper());\n"
},
{
"code": null,
"e": 4065,
"s": 4058,
"text": "Where,"
},
{
"code": null,
"e": 4102,
"s": 4065,
"text": "SQL − Select query to read students."
},
{
"code": null,
"e": 4139,
"s": 4102,
"text": "SQL − Select query to read students."
},
{
"code": null,
"e": 4225,
"s": 4139,
"text": "jdbcTemplateObject − StudentJDBCTemplate object to read student object from database."
},
{
"code": null,
"e": 4311,
"s": 4225,
"text": "jdbcTemplateObject − StudentJDBCTemplate object to read student object from database."
},
{
"code": null,
"e": 4396,
"s": 4311,
"text": "PreparedStatementSetter − PreparedStatementSetter object to set parameters in query."
},
{
"code": null,
"e": 4481,
"s": 4396,
"text": "PreparedStatementSetter − PreparedStatementSetter object to set parameters in query."
},
{
"code": null,
"e": 4579,
"s": 4481,
"text": "StudentMapper − StudentMapper is a RowMapper object to map each fetched record to student object."
},
{
"code": null,
"e": 4677,
"s": 4579,
"text": "StudentMapper − StudentMapper is a RowMapper object to map each fetched record to student object."
},
{
"code": null,
"e": 4920,
"s": 4677,
"text": "To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will select a query. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application."
},
{
"code": null,
"e": 5003,
"s": 4920,
"text": "Following is the content of the Data Access Object interface file StudentDAO.java."
},
{
"code": null,
"e": 5468,
"s": 5003,
"text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\n\npublic interface StudentDAO {\n /** \n * This is the method to be used to initialize\n * database resources ie. connection.\n */\n public void setDataSource(DataSource ds);\n \n /** \n * This is the method to be used to list down\n * a record from the Student table corresponding\n * to a passed student id.\n */\n public Student getStudent(Integer id);\n}"
},
{
"code": null,
"e": 5519,
"s": 5468,
"text": "Following is the content of the Student.java file."
},
{
"code": null,
"e": 5991,
"s": 5519,
"text": "package com.tutorialspoint;\n\npublic class Student {\n private Integer age;\n private String name;\n private Integer id;\n\n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n return age;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n public void setId(Integer id) {\n this.id = id;\n }\n public Integer getId() {\n return id;\n }\n}"
},
{
"code": null,
"e": 6048,
"s": 5991,
"text": "Following is the content of the StudentMapper.java file."
},
{
"code": null,
"e": 6506,
"s": 6048,
"text": "package com.tutorialspoint;\n\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.springframework.jdbc.core.RowMapper;\n\npublic class StudentMapper implements RowMapper<Student> {\n public Student mapRow(ResultSet rs, int rowNum) throws SQLException {\n Student student = new Student();\n student.setId(rs.getInt(\"id\"));\n student.setName(rs.getString(\"name\"));\n student.setAge(rs.getInt(\"age\"));\n return student;\n }\n}"
},
{
"code": null,
"e": 6616,
"s": 6506,
"text": "Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO."
},
{
"code": null,
"e": 7504,
"s": 6616,
"text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\nimport org.springframework.jdbc.core.JdbcTemplate;\n\npublic class StudentJDBCTemplate implements StudentDAO {\n private DataSource dataSource;\n private JdbcTemplate jdbcTemplateObject;\n \n public void setDataSource(DataSource dataSource) {\n this.dataSource = dataSource;\n this.jdbcTemplateObject = new JdbcTemplate(dataSource);\n }\n public Student getStudent(final Integer id) {\n final String SQL = \"select * from Student where id = ? \";\n List <Student> students = jdbcTemplateObject.query(\n SQL, new PreparedStatementSetter() {\n public void setValues(PreparedStatement preparedStatement) throws SQLException {\n preparedStatement.setInt(1, id);\n }\n },\n new StudentMapper()\n );\n return students.get(0);\n }\n}"
},
{
"code": null,
"e": 7555,
"s": 7504,
"text": "Following is the content of the MainApp.java file."
},
{
"code": null,
"e": 8151,
"s": 7555,
"text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean(\"studentJDBCTemplate\");\n Student student = studentJDBCTemplate.getStudent(1);\n System.out.print(\"ID : \" + student.getId() );\n System.out.println(\", Age : \" + student.getAge()); \n }\n}"
},
{
"code": null,
"e": 8198,
"s": 8151,
"text": "Following is the configuration file Beans.xml."
},
{
"code": null,
"e": 9151,
"s": 8198,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \">\n\n <!-- Initialization for data source -->\n <bean id = \"dataSource\" \n class = \"org.springframework.jdbc.datasource.DriverManagerDataSource\">\n <property name = \"driverClassName\" value = \"com.mysql.cj.jdbc.Driver\"/>\n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/TEST\"/>\n <property name = \"username\" value = \"root\"/>\n <property name = \"password\" value = \"admin\"/>\n </bean>\n\n <!-- Definition for studentJDBCTemplate bean -->\n <bean id = \"studentJDBCTemplate\" \n class = \"com.tutorialspoint.StudentJDBCTemplate\">\n <property name = \"dataSource\" ref = \"dataSource\" /> \n </bean> \n</beans>"
},
{
"code": null,
"e": 9329,
"s": 9151,
"text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message."
},
{
"code": null,
"e": 9347,
"s": 9329,
"text": "ID : 1, Age : 17\n"
},
{
"code": null,
"e": 9354,
"s": 9347,
"text": " Print"
},
{
"code": null,
"e": 9365,
"s": 9354,
"text": " Add Notes"
}
] |
Maven Interview Questions | Dear readers, these Maven Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Maven. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:
Normally a deployment process consists of following steps −
Check-in the code from all projects in progress into the SVN or source code repository and tag it.
Check-in the code from all projects in progress into the SVN or source code repository and tag it.
Download the complete source code from SVN.
Download the complete source code from SVN.
Build the application.
Build the application.
Store the build output either WAR or EAR file to a common network location.
Store the build output either WAR or EAR file to a common network location.
Get the file from network and deploy the file to the production site.
Get the file from network and deploy the file to the production site.
Updated the documentation with date and updated version number of the application.
Updated the documentation with date and updated version number of the application.
Maven is a project management and comprehension tool. Maven provides developers a complete build lifecycle framework. Development team can automate the project's build infrastructure in almost no time as Maven uses a standard directory layout and a default build lifecycle.
Maven uses Convention over Configuration which means developers are not required to create build process themselves. Developers do not have to mention each and every configuration details.
Maven provides developers ways to manage following −
Builds
Documentation
Reporting
Dependencies
SCMs
Releases
Distribution
mailing list
Type the following command −
mvn --version
POM stands for Project Object Model. It is fundamental Unit of Work in Maven. It is an XML file. It always resides in the base directory of the project as pom.xml. It contains information about the project and various configuration details used by Maven to build the project(s).
POM contains the some of the following configuration information −
project dependencies
plugins
goals
build profiles
project version
developers
mailing list
An artifact is a file, usually a JAR that gets deployed to a Maven repository. A Maven build produces one or more artifacts, such as a compiled JAR and a "sources" JAR.
Each artifact has a group ID (usually a reversed domain name, like com.example.foo), an artifact ID (just a name), and a version string. The three together uniquely identify the artifact. A project's dependencies are specified as artifacts.
A Build Lifecycle is a well defined sequence of phases which define the order in which the goals are to be executed. Here phase represents a stage in life cycle.
The three build lifecycles are −
clean:cleans up artifacts created by prior builds.
clean:cleans up artifacts created by prior builds.
default (or build):This is used to build the application.
default (or build):This is used to build the application.
site: generates site documentation for the project.
site: generates site documentation for the project.
Type the command −
mvn site
This command removes the target directory with all the build data before starting the build process.
Following are the phases −
validate − validate the project is correct and all necessary information is available.
validate − validate the project is correct and all necessary information is available.
compile − compile the source code of the project.
compile − compile the source code of the project.
test − test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
test − test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
package − take the compiled code and package it in its distributable format, such as a JAR.
package − take the compiled code and package it in its distributable format, such as a JAR.
integration-test − process and deploy the package if necessary into an environment where integration tests can be run.
integration-test − process and deploy the package if necessary into an environment where integration tests can be run.
verify − run any checks to verify the package is valid and meets quality criteria.
verify − run any checks to verify the package is valid and meets quality criteria.
install − install the package into the local repository, for use as a dependency in other projects locally.
install − install the package into the local repository, for use as a dependency in other projects locally.
deploy − done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.
deploy − done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.
A goal represents a specific task which contributes to the building and managing of a project. It may be bound to zero or more build phases. A goal not bound to any build phase could be executed outside of the build lifecycle by direct invocation.
This command will clean the project, copy the dependencies and package the project (executing all phases up to package).
The clean lifecycle consists of the following phases −
pre-clean
clean
post-clean
The phases in Site Lifecycle are −
pre-site
site
post-site
site-deploy
A Build profile is a set of configuration values which can be used to set or override default values of Maven build. Using a build profile, you can customize build for different environments such as Production v/s Development environments.
Build profiles are of three types −
Per Project − Defined in the project POM file, pom.xml.
Per Project − Defined in the project POM file, pom.xml.
Per User − Defined in Maven settings xml file (%USER_HOME%/.m2/settings.xml).
Per User − Defined in Maven settings xml file (%USER_HOME%/.m2/settings.xml).
Global − Defined in Maven global settings xml file (%M2_HOME%/conf/settings.xml)
Global − Defined in Maven global settings xml file (%M2_HOME%/conf/settings.xml)
A Maven Build Profile can be activated in various ways −
Explicitly using command console input.
Explicitly using command console input.
Through maven settings.
Through maven settings.
Based on environment variables (User/System variables).
Based on environment variables (User/System variables).
OS Settings (for example, Windows family).
OS Settings (for example, Windows family).
Present/missing files.
Present/missing files.
A repository is a place i.e. directory where all the project jars, library jar, plugins or any other project specific artifacts are stored and can be used by Maven easily.
Maven repository are of three types: local, central, remote
Maven local repository is a folder location on your machine. It gets created when you run any maven command for the first time. Maven local repository keeps your project's all dependencies (library jars, plugin jars etc).
~/m2./repository.
mvn install
It is repository provided by Maven community. It contains a large number of commonly used libraries. When Maven does not find any dependency in local repository, it starts searching in central repository using following URL: http://repo1.maven.org/maven2/.
Sometimes, Maven does not find a mentioned dependency in central repository as well then it stops the build process and output error message to console. To prevent such situation, Maven provides concept of Remote Repository which is developer's own custom repository containing required libraries or other project jars.
Following is the search pattern −
Step 1 − Search dependency in local repository, if not found, move to step 2 else if found then do the further processing.
Step 1 − Search dependency in local repository, if not found, move to step 2 else if found then do the further processing.
Step 2 − Search dependency in central repository, if not found and remote repository/repositories is/are mentioned then move to step 4 else if found, then it is downloaded to local repository for future reference.
Step 2 − Search dependency in central repository, if not found and remote repository/repositories is/are mentioned then move to step 4 else if found, then it is downloaded to local repository for future reference.
Step 3 − If a remote repository has not been mentioned, Maven simply stops the processing and throws error (Unable to find dependency).
Step 3 − If a remote repository has not been mentioned, Maven simply stops the processing and throws error (Unable to find dependency).
Step 4 − Search dependency in remote repository or repositories, if found then it is downloaded to local repository for future reference otherwise Maven as expected stop processing and throws error (Unable to find dependency).
Step 4 − Search dependency in remote repository or repositories, if found then it is downloaded to local repository for future reference otherwise Maven as expected stop processing and throws error (Unable to find dependency).
Maven Plugins are used to −
create jar file.
create war file.
compile code files.
unit testing of code.
create project documentation.
create project reports.
Maven provides following two types of Plugins −
Build plugins − They execute during the build and should be configured in the <build/> element of pom.xml
Build plugins − They execute during the build and should be configured in the <build/> element of pom.xml
Reporting plugins − They execute during the site generation and they should be configured in the <reporting/> element of the pom.xml
Reporting plugins − They execute during the site generation and they should be configured in the <reporting/> element of the pom.xml
Maven dependency management using concept of Maven Repositories (Local, Central, Remote). Suppose dependency is not available in any of remote repositories and central repository; in such scenarios Maven uses concept of External Dependency.
External dependencies (library jar location) can be configured in pom.xml in same way as other dependencies.
Specify groupId same as name of the library.
Specify artifactId same as name of the library.
Specify scope as system.
Specify system path relative to project location.
Archetype is a Maven plugin whose task is to create a project structure as per its template.
Type the following command −
mvn archetype:generate
SNAPSHOT is a special version that indicates a current development copy. Unlike regular versions, Maven checks for a new SNAPSHOT version in a remote repository for every build.
In case of Version, if Maven once downloaded the mentioned version say data-service:1.0, it will never try to download a newer 1.0 available in repository. To download the updated code, data-service version is be upgraded to 1.1.
In case of SNAPSHOT, Maven will automatically fetch the latest SNAPSHOT (data-service:1.0-SNAPSHOT) everytime app-ui team build their project.
Transitive dependency means to avoid needing to discover and specify the libraries that your own dependencies require, and including them automatically.
It means to directly specify the versions of artifacts to be used when they are encountered in transitive dependencies. For an example project C can include B as a dependency in its dependencyManagement section and directly control which version of B is to be used when it is ever referenced.
Maven determines what version of a dependency is to be used when multiple versions of an artifact are encountered. If two dependency versions are at the same depth in the dependency tree, the first declared dependency will be used. This is called dependency mediation.
Dependency scope includes dependencies as per the current stage of the build. Various Dependency Scopes are −
compile − This scope indicates that dependency is available in classpath of project. It is default scope.
compile − This scope indicates that dependency is available in classpath of project. It is default scope.
provided − This scope indicates that dependency is to be provided by JDK or web-Server/Container at runtime.
provided − This scope indicates that dependency is to be provided by JDK or web-Server/Container at runtime.
runtime − This scope indicates that dependency is not required for compilation, but is required during execution.
runtime − This scope indicates that dependency is not required for compilation, but is required during execution.
test − This scope indicates that the dependency is only available for the test compilation and execution phases.
test − This scope indicates that the dependency is only available for the test compilation and execution phases.
system − This scope indicates that you have to provide the system path.
system − This scope indicates that you have to provide the system path.
import − This scope is only used when dependency is of type pom. This scope indicates that the specified POM should be replaced with the dependencies in that POM's <dependencyManagement> section.
import − This scope is only used when dependency is of type pom. This scope indicates that the specified POM should be replaced with the dependencies in that POM's <dependencyManagement> section.
{groupId,artifactId,type,classifier}.
To reference a property defined in your pom.xml, the property name uses the names of the XML elements that define the value, with "pom" being allowed as an alias for the project (root) element.
So pom.namereferstothenameoftheproject,{pom.version} refers to the version of the project, ${pom.build.finalName} refers to the final name of the file created when the built project is packaged, etc.
Some of the valid packaging values are jar, war, ear and pom. If no packaging value has been specified, it will default to jar.
pom
The <execution> element contains information's required for the execution of a plugin.
<groupId>:<artifactId>:<version>
All POMs inherit from a parent (despite explicitly defined or not). This base POM is known as the Super POM, and contains values inherited by default.
Profiles are specified using a subset of the elements available in the POM itself.
<repositories>, <pluginRepositories>,<dependencies>, <plugins> ,<properties>, <modules><reporting>,<dependencyManagement>,<distributionManagement>
To give portability to projects ( e.g. windows, linux etc).
It uses less storage, it makes checking out project quicker, non need for versioning JAR files.
Use the command −
mvn o package.
Using the exclusion element.
Dependency with scope system are always available and are not looked up in repository, they are usually used to tell Maven about dependencies which are provided by the JDK or the VM. Thus, system dependencies are especially useful for resolving dependencies on artifacts which are now provided by the JDK.
Any transitive dependency can be marked as optional using "optional" element. As example, A depends upon B and B depends upon C. Now B marked C as optional. Then A will not use C.
Any transitive dependency can be exclude using "exclusion" element. As example, A depends upon B and B depends upon C then A can mark C as excluded.
You can put the clean plugin inside the execution tag in pom.xml file.
set <inherited> to false.
It means that you have executed a plugin multiple times with the same <id>. Provide each <execution> with a unique <id> then it would be ok.
A mojo is a Maven plain Old Java Object. Each mojo is an executable goal in Maven, and a plugin is a distribution of one or more related mojos.
Ant is simply a toolbox whereas Maven is about the application of patterns in order to achieve an infrastructure which displays the characteristics of visibility, reusability, maintainability, and comprehensibility. It is wrong to consider Maven as a build tool and just a replacement for Ant.
Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)
34 Lectures
4 hours
Karthikeya T
14 Lectures
1.5 hours
Quaatso Learning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2494,
"s": 2060,
"text": "Dear readers, these Maven Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Maven. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:"
},
{
"code": null,
"e": 2554,
"s": 2494,
"text": "Normally a deployment process consists of following steps −"
},
{
"code": null,
"e": 2653,
"s": 2554,
"text": "Check-in the code from all projects in progress into the SVN or source code repository and tag it."
},
{
"code": null,
"e": 2752,
"s": 2653,
"text": "Check-in the code from all projects in progress into the SVN or source code repository and tag it."
},
{
"code": null,
"e": 2796,
"s": 2752,
"text": "Download the complete source code from SVN."
},
{
"code": null,
"e": 2840,
"s": 2796,
"text": "Download the complete source code from SVN."
},
{
"code": null,
"e": 2863,
"s": 2840,
"text": "Build the application."
},
{
"code": null,
"e": 2886,
"s": 2863,
"text": "Build the application."
},
{
"code": null,
"e": 2962,
"s": 2886,
"text": "Store the build output either WAR or EAR file to a common network location."
},
{
"code": null,
"e": 3038,
"s": 2962,
"text": "Store the build output either WAR or EAR file to a common network location."
},
{
"code": null,
"e": 3108,
"s": 3038,
"text": "Get the file from network and deploy the file to the production site."
},
{
"code": null,
"e": 3178,
"s": 3108,
"text": "Get the file from network and deploy the file to the production site."
},
{
"code": null,
"e": 3261,
"s": 3178,
"text": "Updated the documentation with date and updated version number of the application."
},
{
"code": null,
"e": 3344,
"s": 3261,
"text": "Updated the documentation with date and updated version number of the application."
},
{
"code": null,
"e": 3618,
"s": 3344,
"text": "Maven is a project management and comprehension tool. Maven provides developers a complete build lifecycle framework. Development team can automate the project's build infrastructure in almost no time as Maven uses a standard directory layout and a default build lifecycle."
},
{
"code": null,
"e": 3807,
"s": 3618,
"text": "Maven uses Convention over Configuration which means developers are not required to create build process themselves. Developers do not have to mention each and every configuration details."
},
{
"code": null,
"e": 3860,
"s": 3807,
"text": "Maven provides developers ways to manage following −"
},
{
"code": null,
"e": 3867,
"s": 3860,
"text": "Builds"
},
{
"code": null,
"e": 3881,
"s": 3867,
"text": "Documentation"
},
{
"code": null,
"e": 3891,
"s": 3881,
"text": "Reporting"
},
{
"code": null,
"e": 3904,
"s": 3891,
"text": "Dependencies"
},
{
"code": null,
"e": 3909,
"s": 3904,
"text": "SCMs"
},
{
"code": null,
"e": 3918,
"s": 3909,
"text": "Releases"
},
{
"code": null,
"e": 3931,
"s": 3918,
"text": "Distribution"
},
{
"code": null,
"e": 3944,
"s": 3931,
"text": "mailing list"
},
{
"code": null,
"e": 3973,
"s": 3944,
"text": "Type the following command −"
},
{
"code": null,
"e": 3987,
"s": 3973,
"text": "mvn --version"
},
{
"code": null,
"e": 4266,
"s": 3987,
"text": "POM stands for Project Object Model. It is fundamental Unit of Work in Maven. It is an XML file. It always resides in the base directory of the project as pom.xml. It contains information about the project and various configuration details used by Maven to build the project(s)."
},
{
"code": null,
"e": 4333,
"s": 4266,
"text": "POM contains the some of the following configuration information −"
},
{
"code": null,
"e": 4354,
"s": 4333,
"text": "project dependencies"
},
{
"code": null,
"e": 4362,
"s": 4354,
"text": "plugins"
},
{
"code": null,
"e": 4368,
"s": 4362,
"text": "goals"
},
{
"code": null,
"e": 4383,
"s": 4368,
"text": "build profiles"
},
{
"code": null,
"e": 4399,
"s": 4383,
"text": "project version"
},
{
"code": null,
"e": 4410,
"s": 4399,
"text": "developers"
},
{
"code": null,
"e": 4423,
"s": 4410,
"text": "mailing list"
},
{
"code": null,
"e": 4592,
"s": 4423,
"text": "An artifact is a file, usually a JAR that gets deployed to a Maven repository. A Maven build produces one or more artifacts, such as a compiled JAR and a \"sources\" JAR."
},
{
"code": null,
"e": 4833,
"s": 4592,
"text": "Each artifact has a group ID (usually a reversed domain name, like com.example.foo), an artifact ID (just a name), and a version string. The three together uniquely identify the artifact. A project's dependencies are specified as artifacts."
},
{
"code": null,
"e": 4995,
"s": 4833,
"text": "A Build Lifecycle is a well defined sequence of phases which define the order in which the goals are to be executed. Here phase represents a stage in life cycle."
},
{
"code": null,
"e": 5028,
"s": 4995,
"text": "The three build lifecycles are −"
},
{
"code": null,
"e": 5079,
"s": 5028,
"text": "clean:cleans up artifacts created by prior builds."
},
{
"code": null,
"e": 5130,
"s": 5079,
"text": "clean:cleans up artifacts created by prior builds."
},
{
"code": null,
"e": 5189,
"s": 5130,
"text": "default (or build):This is used to build the application. "
},
{
"code": null,
"e": 5248,
"s": 5189,
"text": "default (or build):This is used to build the application. "
},
{
"code": null,
"e": 5300,
"s": 5248,
"text": "site: generates site documentation for the project."
},
{
"code": null,
"e": 5352,
"s": 5300,
"text": "site: generates site documentation for the project."
},
{
"code": null,
"e": 5371,
"s": 5352,
"text": "Type the command −"
},
{
"code": null,
"e": 5380,
"s": 5371,
"text": "mvn site"
},
{
"code": null,
"e": 5481,
"s": 5380,
"text": "This command removes the target directory with all the build data before starting the build process."
},
{
"code": null,
"e": 5508,
"s": 5481,
"text": "Following are the phases −"
},
{
"code": null,
"e": 5595,
"s": 5508,
"text": "validate − validate the project is correct and all necessary information is available."
},
{
"code": null,
"e": 5682,
"s": 5595,
"text": "validate − validate the project is correct and all necessary information is available."
},
{
"code": null,
"e": 5732,
"s": 5682,
"text": "compile − compile the source code of the project."
},
{
"code": null,
"e": 5782,
"s": 5732,
"text": "compile − compile the source code of the project."
},
{
"code": null,
"e": 5924,
"s": 5782,
"text": "test − test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed"
},
{
"code": null,
"e": 6066,
"s": 5924,
"text": "test − test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed"
},
{
"code": null,
"e": 6158,
"s": 6066,
"text": "package − take the compiled code and package it in its distributable format, such as a JAR."
},
{
"code": null,
"e": 6250,
"s": 6158,
"text": "package − take the compiled code and package it in its distributable format, such as a JAR."
},
{
"code": null,
"e": 6369,
"s": 6250,
"text": "integration-test − process and deploy the package if necessary into an environment where integration tests can be run."
},
{
"code": null,
"e": 6488,
"s": 6369,
"text": "integration-test − process and deploy the package if necessary into an environment where integration tests can be run."
},
{
"code": null,
"e": 6571,
"s": 6488,
"text": "verify − run any checks to verify the package is valid and meets quality criteria."
},
{
"code": null,
"e": 6654,
"s": 6571,
"text": "verify − run any checks to verify the package is valid and meets quality criteria."
},
{
"code": null,
"e": 6762,
"s": 6654,
"text": "install − install the package into the local repository, for use as a dependency in other projects locally."
},
{
"code": null,
"e": 6870,
"s": 6762,
"text": "install − install the package into the local repository, for use as a dependency in other projects locally."
},
{
"code": null,
"e": 7024,
"s": 6870,
"text": "deploy − done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects."
},
{
"code": null,
"e": 7178,
"s": 7024,
"text": "deploy − done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects."
},
{
"code": null,
"e": 7426,
"s": 7178,
"text": "A goal represents a specific task which contributes to the building and managing of a project. It may be bound to zero or more build phases. A goal not bound to any build phase could be executed outside of the build lifecycle by direct invocation."
},
{
"code": null,
"e": 7547,
"s": 7426,
"text": "This command will clean the project, copy the dependencies and package the project (executing all phases up to package)."
},
{
"code": null,
"e": 7602,
"s": 7547,
"text": "The clean lifecycle consists of the following phases −"
},
{
"code": null,
"e": 7612,
"s": 7602,
"text": "pre-clean"
},
{
"code": null,
"e": 7618,
"s": 7612,
"text": "clean"
},
{
"code": null,
"e": 7629,
"s": 7618,
"text": "post-clean"
},
{
"code": null,
"e": 7665,
"s": 7629,
"text": "The phases in Site Lifecycle are −"
},
{
"code": null,
"e": 7674,
"s": 7665,
"text": "pre-site"
},
{
"code": null,
"e": 7679,
"s": 7674,
"text": "site"
},
{
"code": null,
"e": 7689,
"s": 7679,
"text": "post-site"
},
{
"code": null,
"e": 7701,
"s": 7689,
"text": "site-deploy"
},
{
"code": null,
"e": 7941,
"s": 7701,
"text": "A Build profile is a set of configuration values which can be used to set or override default values of Maven build. Using a build profile, you can customize build for different environments such as Production v/s Development environments."
},
{
"code": null,
"e": 7978,
"s": 7941,
"text": "Build profiles are of three types − "
},
{
"code": null,
"e": 8034,
"s": 7978,
"text": "Per Project − Defined in the project POM file, pom.xml."
},
{
"code": null,
"e": 8090,
"s": 8034,
"text": "Per Project − Defined in the project POM file, pom.xml."
},
{
"code": null,
"e": 8168,
"s": 8090,
"text": "Per User − Defined in Maven settings xml file (%USER_HOME%/.m2/settings.xml)."
},
{
"code": null,
"e": 8246,
"s": 8168,
"text": "Per User − Defined in Maven settings xml file (%USER_HOME%/.m2/settings.xml)."
},
{
"code": null,
"e": 8327,
"s": 8246,
"text": "Global − Defined in Maven global settings xml file (%M2_HOME%/conf/settings.xml)"
},
{
"code": null,
"e": 8408,
"s": 8327,
"text": "Global − Defined in Maven global settings xml file (%M2_HOME%/conf/settings.xml)"
},
{
"code": null,
"e": 8465,
"s": 8408,
"text": "A Maven Build Profile can be activated in various ways −"
},
{
"code": null,
"e": 8505,
"s": 8465,
"text": "Explicitly using command console input."
},
{
"code": null,
"e": 8545,
"s": 8505,
"text": "Explicitly using command console input."
},
{
"code": null,
"e": 8569,
"s": 8545,
"text": "Through maven settings."
},
{
"code": null,
"e": 8593,
"s": 8569,
"text": "Through maven settings."
},
{
"code": null,
"e": 8649,
"s": 8593,
"text": "Based on environment variables (User/System variables)."
},
{
"code": null,
"e": 8705,
"s": 8649,
"text": "Based on environment variables (User/System variables)."
},
{
"code": null,
"e": 8748,
"s": 8705,
"text": "OS Settings (for example, Windows family)."
},
{
"code": null,
"e": 8791,
"s": 8748,
"text": "OS Settings (for example, Windows family)."
},
{
"code": null,
"e": 8814,
"s": 8791,
"text": "Present/missing files."
},
{
"code": null,
"e": 8837,
"s": 8814,
"text": "Present/missing files."
},
{
"code": null,
"e": 9009,
"s": 8837,
"text": "A repository is a place i.e. directory where all the project jars, library jar, plugins or any other project specific artifacts are stored and can be used by Maven easily."
},
{
"code": null,
"e": 9069,
"s": 9009,
"text": "Maven repository are of three types: local, central, remote"
},
{
"code": null,
"e": 9291,
"s": 9069,
"text": "Maven local repository is a folder location on your machine. It gets created when you run any maven command for the first time. Maven local repository keeps your project's all dependencies (library jars, plugin jars etc)."
},
{
"code": null,
"e": 9309,
"s": 9291,
"text": "~/m2./repository."
},
{
"code": null,
"e": 9321,
"s": 9309,
"text": "mvn install"
},
{
"code": null,
"e": 9578,
"s": 9321,
"text": "It is repository provided by Maven community. It contains a large number of commonly used libraries. When Maven does not find any dependency in local repository, it starts searching in central repository using following URL: http://repo1.maven.org/maven2/."
},
{
"code": null,
"e": 9898,
"s": 9578,
"text": "Sometimes, Maven does not find a mentioned dependency in central repository as well then it stops the build process and output error message to console. To prevent such situation, Maven provides concept of Remote Repository which is developer's own custom repository containing required libraries or other project jars."
},
{
"code": null,
"e": 9932,
"s": 9898,
"text": "Following is the search pattern −"
},
{
"code": null,
"e": 10055,
"s": 9932,
"text": "Step 1 − Search dependency in local repository, if not found, move to step 2 else if found then do the further processing."
},
{
"code": null,
"e": 10178,
"s": 10055,
"text": "Step 1 − Search dependency in local repository, if not found, move to step 2 else if found then do the further processing."
},
{
"code": null,
"e": 10392,
"s": 10178,
"text": "Step 2 − Search dependency in central repository, if not found and remote repository/repositories is/are mentioned then move to step 4 else if found, then it is downloaded to local repository for future reference."
},
{
"code": null,
"e": 10606,
"s": 10392,
"text": "Step 2 − Search dependency in central repository, if not found and remote repository/repositories is/are mentioned then move to step 4 else if found, then it is downloaded to local repository for future reference."
},
{
"code": null,
"e": 10742,
"s": 10606,
"text": "Step 3 − If a remote repository has not been mentioned, Maven simply stops the processing and throws error (Unable to find dependency)."
},
{
"code": null,
"e": 10878,
"s": 10742,
"text": "Step 3 − If a remote repository has not been mentioned, Maven simply stops the processing and throws error (Unable to find dependency)."
},
{
"code": null,
"e": 11105,
"s": 10878,
"text": "Step 4 − Search dependency in remote repository or repositories, if found then it is downloaded to local repository for future reference otherwise Maven as expected stop processing and throws error (Unable to find dependency)."
},
{
"code": null,
"e": 11332,
"s": 11105,
"text": "Step 4 − Search dependency in remote repository or repositories, if found then it is downloaded to local repository for future reference otherwise Maven as expected stop processing and throws error (Unable to find dependency)."
},
{
"code": null,
"e": 11360,
"s": 11332,
"text": "Maven Plugins are used to −"
},
{
"code": null,
"e": 11377,
"s": 11360,
"text": "create jar file."
},
{
"code": null,
"e": 11394,
"s": 11377,
"text": "create war file."
},
{
"code": null,
"e": 11414,
"s": 11394,
"text": "compile code files."
},
{
"code": null,
"e": 11436,
"s": 11414,
"text": "unit testing of code."
},
{
"code": null,
"e": 11466,
"s": 11436,
"text": "create project documentation."
},
{
"code": null,
"e": 11490,
"s": 11466,
"text": "create project reports."
},
{
"code": null,
"e": 11538,
"s": 11490,
"text": "Maven provides following two types of Plugins −"
},
{
"code": null,
"e": 11644,
"s": 11538,
"text": "Build plugins − They execute during the build and should be configured in the <build/> element of pom.xml"
},
{
"code": null,
"e": 11750,
"s": 11644,
"text": "Build plugins − They execute during the build and should be configured in the <build/> element of pom.xml"
},
{
"code": null,
"e": 11883,
"s": 11750,
"text": "Reporting plugins − They execute during the site generation and they should be configured in the <reporting/> element of the pom.xml"
},
{
"code": null,
"e": 12016,
"s": 11883,
"text": "Reporting plugins − They execute during the site generation and they should be configured in the <reporting/> element of the pom.xml"
},
{
"code": null,
"e": 12257,
"s": 12016,
"text": "Maven dependency management using concept of Maven Repositories (Local, Central, Remote). Suppose dependency is not available in any of remote repositories and central repository; in such scenarios Maven uses concept of External Dependency."
},
{
"code": null,
"e": 12366,
"s": 12257,
"text": "External dependencies (library jar location) can be configured in pom.xml in same way as other dependencies."
},
{
"code": null,
"e": 12411,
"s": 12366,
"text": "Specify groupId same as name of the library."
},
{
"code": null,
"e": 12459,
"s": 12411,
"text": "Specify artifactId same as name of the library."
},
{
"code": null,
"e": 12484,
"s": 12459,
"text": "Specify scope as system."
},
{
"code": null,
"e": 12534,
"s": 12484,
"text": "Specify system path relative to project location."
},
{
"code": null,
"e": 12627,
"s": 12534,
"text": "Archetype is a Maven plugin whose task is to create a project structure as per its template."
},
{
"code": null,
"e": 12656,
"s": 12627,
"text": "Type the following command −"
},
{
"code": null,
"e": 12679,
"s": 12656,
"text": "mvn archetype:generate"
},
{
"code": null,
"e": 12857,
"s": 12679,
"text": "SNAPSHOT is a special version that indicates a current development copy. Unlike regular versions, Maven checks for a new SNAPSHOT version in a remote repository for every build."
},
{
"code": null,
"e": 13087,
"s": 12857,
"text": "In case of Version, if Maven once downloaded the mentioned version say data-service:1.0, it will never try to download a newer 1.0 available in repository. To download the updated code, data-service version is be upgraded to 1.1."
},
{
"code": null,
"e": 13230,
"s": 13087,
"text": "In case of SNAPSHOT, Maven will automatically fetch the latest SNAPSHOT (data-service:1.0-SNAPSHOT) everytime app-ui team build their project."
},
{
"code": null,
"e": 13383,
"s": 13230,
"text": "Transitive dependency means to avoid needing to discover and specify the libraries that your own dependencies require, and including them automatically."
},
{
"code": null,
"e": 13676,
"s": 13383,
"text": "It means to directly specify the versions of artifacts to be used when they are encountered in transitive dependencies. For an example project C can include B as a dependency in its dependencyManagement section and directly control which version of B is to be used when it is ever referenced."
},
{
"code": null,
"e": 13946,
"s": 13676,
"text": "Maven determines what version of a dependency is to be used when multiple versions of an artifact are encountered. If two dependency versions are at the same depth in the dependency tree, the first declared dependency will be used. This is called dependency mediation."
},
{
"code": null,
"e": 14056,
"s": 13946,
"text": "Dependency scope includes dependencies as per the current stage of the build. Various Dependency Scopes are −"
},
{
"code": null,
"e": 14162,
"s": 14056,
"text": "compile − This scope indicates that dependency is available in classpath of project. It is default scope."
},
{
"code": null,
"e": 14268,
"s": 14162,
"text": "compile − This scope indicates that dependency is available in classpath of project. It is default scope."
},
{
"code": null,
"e": 14377,
"s": 14268,
"text": "provided − This scope indicates that dependency is to be provided by JDK or web-Server/Container at runtime."
},
{
"code": null,
"e": 14486,
"s": 14377,
"text": "provided − This scope indicates that dependency is to be provided by JDK or web-Server/Container at runtime."
},
{
"code": null,
"e": 14600,
"s": 14486,
"text": "runtime − This scope indicates that dependency is not required for compilation, but is required during execution."
},
{
"code": null,
"e": 14714,
"s": 14600,
"text": "runtime − This scope indicates that dependency is not required for compilation, but is required during execution."
},
{
"code": null,
"e": 14827,
"s": 14714,
"text": "test − This scope indicates that the dependency is only available for the test compilation and execution phases."
},
{
"code": null,
"e": 14940,
"s": 14827,
"text": "test − This scope indicates that the dependency is only available for the test compilation and execution phases."
},
{
"code": null,
"e": 15012,
"s": 14940,
"text": "system − This scope indicates that you have to provide the system path."
},
{
"code": null,
"e": 15084,
"s": 15012,
"text": "system − This scope indicates that you have to provide the system path."
},
{
"code": null,
"e": 15280,
"s": 15084,
"text": "import − This scope is only used when dependency is of type pom. This scope indicates that the specified POM should be replaced with the dependencies in that POM's <dependencyManagement> section."
},
{
"code": null,
"e": 15476,
"s": 15280,
"text": "import − This scope is only used when dependency is of type pom. This scope indicates that the specified POM should be replaced with the dependencies in that POM's <dependencyManagement> section."
},
{
"code": null,
"e": 15514,
"s": 15476,
"text": "{groupId,artifactId,type,classifier}."
},
{
"code": null,
"e": 15709,
"s": 15514,
"text": "To reference a property defined in your pom.xml, the property name uses the names of the XML elements that define the value, with \"pom\" being allowed as an alias for the project (root) element. "
},
{
"code": null,
"e": 15909,
"s": 15709,
"text": "So pom.namereferstothenameoftheproject,{pom.version} refers to the version of the project, ${pom.build.finalName} refers to the final name of the file created when the built project is packaged, etc."
},
{
"code": null,
"e": 16037,
"s": 15909,
"text": "Some of the valid packaging values are jar, war, ear and pom. If no packaging value has been specified, it will default to jar."
},
{
"code": null,
"e": 16041,
"s": 16037,
"text": "pom"
},
{
"code": null,
"e": 16129,
"s": 16041,
"text": "The <execution> element contains information's required for the execution of a plugin. "
},
{
"code": null,
"e": 16162,
"s": 16129,
"text": "<groupId>:<artifactId>:<version>"
},
{
"code": null,
"e": 16314,
"s": 16162,
"text": "All POMs inherit from a parent (despite explicitly defined or not). This base POM is known as the Super POM, and contains values inherited by default. "
},
{
"code": null,
"e": 16397,
"s": 16314,
"text": "Profiles are specified using a subset of the elements available in the POM itself."
},
{
"code": null,
"e": 16544,
"s": 16397,
"text": "<repositories>, <pluginRepositories>,<dependencies>, <plugins> ,<properties>, <modules><reporting>,<dependencyManagement>,<distributionManagement>"
},
{
"code": null,
"e": 16604,
"s": 16544,
"text": "To give portability to projects ( e.g. windows, linux etc)."
},
{
"code": null,
"e": 16700,
"s": 16604,
"text": "It uses less storage, it makes checking out project quicker, non need for versioning JAR files."
},
{
"code": null,
"e": 16718,
"s": 16700,
"text": "Use the command −"
},
{
"code": null,
"e": 16733,
"s": 16718,
"text": "mvn o package."
},
{
"code": null,
"e": 16762,
"s": 16733,
"text": "Using the exclusion element."
},
{
"code": null,
"e": 17068,
"s": 16762,
"text": "Dependency with scope system are always available and are not looked up in repository, they are usually used to tell Maven about dependencies which are provided by the JDK or the VM. Thus, system dependencies are especially useful for resolving dependencies on artifacts which are now provided by the JDK."
},
{
"code": null,
"e": 17248,
"s": 17068,
"text": "Any transitive dependency can be marked as optional using \"optional\" element. As example, A depends upon B and B depends upon C. Now B marked C as optional. Then A will not use C."
},
{
"code": null,
"e": 17397,
"s": 17248,
"text": "Any transitive dependency can be exclude using \"exclusion\" element. As example, A depends upon B and B depends upon C then A can mark C as excluded."
},
{
"code": null,
"e": 17468,
"s": 17397,
"text": "You can put the clean plugin inside the execution tag in pom.xml file."
},
{
"code": null,
"e": 17494,
"s": 17468,
"text": "set <inherited> to false."
},
{
"code": null,
"e": 17635,
"s": 17494,
"text": "It means that you have executed a plugin multiple times with the same <id>. Provide each <execution> with a unique <id> then it would be ok."
},
{
"code": null,
"e": 17779,
"s": 17635,
"text": "A mojo is a Maven plain Old Java Object. Each mojo is an executable goal in Maven, and a plugin is a distribution of one or more related mojos."
},
{
"code": null,
"e": 18073,
"s": 17779,
"text": "Ant is simply a toolbox whereas Maven is about the application of patterns in order to achieve an infrastructure which displays the characteristics of visibility, reusability, maintainability, and comprehensibility. It is wrong to consider Maven as a build tool and just a replacement for Ant."
},
{
"code": null,
"e": 18360,
"s": 18073,
"text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong."
},
{
"code": null,
"e": 18690,
"s": 18360,
"text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)"
},
{
"code": null,
"e": 18723,
"s": 18690,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 18737,
"s": 18723,
"text": " Karthikeya T"
},
{
"code": null,
"e": 18772,
"s": 18737,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 18790,
"s": 18772,
"text": " Quaatso Learning"
},
{
"code": null,
"e": 18797,
"s": 18790,
"text": " Print"
},
{
"code": null,
"e": 18808,
"s": 18797,
"text": " Add Notes"
}
] |
How to order by certain part of a string in MySQL? | You can use ORDER BY SUBSTRING() to order by certain part of a string in MySQL. Let us first create a table:
mysql> create table DemoTable (UserId varchar(200));
Query OK, 0 rows affected (0.68 sec)
Following is the query to insert records in the table using insert command:
mysql> insert into DemoTable values('USER_1234');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('USER_John');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('USER_Sam');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('USER_Carol');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('USER_Bob');
Query OK, 1 row affected (0.14 sec)
Following is the query to display records from the table using select command:
mysql> select *from DemoTable;
This will produce the following output:
+------------+
| UserId |
+------------+
| USER_1234 |
| USER_John |
| USER_Sam |
| USER_Carol |
| USER_Bob |
+------------+
5 rows in set (0.00 sec)
Case 1: When you want to ORDER BY part of a string in ascending order.
Following is the query. Here, we will order certain part of the string after 4th character:
mysql> select *from DemoTable order by substring(UserId,4) asc;
This will produce the following output
+------------+
| UserId |
+------------+
| USER_1234 |
| USER_Bob |
| USER_Carol |
| USER_John |
| USER_Sam |
+------------+
5 rows in set (0.00 sec)
Case 2: When you want to ORDER BY part of a string in descending order. Following is the query:
mysql> select *from DemoTable order by substring(UserId,4) desc;
This will produce the following output. Here, we will order certain part of the string after 4th character:
+------------+
| UserId |
+------------+
| USER_Sam |
| USER_John |
| USER_Carol |
| USER_Bob |
| USER_1234 |
+------------+
5 rows in set (0.00 sec) | [
{
"code": null,
"e": 1171,
"s": 1062,
"text": "You can use ORDER BY SUBSTRING() to order by certain part of a string in MySQL. Let us first create a table:"
},
{
"code": null,
"e": 1261,
"s": 1171,
"text": "mysql> create table DemoTable (UserId varchar(200));\nQuery OK, 0 rows affected (0.68 sec)"
},
{
"code": null,
"e": 1337,
"s": 1261,
"text": "Following is the query to insert records in the table using insert command:"
},
{
"code": null,
"e": 1766,
"s": 1337,
"text": "mysql> insert into DemoTable values('USER_1234');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('USER_John');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values('USER_Sam');\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable values('USER_Carol');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values('USER_Bob');\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 1845,
"s": 1766,
"text": "Following is the query to display records from the table using select command:"
},
{
"code": null,
"e": 1876,
"s": 1845,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1916,
"s": 1876,
"text": "This will produce the following output:"
},
{
"code": null,
"e": 2077,
"s": 1916,
"text": "+------------+\n| UserId | \n+------------+\n| USER_1234 |\n| USER_John |\n| USER_Sam |\n| USER_Carol |\n| USER_Bob |\n+------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2148,
"s": 2077,
"text": "Case 1: When you want to ORDER BY part of a string in ascending order."
},
{
"code": null,
"e": 2240,
"s": 2148,
"text": "Following is the query. Here, we will order certain part of the string after 4th character:"
},
{
"code": null,
"e": 2304,
"s": 2240,
"text": "mysql> select *from DemoTable order by substring(UserId,4) asc;"
},
{
"code": null,
"e": 2343,
"s": 2304,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2503,
"s": 2343,
"text": "+------------+\n| UserId |\n+------------+\n| USER_1234 |\n| USER_Bob |\n| USER_Carol |\n| USER_John |\n| USER_Sam |\n+------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2599,
"s": 2503,
"text": "Case 2: When you want to ORDER BY part of a string in descending order. Following is the query:"
},
{
"code": null,
"e": 2664,
"s": 2599,
"text": "mysql> select *from DemoTable order by substring(UserId,4) desc;"
},
{
"code": null,
"e": 2772,
"s": 2664,
"text": "This will produce the following output. Here, we will order certain part of the string after 4th character:"
},
{
"code": null,
"e": 2932,
"s": 2772,
"text": "+------------+\n| UserId |\n+------------+\n| USER_Sam |\n| USER_John |\n| USER_Carol |\n| USER_Bob |\n| USER_1234 |\n+------------+\n5 rows in set (0.00 sec)"
}
] |
How to get Value of a Edit Text field in Android using Kotlin? | This example demonstrates how to get Value of a Edit Text field 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"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/button"
android:layout_centerInParent="true" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Get value of " />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/button"
android:layout_centerInParent="true"
android:layout_marginTop="8dp"
android:textColor="@android:color/background_dark"
android:textSize="16sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var button: Button
lateinit var editText: EditText
lateinit var string: String
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
button = findViewById(R.id.button)
editText = findViewById(R.id.editText)
textView = findViewById(R.id.textView)
button.setOnClickListener {
string = editText.text.toString()
textView.text = string
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.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": 1152,
"s": 1062,
"text": "This example demonstrates how to get Value of a Edit Text field in Android using Kotlin?"
},
{
"code": null,
"e": 1281,
"s": 1152,
"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": 1346,
"s": 1281,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2731,
"s": 1346,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_above=\"@id/button\"\n android:layout_centerInParent=\"true\" />\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Get value of \" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/button\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"8dp\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2786,
"s": 2731,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3548,
"s": 2786,
"text": "import android.os.Bundle\nimport android.widget.Button\nimport android.widget.EditText\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var button: Button\n lateinit var editText: EditText\n lateinit var string: String\n lateinit var textView: TextView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n button = findViewById(R.id.button)\n editText = findViewById(R.id.editText)\n textView = findViewById(R.id.textView)\n button.setOnClickListener {\n string = editText.text.toString()\n textView.text = string\n }\n }\n}"
},
{
"code": null,
"e": 3603,
"s": 3548,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4270,
"s": 3603,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.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": 4618,
"s": 4270,
"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"
}
] |
Complementation process in DFA - GeeksforGeeks | 26 Jul, 2021
Prerequisite – Design a Finite automata Suppose we have a DFA that is defined by ( Q, , , q0, F ) and it accepts the language L1. Then, the DFA which accepts the language L2 where L2 = ̅L1‘, will be defined as below:
( Q, , , q0, Q-F )
The complement of a DFA can be obtained by making the non-final states as final states and vice-versa. The language accepted by the complemented DFA L2 is the complement of the language L1.
Example-1: L1: set of all strings over {a, b} of even length
L1 = {, ab, aa, abaa, aaba, ....}
L2: set of all strings over {a, b} of odd length
L2 = { a, b, aab, aaa, bba, bbb, ...}
Here, we can see that L2 = ̅L1
Lets first draw the DFA for L1 that accepts the strings of even length.
Now, for designing the DFA for L2, we just need to complement the above DFA. We will change the non-final states as final state and the final states as non-final states.
This is our required complemented DFA.
Example-2: L1: set of all strings over {a, b} starting with ‘a’.
L1 ={ a, ab, aa, aba, aaa, aab, ..}
L2: set of all strings over {a, b} not starting with ‘a’.
L2 ={ , b, ba, bb, bab, baa, bba, ...}
Here, we can see that L2 = ̅L1
Lets first draw the DFA for L1 that accepts the set of all strings over {a, b} starting with ‘a’
Now, for designing the DFA for L2, we just need to complement the above DFA. We will change the non-final states as final state and the final states as non-final states.
This is our required complemented DFA that accepts the strings that are not starting with ‘a’. Note: Regular languages are closed under complement (i.e Complement of regular language will also be regular).
VaibhavRai3
simmytarika5
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Regular Expressions, Regular Grammar and Regular Languages
Difference between Clustered and Non-clustered index
Phases of a Compiler
Preemptive and Non-Preemptive Scheduling
Introduction of Process Synchronization
Regular Expressions, Regular Grammar and Regular Languages
Difference between DFA and NFA
Pumping Lemma in Theory of Computation
Introduction of Finite Automata
Turing Machine in TOC | [
{
"code": null,
"e": 24376,
"s": 24348,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 24595,
"s": 24376,
"text": "Prerequisite – Design a Finite automata Suppose we have a DFA that is defined by ( Q, , , q0, F ) and it accepts the language L1. Then, the DFA which accepts the language L2 where L2 = ̅L1‘, will be defined as below: "
},
{
"code": null,
"e": 24614,
"s": 24595,
"text": "( Q, , , q0, Q-F )"
},
{
"code": null,
"e": 24805,
"s": 24614,
"text": "The complement of a DFA can be obtained by making the non-final states as final states and vice-versa. The language accepted by the complemented DFA L2 is the complement of the language L1. "
},
{
"code": null,
"e": 24868,
"s": 24805,
"text": "Example-1: L1: set of all strings over {a, b} of even length "
},
{
"code": null,
"e": 24903,
"s": 24868,
"text": "L1 = {, ab, aa, abaa, aaba, ....} "
},
{
"code": null,
"e": 24954,
"s": 24903,
"text": "L2: set of all strings over {a, b} of odd length "
},
{
"code": null,
"e": 24993,
"s": 24954,
"text": "L2 = { a, b, aab, aaa, bba, bbb, ...} "
},
{
"code": null,
"e": 25025,
"s": 24993,
"text": "Here, we can see that L2 = ̅L1 "
},
{
"code": null,
"e": 25098,
"s": 25025,
"text": "Lets first draw the DFA for L1 that accepts the strings of even length. "
},
{
"code": null,
"e": 25271,
"s": 25100,
"text": "Now, for designing the DFA for L2, we just need to complement the above DFA. We will change the non-final states as final state and the final states as non-final states. "
},
{
"code": null,
"e": 25313,
"s": 25273,
"text": "This is our required complemented DFA. "
},
{
"code": null,
"e": 25380,
"s": 25313,
"text": "Example-2: L1: set of all strings over {a, b} starting with ‘a’. "
},
{
"code": null,
"e": 25417,
"s": 25380,
"text": "L1 ={ a, ab, aa, aba, aaa, aab, ..} "
},
{
"code": null,
"e": 25477,
"s": 25417,
"text": "L2: set of all strings over {a, b} not starting with ‘a’. "
},
{
"code": null,
"e": 25517,
"s": 25477,
"text": "L2 ={ , b, ba, bb, bab, baa, bba, ...} "
},
{
"code": null,
"e": 25549,
"s": 25517,
"text": "Here, we can see that L2 = ̅L1 "
},
{
"code": null,
"e": 25647,
"s": 25549,
"text": "Lets first draw the DFA for L1 that accepts the set of all strings over {a, b} starting with ‘a’ "
},
{
"code": null,
"e": 25820,
"s": 25649,
"text": "Now, for designing the DFA for L2, we just need to complement the above DFA. We will change the non-final states as final state and the final states as non-final states. "
},
{
"code": null,
"e": 26029,
"s": 25822,
"text": "This is our required complemented DFA that accepts the strings that are not starting with ‘a’. Note: Regular languages are closed under complement (i.e Complement of regular language will also be regular). "
},
{
"code": null,
"e": 26041,
"s": 26029,
"text": "VaibhavRai3"
},
{
"code": null,
"e": 26054,
"s": 26041,
"text": "simmytarika5"
},
{
"code": null,
"e": 26062,
"s": 26054,
"text": "GATE CS"
},
{
"code": null,
"e": 26095,
"s": 26062,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 26193,
"s": 26095,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26202,
"s": 26193,
"text": "Comments"
},
{
"code": null,
"e": 26215,
"s": 26202,
"text": "Old Comments"
},
{
"code": null,
"e": 26274,
"s": 26215,
"text": "Regular Expressions, Regular Grammar and Regular Languages"
},
{
"code": null,
"e": 26327,
"s": 26274,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 26348,
"s": 26327,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 26389,
"s": 26348,
"text": "Preemptive and Non-Preemptive Scheduling"
},
{
"code": null,
"e": 26429,
"s": 26389,
"text": "Introduction of Process Synchronization"
},
{
"code": null,
"e": 26488,
"s": 26429,
"text": "Regular Expressions, Regular Grammar and Regular Languages"
},
{
"code": null,
"e": 26519,
"s": 26488,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 26558,
"s": 26519,
"text": "Pumping Lemma in Theory of Computation"
},
{
"code": null,
"e": 26590,
"s": 26558,
"text": "Introduction of Finite Automata"
}
] |
Rotate In Animation Effect with CSS | To create a rotate in animation effect with CSS, you can try to run the following code −
Live Demo
<html>
<head>
<style>
.animated {
background-image: url(/css/images/logo.png);
background-repeat: no-repeat;
background-position: left top;
padding-top:95px;
margin-bottom:60px;
-webkit-animation-duration: 10s;
animation-duration: 10s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
@-webkit-keyframes rotateIn {
0% {
-webkit-transform-origin: center center;
-webkit-transform: rotate(-200deg);
opacity: 0;
}
100% {
-webkit-transform-origin: center center;
-webkit-transform: rotate(0);
opacity: 1;
}
}
@keyframes rotateIn {
0% {
transform-origin: center center;
transform: rotate(-200deg);
opacity: 0;
}
100% {
transform-origin: center center;
transform: rotate(0);
opacity: 1;
}
}
.rotateIn {
-webkit-animation-name: rotateIn;
animation-name: rotateIn;
}
</style>
</head>
<body>
<div id = "animated-example" class = "animated rotateIn"></div>
<button onclick = "myFunction()">Reload page</button>
<script>
function myFunction() {
location.reload();
}
</script>
</body>
</html> | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "To create a rotate in animation effect with CSS, you can try to run the following code −"
},
{
"code": null,
"e": 1161,
"s": 1151,
"text": "Live Demo"
},
{
"code": null,
"e": 2727,
"s": 1161,
"text": "<html>\n <head>\n <style>\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;\n animation-duration: 10s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n\n @-webkit-keyframes rotateIn {\n 0% {\n -webkit-transform-origin: center center;\n -webkit-transform: rotate(-200deg);\n opacity: 0;\n }\n 100% {\n -webkit-transform-origin: center center;\n -webkit-transform: rotate(0);\n opacity: 1;\n }\n }\n\n @keyframes rotateIn {\n 0% {\n transform-origin: center center;\n transform: rotate(-200deg);\n opacity: 0;\n }\n 100% {\n transform-origin: center center;\n transform: rotate(0);\n opacity: 1;\n }\n }\n\n .rotateIn {\n -webkit-animation-name: rotateIn;\n animation-name: rotateIn;\n }\n </style>\n\n </head>\n <body>\n\n <div id = \"animated-example\" class = \"animated rotateIn\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n\n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n </body>\n</html>"
}
] |
C library function - free() | The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc.
Following is the declaration for free() function.
void free(void *ptr)
ptr − This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be deallocated. If a null pointer is passed as argument, no action occurs.
ptr − This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be deallocated. If a null pointer is passed as argument, no action occurs.
This function does not return any value.
The following example shows the usage of free() function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char *str;
/* Initial memory allocation */
str = (char *) malloc(15);
strcpy(str, "tutorialspoint");
printf("String = %s, Address = %u\n", str, str);
/* Reallocating memory */
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
/* Deallocate allocated memory */
free(str);
return(0);
}
Let us compile and run the above program that will produce the following result −
String = tutorialspoint, Address = 355090448
String = tutorialspoint.com, Address = 355090448
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2136,
"s": 2007,
"text": "The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc."
},
{
"code": null,
"e": 2186,
"s": 2136,
"text": "Following is the declaration for free() function."
},
{
"code": null,
"e": 2207,
"s": 2186,
"text": "void free(void *ptr)"
},
{
"code": null,
"e": 2381,
"s": 2207,
"text": "ptr − This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be deallocated. If a null pointer is passed as argument, no action occurs."
},
{
"code": null,
"e": 2555,
"s": 2381,
"text": "ptr − This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be deallocated. If a null pointer is passed as argument, no action occurs."
},
{
"code": null,
"e": 2596,
"s": 2555,
"text": "This function does not return any value."
},
{
"code": null,
"e": 2654,
"s": 2596,
"text": "The following example shows the usage of free() function."
},
{
"code": null,
"e": 3110,
"s": 2654,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main () {\n char *str;\n\n /* Initial memory allocation */\n str = (char *) malloc(15);\n strcpy(str, \"tutorialspoint\");\n printf(\"String = %s, Address = %u\\n\", str, str);\n\n /* Reallocating memory */\n str = (char *) realloc(str, 25);\n strcat(str, \".com\");\n printf(\"String = %s, Address = %u\\n\", str, str);\n\n /* Deallocate allocated memory */\n free(str);\n \n return(0);\n}"
},
{
"code": null,
"e": 3192,
"s": 3110,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 3287,
"s": 3192,
"text": "String = tutorialspoint, Address = 355090448\nString = tutorialspoint.com, Address = 355090448\n"
},
{
"code": null,
"e": 3320,
"s": 3287,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3335,
"s": 3320,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3370,
"s": 3335,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3385,
"s": 3370,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3420,
"s": 3385,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3434,
"s": 3420,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3467,
"s": 3434,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3485,
"s": 3467,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3520,
"s": 3485,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3539,
"s": 3520,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3572,
"s": 3539,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3584,
"s": 3572,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3591,
"s": 3584,
"text": " Print"
},
{
"code": null,
"e": 3602,
"s": 3591,
"text": " Add Notes"
}
] |
Print all possible strings that can be made by placing spaces - GeeksforGeeks | 29 Apr, 2021
Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them
Examples :
Input : str[] = "ABC"
Output : ABC
AB C
A BC
A B C
Input : str[] = "ABCD"
Output : ABCD
A BCD
AB CD
A B CD
ABC D
A BC D
AB C D
A B C D
If we take a closer look, we can notice that this problem boils down to Power Set problem. We basically need to generate all subsets where every element is a different space.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print all strings that can be// made by placing spaces#include <bits/stdc++.h>using namespace std; void printSubsequences(string str){ int n = str.length(); unsigned int opsize = pow(2, n - 1); for (int counter = 0; counter < opsize; counter++) { for (int j = 0; j < n; j++) { cout << str[j]; if (counter & (1 << j)) cout << " "; } cout << endl; }} // Driver codeint main(){ string str = "ABC"; printSubsequences(str); return 0;}
// Java program to print all strings that can be// made by placing spacesimport java.util.*;class GFG{static void printSubsequences(String s){ char[] str= s.toCharArray(); int n = str.length; int opsize = (int)(Math.pow(2, n - 1)); for (int counter = 0; counter < opsize; counter++) { for (int j = 0; j < n; j++) { System.out.print(str[j]); if ((counter & (1 << j)) > 0) System.out.print(" "); } System.out.println(); }} // Driver codepublic static void main(String[] args){ String str = "AB"; printSubsequences(str);}} /* This code is contributed by Mr. Somesh Awasthi */
# Python 3 program to print all strings # that can be made by placing spacesfrom math import pow def printSubsequences(str): n = len(str) opsize = int(pow(2, n - 1)) for counter in range(opsize): for j in range(n): print(str[j], end = "") if (counter & (1 << j)): print(" ", end = "") print("\n", end = "") # Driver codeif __name__ == '__main__': str = "ABC" printSubsequences(str) # This code is contributed by# Sanjit_Prasad
// C# program to print all strings// that can be made by placing spacesusing System; class GFG { // Function to print all subsequences static void printSubsequences(String s) { char[] str= s.ToCharArray(); int n = str.Length; int opsize = (int)(Math.Pow(2, n - 1)); for (int counter = 0; counter < opsize; counter++) { for (int j = 0; j < n; j++) { Console.Write(str[j]); if ((counter & (1 << j)) > 0) Console.Write(" "); } Console.WriteLine(); } } // Driver code public static void Main() { String str = "ABC"; printSubsequences(str); }} // This code is contributed by shiv_bhakt.
<?php// PHP program to print // all strings that can be// made by placing spaces function printSubsequences($str){ $n = strlen($str); $opsize = pow(2, $n - 1); for ($counter = 0; $counter < $opsize; $counter++) { for ($j = 0; $j < $n; $j++) { echo $str[$j]; if ($counter & (1 << $j)) echo " "; } echo "\n"; }} // Driver code$str = "ABC";printSubsequences($str); // This code is contributed by ajit?>
<script> // Javascript program to print all strings// that can be made by placing spaces // Function to print all subsequencesfunction printSubsequences(s){ let str= s.split(''); let n = str.length; let opsize = Math.pow(2, n - 1); for(let counter = 0; counter < opsize; counter++) { for(let j = 0; j < n; j++) { document.write(str[j]); if ((counter & (1 << j)) > 0) document.write(" "); } document.write("</br>"); }} // Driver codelet str = "ABC";printSubsequences(str); // This code is contributed by rameshtravel07</script>
Output :
ABC
A BC
AB C
A B C
Asked in: AmazonThis article is contributed by Jebasingh and Ninja.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Vishal_Khoda
jit_t
Sanjit_Prasad
rameshtravel07
Amazon
Backtracking
Combinatorial
Recursion
Strings
Amazon
Strings
Recursion
Combinatorial
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Backtracking | Introduction
Subset Sum | Backtracking-4
m Coloring Problem | Backtracking-5
Print all paths from a given source to a destination
Hamiltonian Cycle | Backtracking-6
Permutation and Combination in Python
Program to calculate value of nCr
itertools.combinations() module in Python to print all possible combinations
Combinational Sum
Count ways to reach the nth stair using step 1, 2 or 3 | [
{
"code": null,
"e": 25112,
"s": 25084,
"text": "\n29 Apr, 2021"
},
{
"code": null,
"e": 25232,
"s": 25112,
"text": "Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them "
},
{
"code": null,
"e": 25244,
"s": 25232,
"text": "Examples : "
},
{
"code": null,
"e": 25471,
"s": 25244,
"text": "Input : str[] = \"ABC\"\nOutput : ABC\n AB C\n A BC\n A B C\n\nInput : str[] = \"ABCD\"\nOutput : ABCD\n A BCD\n AB CD\n A B CD\n ABC D\n A BC D\n AB C D\n A B C D"
},
{
"code": null,
"e": 25648,
"s": 25471,
"text": "If we take a closer look, we can notice that this problem boils down to Power Set problem. We basically need to generate all subsets where every element is a different space. "
},
{
"code": null,
"e": 25652,
"s": 25648,
"text": "C++"
},
{
"code": null,
"e": 25657,
"s": 25652,
"text": "Java"
},
{
"code": null,
"e": 25665,
"s": 25657,
"text": "Python3"
},
{
"code": null,
"e": 25668,
"s": 25665,
"text": "C#"
},
{
"code": null,
"e": 25672,
"s": 25668,
"text": "PHP"
},
{
"code": null,
"e": 25683,
"s": 25672,
"text": "Javascript"
},
{
"code": "// C++ program to print all strings that can be// made by placing spaces#include <bits/stdc++.h>using namespace std; void printSubsequences(string str){ int n = str.length(); unsigned int opsize = pow(2, n - 1); for (int counter = 0; counter < opsize; counter++) { for (int j = 0; j < n; j++) { cout << str[j]; if (counter & (1 << j)) cout << \" \"; } cout << endl; }} // Driver codeint main(){ string str = \"ABC\"; printSubsequences(str); return 0;}",
"e": 26216,
"s": 25683,
"text": null
},
{
"code": "// Java program to print all strings that can be// made by placing spacesimport java.util.*;class GFG{static void printSubsequences(String s){ char[] str= s.toCharArray(); int n = str.length; int opsize = (int)(Math.pow(2, n - 1)); for (int counter = 0; counter < opsize; counter++) { for (int j = 0; j < n; j++) { System.out.print(str[j]); if ((counter & (1 << j)) > 0) System.out.print(\" \"); } System.out.println(); }} // Driver codepublic static void main(String[] args){ String str = \"AB\"; printSubsequences(str);}} /* This code is contributed by Mr. Somesh Awasthi */",
"e": 26874,
"s": 26216,
"text": null
},
{
"code": "# Python 3 program to print all strings # that can be made by placing spacesfrom math import pow def printSubsequences(str): n = len(str) opsize = int(pow(2, n - 1)) for counter in range(opsize): for j in range(n): print(str[j], end = \"\") if (counter & (1 << j)): print(\" \", end = \"\") print(\"\\n\", end = \"\") # Driver codeif __name__ == '__main__': str = \"ABC\" printSubsequences(str) # This code is contributed by# Sanjit_Prasad",
"e": 27374,
"s": 26874,
"text": null
},
{
"code": "// C# program to print all strings// that can be made by placing spacesusing System; class GFG { // Function to print all subsequences static void printSubsequences(String s) { char[] str= s.ToCharArray(); int n = str.Length; int opsize = (int)(Math.Pow(2, n - 1)); for (int counter = 0; counter < opsize; counter++) { for (int j = 0; j < n; j++) { Console.Write(str[j]); if ((counter & (1 << j)) > 0) Console.Write(\" \"); } Console.WriteLine(); } } // Driver code public static void Main() { String str = \"ABC\"; printSubsequences(str); }} // This code is contributed by shiv_bhakt.",
"e": 28205,
"s": 27374,
"text": null
},
{
"code": "<?php// PHP program to print // all strings that can be// made by placing spaces function printSubsequences($str){ $n = strlen($str); $opsize = pow(2, $n - 1); for ($counter = 0; $counter < $opsize; $counter++) { for ($j = 0; $j < $n; $j++) { echo $str[$j]; if ($counter & (1 << $j)) echo \" \"; } echo \"\\n\"; }} // Driver code$str = \"ABC\";printSubsequences($str); // This code is contributed by ajit?>",
"e": 28710,
"s": 28205,
"text": null
},
{
"code": "<script> // Javascript program to print all strings// that can be made by placing spaces // Function to print all subsequencesfunction printSubsequences(s){ let str= s.split(''); let n = str.length; let opsize = Math.pow(2, n - 1); for(let counter = 0; counter < opsize; counter++) { for(let j = 0; j < n; j++) { document.write(str[j]); if ((counter & (1 << j)) > 0) document.write(\" \"); } document.write(\"</br>\"); }} // Driver codelet str = \"ABC\";printSubsequences(str); // This code is contributed by rameshtravel07</script>",
"e": 29346,
"s": 28710,
"text": null
},
{
"code": null,
"e": 29356,
"s": 29346,
"text": "Output : "
},
{
"code": null,
"e": 29376,
"s": 29356,
"text": "ABC\nA BC\nAB C\nA B C"
},
{
"code": null,
"e": 29445,
"s": 29376,
"text": "Asked in: AmazonThis article is contributed by Jebasingh and Ninja. "
},
{
"code": null,
"e": 29820,
"s": 29445,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 29833,
"s": 29820,
"text": "Vishal_Khoda"
},
{
"code": null,
"e": 29839,
"s": 29833,
"text": "jit_t"
},
{
"code": null,
"e": 29853,
"s": 29839,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 29868,
"s": 29853,
"text": "rameshtravel07"
},
{
"code": null,
"e": 29875,
"s": 29868,
"text": "Amazon"
},
{
"code": null,
"e": 29888,
"s": 29875,
"text": "Backtracking"
},
{
"code": null,
"e": 29902,
"s": 29888,
"text": "Combinatorial"
},
{
"code": null,
"e": 29912,
"s": 29902,
"text": "Recursion"
},
{
"code": null,
"e": 29920,
"s": 29912,
"text": "Strings"
},
{
"code": null,
"e": 29927,
"s": 29920,
"text": "Amazon"
},
{
"code": null,
"e": 29935,
"s": 29927,
"text": "Strings"
},
{
"code": null,
"e": 29945,
"s": 29935,
"text": "Recursion"
},
{
"code": null,
"e": 29959,
"s": 29945,
"text": "Combinatorial"
},
{
"code": null,
"e": 29972,
"s": 29959,
"text": "Backtracking"
},
{
"code": null,
"e": 30070,
"s": 29972,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30079,
"s": 30070,
"text": "Comments"
},
{
"code": null,
"e": 30092,
"s": 30079,
"text": "Old Comments"
},
{
"code": null,
"e": 30120,
"s": 30092,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 30148,
"s": 30120,
"text": "Subset Sum | Backtracking-4"
},
{
"code": null,
"e": 30184,
"s": 30148,
"text": "m Coloring Problem | Backtracking-5"
},
{
"code": null,
"e": 30237,
"s": 30184,
"text": "Print all paths from a given source to a destination"
},
{
"code": null,
"e": 30272,
"s": 30237,
"text": "Hamiltonian Cycle | Backtracking-6"
},
{
"code": null,
"e": 30310,
"s": 30272,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 30344,
"s": 30310,
"text": "Program to calculate value of nCr"
},
{
"code": null,
"e": 30421,
"s": 30344,
"text": "itertools.combinations() module in Python to print all possible combinations"
},
{
"code": null,
"e": 30439,
"s": 30421,
"text": "Combinational Sum"
}
] |
ArrayDeque in Java - GeeksforGeeks | 24 Jan, 2022
The ArrayDeque in Java provides a way to apply resizable-array in addition to the implementation of the Deque interface. It is also known as Array Double Ended Queue or Array Deck. This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue.
Few important features of ArrayDeque are as follows:
Array deques have no capacity restrictions and they grow as necessary to support usage.
They are not thread-safe which means that in the absence of external synchronization, ArrayDeque does not support concurrent access by multiple threads.
Null elements are prohibited in the ArrayDeque.
ArrayDeque class is likely to be faster than Stack when used as a stack.
ArrayDeque class is likely to be faster than LinkedList when used as a queue.
Interfaces implemented by ArrayDeque:
The ArrayDeque class implements these two interfaces:
Queue Interface: It is an Interface that is a FirstIn – FirstOut Data Structure where the elements are added from the back.
Deque Interface: It is a Doubly Ended Queue in which you can insert the elements from both sides. It is an interface that implements the Queue.
ArrayDeque implements both Queue and Deque. It is dynamically resizable from both sides. All implemented interfaces of ArrayDeque in the hierarchy are Serializable, Cloneable, Iterable<E>, Collection<E>, Deque<E>, Queue<E>
Syntax: Declaration
public class ArrayDeque<E>
extends AbstractCollection<E>
implements Deque<E>, Cloneable, Serializable
Here, E refers to the element which can refer to any class, such as Integer or String class.
Now we are done with syntax now let us come up with constructors been defined for it prior before implementing to grasp it better and perceiving the output better.
ArrayDeque(): This constructor is used to create an empty ArrayDeque and by default holds an initial capacity to hold 16 elements.
ArrayDeque<E> dq = new ArrayDeque<E>();
ArrayDeque(Collection<? extends E> c): This constructor is used to create an ArrayDeque containing all the elements the same as that of the specified collection.
ArrayDeque<E> dq = new ArrayDeque<E>(Collection col);
ArrayDeque(int numofElements): This constructor is used to create an empty ArrayDeque and holds the capacity to contain a specified number of elements.
ArrayDeque<E> dq = new ArrayDeque<E>(int numofElements);
Methods in ArrayDeque are as follows:
Note: Here, Element is the type of elements stored by ArrayDeque.
METHOD
DESCRIPTION
Methods inherited from class java.util.AbstractCollection
Method
Action Performed
Methods inherited from interface java.util.Collection
Method
Action Performed
Methods declared in interface java.util.Deque
Method
Action Performed
Example
Java
// Java program to Implement ArrayDeque in Java// // Importing utility classesimport java.util.*; // ArrayDequeDemopublic class GGFG { public static void main(String[] args) { // Creating and initializing deque // Declaring object of integer type Deque<Integer> de_que = new ArrayDeque<Integer>(10); // Operations 1 // add() method // Adding custom elements // using add() method to insert de_que.add(10); de_que.add(20); de_que.add(30); de_que.add(40); de_que.add(50); // Iterating using for each loop for (Integer element : de_que) { // Print the corresponding element System.out.println("Element : " + element); } // Operation 2 // clear() method System.out.println("Using clear() "); // Clearing all elements using clear() method de_que.clear(); // Operations 3 // addFirst() method // Inserting at the start de_que.addFirst(564); de_que.addFirst(291); // Operation 4 // addLast() method // Inserting at end de_que.addLast(24); de_que.addLast(14); // Display message System.out.println( "Above elements are removed now"); // Iterators // Display message System.out.println( "Elements of deque using Iterator :"); for (Iterator itr = de_que.iterator(); itr.hasNext();) { System.out.println(itr.next()); } // descendingIterator() // To reverse the deque order System.out.println( "Elements of deque in reverse order :"); for (Iterator dItr = de_que.descendingIterator(); dItr.hasNext();) { System.out.println(dItr.next()); } // Operation 5 // element() method : to get Head element System.out.println( "\nHead Element using element(): " + de_que.element()); // Operation 6 // getFirst() method : to get Head element System.out.println("Head Element using getFirst(): " + de_que.getFirst()); // Operation 7 // getLast() method : to get last element System.out.println("Last Element using getLast(): " + de_que.getLast()); // Operation 8 // toArray() method : Object[] arr = de_que.toArray(); System.out.println("\nArray Size : " + arr.length); System.out.print("Array elements : "); for (int i = 0; i < arr.length; i++) System.out.print(" " + arr[i]); // Operation 9 // peek() method : to get head System.out.println("\nHead element : " + de_que.peek()); // Operation 10 // poll() method : to get head System.out.println("Head element poll : " + de_que.poll()); // Operation 11 // push() method de_que.push(265); de_que.push(984); de_que.push(2365); // Operation 12 // remove() method : to get head System.out.println("Head element remove : " + de_que.remove()); System.out.println("The final array is: " + de_que); }}
Element : 10
Element : 20
Element : 30
Element : 40
Element : 50
Using clear()
Above elements are removed now
Elements of deque using Iterator :
291
564
24
14
Elements of deque in reverse order :
14
24
564
291
Head Element using element(): 291
Head Element using getFirst(): 291
Last Element using getLast(): 14
Array Size : 4
Array elements : 291 564 24 14
Head element : 291
Head element poll : 291
Head element remove : 2365
The final array is: [984, 265, 564, 24, 14]
If there is some lag in clarity in this example, if so then we are proposing various operations on the ArrayDeque class Let’s see how to perform a few frequently used operations on the ArrayDeque to get a better understanding of the operations that we have used above to illustrate Array Deque as a whole.
Adding operation
Accessing operation
Removing operations
Iterating through the Deque
Let us go through each of the operations by implementing alongside by providing clean java program as follows:
Operation 1: Adding Elements
In order to add an element to the ArrayDeque, we can use the methods add(), addFirst(), addLast(), offer(), offerFirst(), offerLast() methods.
add()
addFirst()
addLast()
offer()
offerFirst()
offerLast()
Example
Java
// Java program to Illustrate Addition of elements// in ArrayDeque // Importing required classesimport java.io.*;import java.util.*; // Main class// AddingElementsToArrayDequepublic class GFG { // Main driver method public static void main(String[] args) { // Initializing a deque // since deque is an interface // it is assigned the // ArrayDeque class Deque<String> dq = new ArrayDeque<String>(); // add() method to insert dq.add("The"); dq.addFirst("To"); dq.addLast("Geeks"); // offer() method to insert dq.offer("For"); dq.offerFirst("Welcome"); dq.offerLast("Geeks"); // Printing Elements of ArrayDeque to the console System.out.println("ArrayDeque : " + dq); }}
ArrayDeque : [Welcome, To, The, Geeks, For, Geeks]
Operation 2: Accessing the Elements
After adding the elements, if we wish to access the elements, we can use inbuilt methods like getFirst(), getLast(), etc.
getFirst()
getLast()
peek()
peekFirst()
peekLast()
Example
Java
// Java program to Access Elements of ArrayDeque // Importing required classesimport java.io.*;import java.util.*; // Main class// AccessingElementsOfArrayDequepublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty ArrayDeque ArrayDeque<String> de_que = new ArrayDeque<String>(); // Using add() method to add elements into the Deque // Custom input elements de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("4"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("ArrayDeque: " + de_que); // Displaying the First element System.out.println("The first element is: " + de_que.getFirst()); // Displaying the Last element System.out.println("The last element is: " + de_que.getLast()); }}
ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
The first element is: Welcome
The last element is: Geeks
Operation 3. Removing Elements
In order to remove an element from a deque, there are various methods available. Since we can also remove from both the ends, the deque interface provides us with removeFirst(), removeLast() methods. Apart from that, this interface also provides us with the poll(), pop(), pollFirst(), pollLast() methods where pop() is used to remove and return the head of the deque. However, poll() is used because this offers the same functionality as pop() and doesn’t return an exception when the deque is empty. These sets of operations are as listed below as follows:
remove()
removeFirst()
removeLast()
poll()
pollFirst()
pollLast()
pop()
Example
Java
// Java program to Illustrate Removal Elements in Deque // Importing all utility classesimport java.util.*; // RemoveElementsOfArrayDequepublic class GFG { // Main driver method public static void main(String[] args) { // Initializing a deque Deque<String> dq = new ArrayDeque<String>(); // add() method to insert dq.add("One"); // addFirst inserts at the front dq.addFirst("Two"); // addLast inserts at the back dq.addLast("Three"); // print elements to the console System.out.println("ArrayDeque : " + dq); // remove element as a stack from top/front System.out.println(dq.pop()); // remove element as a queue from front System.out.println(dq.poll()); // remove element from front System.out.println(dq.pollFirst()); // remove element from back System.out.println(dq.pollLast()); }}
ArrayDeque : [Two, One, Three]
Two
One
Three
null
Operation 4: Iterating through the Deque
Since a deque can be iterated from both directions, the iterator method of the deque interface provides us two ways to iterate. One from the first and the other from the back. These sets of operations are listed below as follows:
remove()
iterator()
descendingIterator()
Example
Java
// Java program to Illustrate Iteration of Elements// in Deque // Importing all utility classesimport java.util.*; // Main class// IterateArrayDequepublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing an deque Deque<String> dq = new ArrayDeque<String>(); // Adding elements at the back // using add() method dq.add("For"); // Adding element at the front // using addFirst() method dq.addFirst("Geeks"); // add element at the last // using addLast() method dq.addLast("Geeks"); dq.add("is so good"); // Iterate using Iterator interface // from the front of the queue for (Iterator itr = dq.iterator(); itr.hasNext();) { // Print the elements System.out.print(itr.next() + " "); } // New line System.out.println(); // Iterate in reverse sequence in a queue for (Iterator itr = dq.descendingIterator(); itr.hasNext();) { System.out.print(itr.next() + " "); } }}
Geeks For Geeks is so good
is so good Geeks For Geeks
Related Articles:
Java.util.ArrayDeque Class in Java | Set 1
Java.util.ArrayDeque Class in Java | Set 2
ArrayList vs LinkedList in Java
Codextor
Code_Mech
Ganeshchowdharysadanala
wiprogovind
gabaa406
surindertarika1234
simmytarika5
anikakapoor
sagar0719kumar
Java - util package
Java-ArrayDeque
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Split() String method in Java with examples
Reverse a string in Java
Arrays.sort() in Java with examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Singleton Class in Java
How to add an element to an Array in Java?
Stream In Java
Initializing a List in Java
Different ways of Reading a text file in Java | [
{
"code": null,
"e": 28561,
"s": 28533,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 28861,
"s": 28561,
"text": "The ArrayDeque in Java provides a way to apply resizable-array in addition to the implementation of the Deque interface. It is also known as Array Double Ended Queue or Array Deck. This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue. "
},
{
"code": null,
"e": 28916,
"s": 28861,
"text": "Few important features of ArrayDeque are as follows: "
},
{
"code": null,
"e": 29004,
"s": 28916,
"text": "Array deques have no capacity restrictions and they grow as necessary to support usage."
},
{
"code": null,
"e": 29157,
"s": 29004,
"text": "They are not thread-safe which means that in the absence of external synchronization, ArrayDeque does not support concurrent access by multiple threads."
},
{
"code": null,
"e": 29205,
"s": 29157,
"text": "Null elements are prohibited in the ArrayDeque."
},
{
"code": null,
"e": 29278,
"s": 29205,
"text": "ArrayDeque class is likely to be faster than Stack when used as a stack."
},
{
"code": null,
"e": 29356,
"s": 29278,
"text": "ArrayDeque class is likely to be faster than LinkedList when used as a queue."
},
{
"code": null,
"e": 29394,
"s": 29356,
"text": "Interfaces implemented by ArrayDeque:"
},
{
"code": null,
"e": 29448,
"s": 29394,
"text": "The ArrayDeque class implements these two interfaces:"
},
{
"code": null,
"e": 29572,
"s": 29448,
"text": "Queue Interface: It is an Interface that is a FirstIn – FirstOut Data Structure where the elements are added from the back."
},
{
"code": null,
"e": 29716,
"s": 29572,
"text": "Deque Interface: It is a Doubly Ended Queue in which you can insert the elements from both sides. It is an interface that implements the Queue."
},
{
"code": null,
"e": 29939,
"s": 29716,
"text": "ArrayDeque implements both Queue and Deque. It is dynamically resizable from both sides. All implemented interfaces of ArrayDeque in the hierarchy are Serializable, Cloneable, Iterable<E>, Collection<E>, Deque<E>, Queue<E>"
},
{
"code": null,
"e": 29959,
"s": 29939,
"text": "Syntax: Declaration"
},
{
"code": null,
"e": 29987,
"s": 29959,
"text": "public class ArrayDeque<E> "
},
{
"code": null,
"e": 30018,
"s": 29987,
"text": "extends AbstractCollection<E> "
},
{
"code": null,
"e": 30063,
"s": 30018,
"text": "implements Deque<E>, Cloneable, Serializable"
},
{
"code": null,
"e": 30156,
"s": 30063,
"text": "Here, E refers to the element which can refer to any class, such as Integer or String class."
},
{
"code": null,
"e": 30321,
"s": 30156,
"text": "Now we are done with syntax now let us come up with constructors been defined for it prior before implementing to grasp it better and perceiving the output better. "
},
{
"code": null,
"e": 30452,
"s": 30321,
"text": "ArrayDeque(): This constructor is used to create an empty ArrayDeque and by default holds an initial capacity to hold 16 elements."
},
{
"code": null,
"e": 30492,
"s": 30452,
"text": "ArrayDeque<E> dq = new ArrayDeque<E>();"
},
{
"code": null,
"e": 30654,
"s": 30492,
"text": "ArrayDeque(Collection<? extends E> c): This constructor is used to create an ArrayDeque containing all the elements the same as that of the specified collection."
},
{
"code": null,
"e": 30708,
"s": 30654,
"text": "ArrayDeque<E> dq = new ArrayDeque<E>(Collection col);"
},
{
"code": null,
"e": 30860,
"s": 30708,
"text": "ArrayDeque(int numofElements): This constructor is used to create an empty ArrayDeque and holds the capacity to contain a specified number of elements."
},
{
"code": null,
"e": 30917,
"s": 30860,
"text": "ArrayDeque<E> dq = new ArrayDeque<E>(int numofElements);"
},
{
"code": null,
"e": 30955,
"s": 30917,
"text": "Methods in ArrayDeque are as follows:"
},
{
"code": null,
"e": 31022,
"s": 30955,
"text": "Note: Here, Element is the type of elements stored by ArrayDeque. "
},
{
"code": null,
"e": 31029,
"s": 31022,
"text": "METHOD"
},
{
"code": null,
"e": 31041,
"s": 31029,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 31099,
"s": 31041,
"text": "Methods inherited from class java.util.AbstractCollection"
},
{
"code": null,
"e": 31107,
"s": 31099,
"text": "Method "
},
{
"code": null,
"e": 31125,
"s": 31107,
"text": "Action Performed "
},
{
"code": null,
"e": 31179,
"s": 31125,
"text": "Methods inherited from interface java.util.Collection"
},
{
"code": null,
"e": 31187,
"s": 31179,
"text": "Method "
},
{
"code": null,
"e": 31205,
"s": 31187,
"text": "Action Performed "
},
{
"code": null,
"e": 31251,
"s": 31205,
"text": "Methods declared in interface java.util.Deque"
},
{
"code": null,
"e": 31259,
"s": 31251,
"text": "Method "
},
{
"code": null,
"e": 31277,
"s": 31259,
"text": "Action Performed "
},
{
"code": null,
"e": 31286,
"s": 31277,
"text": "Example "
},
{
"code": null,
"e": 31291,
"s": 31286,
"text": "Java"
},
{
"code": "// Java program to Implement ArrayDeque in Java// // Importing utility classesimport java.util.*; // ArrayDequeDemopublic class GGFG { public static void main(String[] args) { // Creating and initializing deque // Declaring object of integer type Deque<Integer> de_que = new ArrayDeque<Integer>(10); // Operations 1 // add() method // Adding custom elements // using add() method to insert de_que.add(10); de_que.add(20); de_que.add(30); de_que.add(40); de_que.add(50); // Iterating using for each loop for (Integer element : de_que) { // Print the corresponding element System.out.println(\"Element : \" + element); } // Operation 2 // clear() method System.out.println(\"Using clear() \"); // Clearing all elements using clear() method de_que.clear(); // Operations 3 // addFirst() method // Inserting at the start de_que.addFirst(564); de_que.addFirst(291); // Operation 4 // addLast() method // Inserting at end de_que.addLast(24); de_que.addLast(14); // Display message System.out.println( \"Above elements are removed now\"); // Iterators // Display message System.out.println( \"Elements of deque using Iterator :\"); for (Iterator itr = de_que.iterator(); itr.hasNext();) { System.out.println(itr.next()); } // descendingIterator() // To reverse the deque order System.out.println( \"Elements of deque in reverse order :\"); for (Iterator dItr = de_que.descendingIterator(); dItr.hasNext();) { System.out.println(dItr.next()); } // Operation 5 // element() method : to get Head element System.out.println( \"\\nHead Element using element(): \" + de_que.element()); // Operation 6 // getFirst() method : to get Head element System.out.println(\"Head Element using getFirst(): \" + de_que.getFirst()); // Operation 7 // getLast() method : to get last element System.out.println(\"Last Element using getLast(): \" + de_que.getLast()); // Operation 8 // toArray() method : Object[] arr = de_que.toArray(); System.out.println(\"\\nArray Size : \" + arr.length); System.out.print(\"Array elements : \"); for (int i = 0; i < arr.length; i++) System.out.print(\" \" + arr[i]); // Operation 9 // peek() method : to get head System.out.println(\"\\nHead element : \" + de_que.peek()); // Operation 10 // poll() method : to get head System.out.println(\"Head element poll : \" + de_que.poll()); // Operation 11 // push() method de_que.push(265); de_que.push(984); de_que.push(2365); // Operation 12 // remove() method : to get head System.out.println(\"Head element remove : \" + de_que.remove()); System.out.println(\"The final array is: \" + de_que); }}",
"e": 34613,
"s": 31291,
"text": null
},
{
"code": null,
"e": 35089,
"s": 34613,
"text": "Element : 10\nElement : 20\nElement : 30\nElement : 40\nElement : 50\nUsing clear() \nAbove elements are removed now\nElements of deque using Iterator :\n291\n564\n24\n14\nElements of deque in reverse order :\n14\n24\n564\n291\n\nHead Element using element(): 291\nHead Element using getFirst(): 291\nLast Element using getLast(): 14\n\nArray Size : 4\nArray elements : 291 564 24 14\nHead element : 291\nHead element poll : 291\nHead element remove : 2365\nThe final array is: [984, 265, 564, 24, 14]"
},
{
"code": null,
"e": 35395,
"s": 35089,
"text": "If there is some lag in clarity in this example, if so then we are proposing various operations on the ArrayDeque class Let’s see how to perform a few frequently used operations on the ArrayDeque to get a better understanding of the operations that we have used above to illustrate Array Deque as a whole."
},
{
"code": null,
"e": 35412,
"s": 35395,
"text": "Adding operation"
},
{
"code": null,
"e": 35432,
"s": 35412,
"text": "Accessing operation"
},
{
"code": null,
"e": 35452,
"s": 35432,
"text": "Removing operations"
},
{
"code": null,
"e": 35480,
"s": 35452,
"text": "Iterating through the Deque"
},
{
"code": null,
"e": 35591,
"s": 35480,
"text": "Let us go through each of the operations by implementing alongside by providing clean java program as follows:"
},
{
"code": null,
"e": 35620,
"s": 35591,
"text": "Operation 1: Adding Elements"
},
{
"code": null,
"e": 35764,
"s": 35620,
"text": "In order to add an element to the ArrayDeque, we can use the methods add(), addFirst(), addLast(), offer(), offerFirst(), offerLast() methods."
},
{
"code": null,
"e": 35770,
"s": 35764,
"text": "add()"
},
{
"code": null,
"e": 35781,
"s": 35770,
"text": "addFirst()"
},
{
"code": null,
"e": 35791,
"s": 35781,
"text": "addLast()"
},
{
"code": null,
"e": 35799,
"s": 35791,
"text": "offer()"
},
{
"code": null,
"e": 35812,
"s": 35799,
"text": "offerFirst()"
},
{
"code": null,
"e": 35824,
"s": 35812,
"text": "offerLast()"
},
{
"code": null,
"e": 35832,
"s": 35824,
"text": "Example"
},
{
"code": null,
"e": 35837,
"s": 35832,
"text": "Java"
},
{
"code": "// Java program to Illustrate Addition of elements// in ArrayDeque // Importing required classesimport java.io.*;import java.util.*; // Main class// AddingElementsToArrayDequepublic class GFG { // Main driver method public static void main(String[] args) { // Initializing a deque // since deque is an interface // it is assigned the // ArrayDeque class Deque<String> dq = new ArrayDeque<String>(); // add() method to insert dq.add(\"The\"); dq.addFirst(\"To\"); dq.addLast(\"Geeks\"); // offer() method to insert dq.offer(\"For\"); dq.offerFirst(\"Welcome\"); dq.offerLast(\"Geeks\"); // Printing Elements of ArrayDeque to the console System.out.println(\"ArrayDeque : \" + dq); }}",
"e": 36627,
"s": 35837,
"text": null
},
{
"code": null,
"e": 36678,
"s": 36627,
"text": "ArrayDeque : [Welcome, To, The, Geeks, For, Geeks]"
},
{
"code": null,
"e": 36714,
"s": 36678,
"text": "Operation 2: Accessing the Elements"
},
{
"code": null,
"e": 36836,
"s": 36714,
"text": "After adding the elements, if we wish to access the elements, we can use inbuilt methods like getFirst(), getLast(), etc."
},
{
"code": null,
"e": 36847,
"s": 36836,
"text": "getFirst()"
},
{
"code": null,
"e": 36857,
"s": 36847,
"text": "getLast()"
},
{
"code": null,
"e": 36864,
"s": 36857,
"text": "peek()"
},
{
"code": null,
"e": 36876,
"s": 36864,
"text": "peekFirst()"
},
{
"code": null,
"e": 36887,
"s": 36876,
"text": "peekLast()"
},
{
"code": null,
"e": 36896,
"s": 36887,
"text": "Example "
},
{
"code": null,
"e": 36901,
"s": 36896,
"text": "Java"
},
{
"code": "// Java program to Access Elements of ArrayDeque // Importing required classesimport java.io.*;import java.util.*; // Main class// AccessingElementsOfArrayDequepublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty ArrayDeque ArrayDeque<String> de_que = new ArrayDeque<String>(); // Using add() method to add elements into the Deque // Custom input elements de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"4\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"ArrayDeque: \" + de_que); // Displaying the First element System.out.println(\"The first element is: \" + de_que.getFirst()); // Displaying the Last element System.out.println(\"The last element is: \" + de_que.getLast()); }}",
"e": 37862,
"s": 36901,
"text": null
},
{
"code": null,
"e": 37962,
"s": 37862,
"text": "ArrayDeque: [Welcome, To, Geeks, 4, Geeks]\nThe first element is: Welcome\nThe last element is: Geeks"
},
{
"code": null,
"e": 37994,
"s": 37962,
"text": " Operation 3. Removing Elements"
},
{
"code": null,
"e": 38553,
"s": 37994,
"text": "In order to remove an element from a deque, there are various methods available. Since we can also remove from both the ends, the deque interface provides us with removeFirst(), removeLast() methods. Apart from that, this interface also provides us with the poll(), pop(), pollFirst(), pollLast() methods where pop() is used to remove and return the head of the deque. However, poll() is used because this offers the same functionality as pop() and doesn’t return an exception when the deque is empty. These sets of operations are as listed below as follows:"
},
{
"code": null,
"e": 38562,
"s": 38553,
"text": "remove()"
},
{
"code": null,
"e": 38576,
"s": 38562,
"text": "removeFirst()"
},
{
"code": null,
"e": 38589,
"s": 38576,
"text": "removeLast()"
},
{
"code": null,
"e": 38596,
"s": 38589,
"text": "poll()"
},
{
"code": null,
"e": 38608,
"s": 38596,
"text": "pollFirst()"
},
{
"code": null,
"e": 38619,
"s": 38608,
"text": "pollLast()"
},
{
"code": null,
"e": 38625,
"s": 38619,
"text": "pop()"
},
{
"code": null,
"e": 38634,
"s": 38625,
"text": "Example "
},
{
"code": null,
"e": 38639,
"s": 38634,
"text": "Java"
},
{
"code": "// Java program to Illustrate Removal Elements in Deque // Importing all utility classesimport java.util.*; // RemoveElementsOfArrayDequepublic class GFG { // Main driver method public static void main(String[] args) { // Initializing a deque Deque<String> dq = new ArrayDeque<String>(); // add() method to insert dq.add(\"One\"); // addFirst inserts at the front dq.addFirst(\"Two\"); // addLast inserts at the back dq.addLast(\"Three\"); // print elements to the console System.out.println(\"ArrayDeque : \" + dq); // remove element as a stack from top/front System.out.println(dq.pop()); // remove element as a queue from front System.out.println(dq.poll()); // remove element from front System.out.println(dq.pollFirst()); // remove element from back System.out.println(dq.pollLast()); }}",
"e": 39571,
"s": 38639,
"text": null
},
{
"code": null,
"e": 39621,
"s": 39571,
"text": "ArrayDeque : [Two, One, Three]\nTwo\nOne\nThree\nnull"
},
{
"code": null,
"e": 39662,
"s": 39621,
"text": "Operation 4: Iterating through the Deque"
},
{
"code": null,
"e": 39892,
"s": 39662,
"text": "Since a deque can be iterated from both directions, the iterator method of the deque interface provides us two ways to iterate. One from the first and the other from the back. These sets of operations are listed below as follows:"
},
{
"code": null,
"e": 39901,
"s": 39892,
"text": "remove()"
},
{
"code": null,
"e": 39912,
"s": 39901,
"text": "iterator()"
},
{
"code": null,
"e": 39933,
"s": 39912,
"text": "descendingIterator()"
},
{
"code": null,
"e": 39941,
"s": 39933,
"text": "Example"
},
{
"code": null,
"e": 39946,
"s": 39941,
"text": "Java"
},
{
"code": "// Java program to Illustrate Iteration of Elements// in Deque // Importing all utility classesimport java.util.*; // Main class// IterateArrayDequepublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing an deque Deque<String> dq = new ArrayDeque<String>(); // Adding elements at the back // using add() method dq.add(\"For\"); // Adding element at the front // using addFirst() method dq.addFirst(\"Geeks\"); // add element at the last // using addLast() method dq.addLast(\"Geeks\"); dq.add(\"is so good\"); // Iterate using Iterator interface // from the front of the queue for (Iterator itr = dq.iterator(); itr.hasNext();) { // Print the elements System.out.print(itr.next() + \" \"); } // New line System.out.println(); // Iterate in reverse sequence in a queue for (Iterator itr = dq.descendingIterator(); itr.hasNext();) { System.out.print(itr.next() + \" \"); } }}",
"e": 41077,
"s": 39946,
"text": null
},
{
"code": null,
"e": 41132,
"s": 41077,
"text": "Geeks For Geeks is so good \nis so good Geeks For Geeks"
},
{
"code": null,
"e": 41152,
"s": 41132,
"text": " Related Articles: "
},
{
"code": null,
"e": 41195,
"s": 41152,
"text": "Java.util.ArrayDeque Class in Java | Set 1"
},
{
"code": null,
"e": 41238,
"s": 41195,
"text": "Java.util.ArrayDeque Class in Java | Set 2"
},
{
"code": null,
"e": 41270,
"s": 41238,
"text": "ArrayList vs LinkedList in Java"
},
{
"code": null,
"e": 41279,
"s": 41270,
"text": "Codextor"
},
{
"code": null,
"e": 41289,
"s": 41279,
"text": "Code_Mech"
},
{
"code": null,
"e": 41313,
"s": 41289,
"text": "Ganeshchowdharysadanala"
},
{
"code": null,
"e": 41325,
"s": 41313,
"text": "wiprogovind"
},
{
"code": null,
"e": 41334,
"s": 41325,
"text": "gabaa406"
},
{
"code": null,
"e": 41353,
"s": 41334,
"text": "surindertarika1234"
},
{
"code": null,
"e": 41366,
"s": 41353,
"text": "simmytarika5"
},
{
"code": null,
"e": 41378,
"s": 41366,
"text": "anikakapoor"
},
{
"code": null,
"e": 41393,
"s": 41378,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 41413,
"s": 41393,
"text": "Java - util package"
},
{
"code": null,
"e": 41429,
"s": 41413,
"text": "Java-ArrayDeque"
},
{
"code": null,
"e": 41446,
"s": 41429,
"text": "Java-Collections"
},
{
"code": null,
"e": 41451,
"s": 41446,
"text": "Java"
},
{
"code": null,
"e": 41456,
"s": 41451,
"text": "Java"
},
{
"code": null,
"e": 41473,
"s": 41456,
"text": "Java-Collections"
},
{
"code": null,
"e": 41571,
"s": 41473,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41580,
"s": 41571,
"text": "Comments"
},
{
"code": null,
"e": 41593,
"s": 41580,
"text": "Old Comments"
},
{
"code": null,
"e": 41637,
"s": 41593,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 41662,
"s": 41637,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 41698,
"s": 41662,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 41729,
"s": 41698,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 41761,
"s": 41729,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 41785,
"s": 41761,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 41828,
"s": 41785,
"text": "How to add an element to an Array in Java?"
},
{
"code": null,
"e": 41843,
"s": 41828,
"text": "Stream In Java"
},
{
"code": null,
"e": 41871,
"s": 41843,
"text": "Initializing a List in Java"
}
] |
Advantages of getter and setter Over Public Fields in Java with Examples - GeeksforGeeks | 03 Mar, 2021
Providing getter and setter methods to access any class field in Java can at first look pointless and meaningless, simply because you can make the field public, and it is available in Java programs from anywhere. In reality, many programmers do this in the early days, but once you start thinking in terms of enterprise application or production code, you can begin to see how much maintenance trouble it can make.
Since software spends more time on maintenance than development according to the SDLC process, it is worth having ease of maintenance as one of the development goals. One of the Java coding best practices involves simply using the getter and setter approaches in Java.
Below are some advantages of getter and setter over public fields
1. The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement.
2. You make the class accessible with many open source libraries and modules such as display tags by making fields private by including getter and setter and following the java bean naming convention. It uses a combination of reflection and the Java bean naming convention to load and access fields dynamically.
3. You give Subclass an opportunity to override this method with getter and setter and return what makes more sense in the context of the subclass.
4. Hiding the property’s internal representation by using an alternative representation to expose a property.
5. Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.
Java
class Person { // private = restricted access private String name; // Getter public String getName() { return name; } // Setter public void setName(String newName) { this.name = newName; }} class Main { public static void main(String[] args) { Person person = new Person(); // Set the value of the name variable to "kapil" person.setName("kapil"); System.out.println(person.getName()); }}
kapil
Java-Field
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java | [
{
"code": null,
"e": 23581,
"s": 23553,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 23996,
"s": 23581,
"text": "Providing getter and setter methods to access any class field in Java can at first look pointless and meaningless, simply because you can make the field public, and it is available in Java programs from anywhere. In reality, many programmers do this in the early days, but once you start thinking in terms of enterprise application or production code, you can begin to see how much maintenance trouble it can make."
},
{
"code": null,
"e": 24265,
"s": 23996,
"text": "Since software spends more time on maintenance than development according to the SDLC process, it is worth having ease of maintenance as one of the development goals. One of the Java coding best practices involves simply using the getter and setter approaches in Java."
},
{
"code": null,
"e": 24331,
"s": 24265,
"text": "Below are some advantages of getter and setter over public fields"
},
{
"code": null,
"e": 24627,
"s": 24331,
"text": "1. The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement."
},
{
"code": null,
"e": 24939,
"s": 24627,
"text": "2. You make the class accessible with many open source libraries and modules such as display tags by making fields private by including getter and setter and following the java bean naming convention. It uses a combination of reflection and the Java bean naming convention to load and access fields dynamically."
},
{
"code": null,
"e": 25087,
"s": 24939,
"text": "3. You give Subclass an opportunity to override this method with getter and setter and return what makes more sense in the context of the subclass."
},
{
"code": null,
"e": 25197,
"s": 25087,
"text": "4. Hiding the property’s internal representation by using an alternative representation to expose a property."
},
{
"code": null,
"e": 25328,
"s": 25197,
"text": "5. Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods."
},
{
"code": null,
"e": 25333,
"s": 25328,
"text": "Java"
},
{
"code": "class Person { // private = restricted access private String name; // Getter public String getName() { return name; } // Setter public void setName(String newName) { this.name = newName; }} class Main { public static void main(String[] args) { Person person = new Person(); // Set the value of the name variable to \"kapil\" person.setName(\"kapil\"); System.out.println(person.getName()); }}",
"e": 25795,
"s": 25333,
"text": null
},
{
"code": null,
"e": 25802,
"s": 25795,
"text": "kapil\n"
},
{
"code": null,
"e": 25813,
"s": 25802,
"text": "Java-Field"
},
{
"code": null,
"e": 25820,
"s": 25813,
"text": "Picked"
},
{
"code": null,
"e": 25825,
"s": 25820,
"text": "Java"
},
{
"code": null,
"e": 25830,
"s": 25825,
"text": "Java"
},
{
"code": null,
"e": 25928,
"s": 25830,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25937,
"s": 25928,
"text": "Comments"
},
{
"code": null,
"e": 25950,
"s": 25937,
"text": "Old Comments"
},
{
"code": null,
"e": 25980,
"s": 25950,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 25995,
"s": 25980,
"text": "Stream In Java"
},
{
"code": null,
"e": 26016,
"s": 25995,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26062,
"s": 26016,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26081,
"s": 26062,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26098,
"s": 26081,
"text": "Generics in Java"
},
{
"code": null,
"e": 26141,
"s": 26098,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26157,
"s": 26141,
"text": "Strings in Java"
},
{
"code": null,
"e": 26206,
"s": 26157,
"text": "How to remove an element from ArrayList in Java?"
}
] |
A (very) friendly introduction to Confidence Intervals | by Dima Shulga | Towards Data Science | Today I want to talk about a basic term in statistics — confidence intervals, I want to do it in a very friendly manner, discussing only the general idea, without too much fancy statistics terms and with python!
Although this term is very basic, it sometimes very hard to fully understand (as it was for me) what’s really going on, why we need it and when should we use it.
So let’s start.
Suppose you want to know what percentage of people in the U.S. who love soccer. The only one thing you can do in order to get a 100% correct answer to that question is by asking each one of the citizens in the U.S. whether or not they love soccer. According to Wikipedia, there’re over 325 million people in the U.S. It is not really practical to talk to 325 million people, so we got to think about something else, we have to get an answer by asking (much) less people.
We can do that by getting a random sample of people in the U.S. (talk to much less people) and get the percentage of people who love soccer in that sample, but then we won’t be 100% confident that this number is right or how far is this number from the real answer, so, what we’ll try to achieve is get an interval, for example, a possible answer to that question may be: “I am 95% confident that the percentage of people that love soccer in the U.S. is between 58% and 62%”. That’s where the name Confidence Interval come from, we have an interval, and we have some confidence about it.
Side note: Its very important that our sample will be random, we can’t just choose 1000 people from the city we live in, because then it won’t represent the whole U.S. population well. Another bad example, we can’t send Facebook messages to 1000 random people, because then we’ll get a representation of U.S. Facebook users, and of course not all of the U.S. citizens use Facebook.
So let’s say we have a random sample of 1000 of people form U.S. and we see that among those 1000 people 63% love soccer, what can we assume (infer) about the whole U.S. population?
In order to answer that, I want us to look at it in a different way. Suppose we know (theoretically) the exact percentage of people in the U.S., let's say it’s 65%, what is the chance, that by randomly picking 1000 people, only 63% of them will love soccer? lets use python to explore this!
love_soccer_prop = 0.65 # Real percentage of people who love soccertotal_population = 325*10**6 # Total population in the U.S. (325M)num_people_love_soccer = int(total_population * love_soccer_prop)num_people_dont_love_soccer = int(total_population * (1 - love_soccer_prop))people_love_soccer = np.ones(num_of_people_who_love_soccer)people_dont_love_soccer = np.zeros(num_people_dont_love_soccer)all_people = np.hstack([people_love_soccer, people_dont_love_soccer])print np.mean(all_people)# Output = 0.65000000000000002
In this code I created a numpy array with 325 million people, for each one of them I store one if he/she loves soccer and zero otherwise. We can get the percentage of ones in the array by calculating the mean of it, and indeed it is 65%.
Now, lets take few samples and see what percentage do we get:
for i in range(10): sample = np.random.choice(all_people, size=1000) print 'Sample', i, ':', np.mean(sample)# Output:Sample 0 : 0.641Sample 1 : 0.647Sample 2 : 0.661Sample 3 : 0.642Sample 4 : 0.652Sample 5 : 0.647Sample 6 : 0.671Sample 7 : 0.629Sample 8 : 0.648Sample 9 : 0.627
You can see that we’re getting different values for each sample, but the intuition (and statistics theory) says that the average of large amount of samples should be very close to the real percentage. Let’s do that! lets take many samples and see what happens:
values = []for i in range(10000): sample = np.random.choice(all_people, size=1000) mean = np.mean(sample) values.append(mean)print np.mean(values)# Output = 0.64982259999999992
We created 10K samples, checked what is the percentage of people who love soccer in each sample, and then just averaged them, we got 64.98% which is very close to the real value 65%. Let’s plot all the values we got:
What you see here is an histogram of all the values we got in all the samples, a very nice property of this histogram is that it very similar to the normal distribution. As I said I don’t want to use too much statistics terms here, but let’s just say that if we do this process a very large number of times (infinite number of times) we will get an histogram that is very close to the normal distribution and we can know the parameters of this distribution. In more simple words, we’ll know the shape of this histogram, so we’ll be able to tell exactly how many samples can get any range of values.
Here’s an example, we’ll run this simulation ever more times (trying to reach infinity):
First of all, we can see that the center (the mean) of the histogram is near 65%, exactly as we expected, but we are able to say much more just by looking at the histogram, for example, we can say, that half of the samples are larger than 65%, or, we can say that roughly 25% are larger than 67%, or even, we can say that (roughly) only 2.5% of the samples are larger than 68%.
At this point, many people might ask two important questions, “How can I take infinite number of samples?” and “How does it helps me?”.
Let’s go back to our example, we took a sample of 1000 people and got 63%, we wanted to know, what is the chance that a random sample of 1000 people will have 63% soccer lovers. Using this histogram, we can say that there’s a chance of (roughly) 25% that we’ll get a value that is smaller or equal to 63%. We don’t actually need to do the infinite samples, the theory says us, that it is somewhat probable that if we choose randomly 1000 people, only 63% of them will love soccer.
Side note #2: Actually, in order to all that (find the chance of range of values), we need to know, or at least estimate, the standard deviation of the population. As I want to keep things simple, I’ll leave it for now.
Let’s go back to the reality and the real question, I don’t know the actual percentage of soccer lovers in the U.S. I just took a sample and got 63%, how does it help me?
So we don’t know the actual percentage of people who love soccer in the U.S. What we do know, that if we took infinite number of samples it will look like this:
Here μ is the population mean (real percentage of soccer lovers in our example), and σ is the standard deviation of the population.
If we know this (and we know the standard deviation) we are able to say that ~64% of the samples will fall in the red area or, more than 95% of the samples will fall outside the green area in this plot:
If we use the plots before when we assumed that the actual percentage is 65%, than 95% of the samples will fall between 62% and 68% (+- 3)
Of course the distance is symmetric, so if the sample percentage will fall 95% of the time between real percentage-3 and real percentage +3, then the real percentage will be 95% of the times between sample percentage -3 and sample percentage +3.
If we took a sample and got 63%, we can say that we 95% confident that the real percentage is between 60% (63 -3) and 66% (63+3).
This is the Confidence Interval, the interval is 63+-3 and the confidence is 95%.
I hope confidence intervals make more sense now, as I said before, this introduction misses some technical but important parts. There are plenty of articles that do contain these parts, and I hope that now it will be much easier to follow them. | [
{
"code": null,
"e": 384,
"s": 172,
"text": "Today I want to talk about a basic term in statistics — confidence intervals, I want to do it in a very friendly manner, discussing only the general idea, without too much fancy statistics terms and with python!"
},
{
"code": null,
"e": 546,
"s": 384,
"text": "Although this term is very basic, it sometimes very hard to fully understand (as it was for me) what’s really going on, why we need it and when should we use it."
},
{
"code": null,
"e": 562,
"s": 546,
"text": "So let’s start."
},
{
"code": null,
"e": 1033,
"s": 562,
"text": "Suppose you want to know what percentage of people in the U.S. who love soccer. The only one thing you can do in order to get a 100% correct answer to that question is by asking each one of the citizens in the U.S. whether or not they love soccer. According to Wikipedia, there’re over 325 million people in the U.S. It is not really practical to talk to 325 million people, so we got to think about something else, we have to get an answer by asking (much) less people."
},
{
"code": null,
"e": 1621,
"s": 1033,
"text": "We can do that by getting a random sample of people in the U.S. (talk to much less people) and get the percentage of people who love soccer in that sample, but then we won’t be 100% confident that this number is right or how far is this number from the real answer, so, what we’ll try to achieve is get an interval, for example, a possible answer to that question may be: “I am 95% confident that the percentage of people that love soccer in the U.S. is between 58% and 62%”. That’s where the name Confidence Interval come from, we have an interval, and we have some confidence about it."
},
{
"code": null,
"e": 2003,
"s": 1621,
"text": "Side note: Its very important that our sample will be random, we can’t just choose 1000 people from the city we live in, because then it won’t represent the whole U.S. population well. Another bad example, we can’t send Facebook messages to 1000 random people, because then we’ll get a representation of U.S. Facebook users, and of course not all of the U.S. citizens use Facebook."
},
{
"code": null,
"e": 2185,
"s": 2003,
"text": "So let’s say we have a random sample of 1000 of people form U.S. and we see that among those 1000 people 63% love soccer, what can we assume (infer) about the whole U.S. population?"
},
{
"code": null,
"e": 2476,
"s": 2185,
"text": "In order to answer that, I want us to look at it in a different way. Suppose we know (theoretically) the exact percentage of people in the U.S., let's say it’s 65%, what is the chance, that by randomly picking 1000 people, only 63% of them will love soccer? lets use python to explore this!"
},
{
"code": null,
"e": 2999,
"s": 2476,
"text": "love_soccer_prop = 0.65 # Real percentage of people who love soccertotal_population = 325*10**6 # Total population in the U.S. (325M)num_people_love_soccer = int(total_population * love_soccer_prop)num_people_dont_love_soccer = int(total_population * (1 - love_soccer_prop))people_love_soccer = np.ones(num_of_people_who_love_soccer)people_dont_love_soccer = np.zeros(num_people_dont_love_soccer)all_people = np.hstack([people_love_soccer, people_dont_love_soccer])print np.mean(all_people)# Output = 0.65000000000000002"
},
{
"code": null,
"e": 3237,
"s": 2999,
"text": "In this code I created a numpy array with 325 million people, for each one of them I store one if he/she loves soccer and zero otherwise. We can get the percentage of ones in the array by calculating the mean of it, and indeed it is 65%."
},
{
"code": null,
"e": 3299,
"s": 3237,
"text": "Now, lets take few samples and see what percentage do we get:"
},
{
"code": null,
"e": 3583,
"s": 3299,
"text": "for i in range(10): sample = np.random.choice(all_people, size=1000) print 'Sample', i, ':', np.mean(sample)# Output:Sample 0 : 0.641Sample 1 : 0.647Sample 2 : 0.661Sample 3 : 0.642Sample 4 : 0.652Sample 5 : 0.647Sample 6 : 0.671Sample 7 : 0.629Sample 8 : 0.648Sample 9 : 0.627"
},
{
"code": null,
"e": 3844,
"s": 3583,
"text": "You can see that we’re getting different values for each sample, but the intuition (and statistics theory) says that the average of large amount of samples should be very close to the real percentage. Let’s do that! lets take many samples and see what happens:"
},
{
"code": null,
"e": 4030,
"s": 3844,
"text": "values = []for i in range(10000): sample = np.random.choice(all_people, size=1000) mean = np.mean(sample) values.append(mean)print np.mean(values)# Output = 0.64982259999999992"
},
{
"code": null,
"e": 4247,
"s": 4030,
"text": "We created 10K samples, checked what is the percentage of people who love soccer in each sample, and then just averaged them, we got 64.98% which is very close to the real value 65%. Let’s plot all the values we got:"
},
{
"code": null,
"e": 4846,
"s": 4247,
"text": "What you see here is an histogram of all the values we got in all the samples, a very nice property of this histogram is that it very similar to the normal distribution. As I said I don’t want to use too much statistics terms here, but let’s just say that if we do this process a very large number of times (infinite number of times) we will get an histogram that is very close to the normal distribution and we can know the parameters of this distribution. In more simple words, we’ll know the shape of this histogram, so we’ll be able to tell exactly how many samples can get any range of values."
},
{
"code": null,
"e": 4935,
"s": 4846,
"text": "Here’s an example, we’ll run this simulation ever more times (trying to reach infinity):"
},
{
"code": null,
"e": 5313,
"s": 4935,
"text": "First of all, we can see that the center (the mean) of the histogram is near 65%, exactly as we expected, but we are able to say much more just by looking at the histogram, for example, we can say, that half of the samples are larger than 65%, or, we can say that roughly 25% are larger than 67%, or even, we can say that (roughly) only 2.5% of the samples are larger than 68%."
},
{
"code": null,
"e": 5449,
"s": 5313,
"text": "At this point, many people might ask two important questions, “How can I take infinite number of samples?” and “How does it helps me?”."
},
{
"code": null,
"e": 5930,
"s": 5449,
"text": "Let’s go back to our example, we took a sample of 1000 people and got 63%, we wanted to know, what is the chance that a random sample of 1000 people will have 63% soccer lovers. Using this histogram, we can say that there’s a chance of (roughly) 25% that we’ll get a value that is smaller or equal to 63%. We don’t actually need to do the infinite samples, the theory says us, that it is somewhat probable that if we choose randomly 1000 people, only 63% of them will love soccer."
},
{
"code": null,
"e": 6150,
"s": 5930,
"text": "Side note #2: Actually, in order to all that (find the chance of range of values), we need to know, or at least estimate, the standard deviation of the population. As I want to keep things simple, I’ll leave it for now."
},
{
"code": null,
"e": 6321,
"s": 6150,
"text": "Let’s go back to the reality and the real question, I don’t know the actual percentage of soccer lovers in the U.S. I just took a sample and got 63%, how does it help me?"
},
{
"code": null,
"e": 6482,
"s": 6321,
"text": "So we don’t know the actual percentage of people who love soccer in the U.S. What we do know, that if we took infinite number of samples it will look like this:"
},
{
"code": null,
"e": 6614,
"s": 6482,
"text": "Here μ is the population mean (real percentage of soccer lovers in our example), and σ is the standard deviation of the population."
},
{
"code": null,
"e": 6817,
"s": 6614,
"text": "If we know this (and we know the standard deviation) we are able to say that ~64% of the samples will fall in the red area or, more than 95% of the samples will fall outside the green area in this plot:"
},
{
"code": null,
"e": 6956,
"s": 6817,
"text": "If we use the plots before when we assumed that the actual percentage is 65%, than 95% of the samples will fall between 62% and 68% (+- 3)"
},
{
"code": null,
"e": 7202,
"s": 6956,
"text": "Of course the distance is symmetric, so if the sample percentage will fall 95% of the time between real percentage-3 and real percentage +3, then the real percentage will be 95% of the times between sample percentage -3 and sample percentage +3."
},
{
"code": null,
"e": 7332,
"s": 7202,
"text": "If we took a sample and got 63%, we can say that we 95% confident that the real percentage is between 60% (63 -3) and 66% (63+3)."
},
{
"code": null,
"e": 7414,
"s": 7332,
"text": "This is the Confidence Interval, the interval is 63+-3 and the confidence is 95%."
}
] |
How to delete the Azure Resource Group using PowerShell? | To delete the azure resource group using PowerShell, we need to use the Remove-AZResourceGroup command. But before using this command, make sure that no usable resources exist in the resource group that you want to delete.
To check if the resources are available in the resource group, use the below command. Here we are using the TestRG resource group name.
Get-AzResource -ResourceGroupName TestRG
Once you are confirmed that you need to delete the Resource Group then use the below command to delete the resource group.
Remove-AzResourceGroup TestRG -Force -Verbose
When you use the -Force parameter, you won’t be prompted for deletion confirmation. | [
{
"code": null,
"e": 1285,
"s": 1062,
"text": "To delete the azure resource group using PowerShell, we need to use the Remove-AZResourceGroup command. But before using this command, make sure that no usable resources exist in the resource group that you want to delete."
},
{
"code": null,
"e": 1421,
"s": 1285,
"text": "To check if the resources are available in the resource group, use the below command. Here we are using the TestRG resource group name."
},
{
"code": null,
"e": 1462,
"s": 1421,
"text": "Get-AzResource -ResourceGroupName TestRG"
},
{
"code": null,
"e": 1585,
"s": 1462,
"text": "Once you are confirmed that you need to delete the Resource Group then use the below command to delete the resource group."
},
{
"code": null,
"e": 1631,
"s": 1585,
"text": "Remove-AzResourceGroup TestRG -Force -Verbose"
},
{
"code": null,
"e": 1715,
"s": 1631,
"text": "When you use the -Force parameter, you won’t be prompted for deletion confirmation."
}
] |
Search in Rotated Sorted Array II in C++ | Consider we have an array sorted in ascending order. That is rotated at some pivot unknown to us beforehand. For example, if the array is like [0,0,1,2,2,5,6], this might become [2,5,6,0,0,1,2]. We have a target value to search. If that is found in the array, then return true, otherwise return false. So if the array is like [2,5,6,0,0,1,2], and target is 0, then the output will be 0
Let us see the steps −
low := 0 and high := size of array
low := 0 and high := size of array
while low < highmid := low + (high - low)/2if nums[mid] = target, then return trueif nums[low] = nums[mid] and nums[high - 1] = nums[mid], thenincrease low by 1 and decrease high by 1, and continue for the next iterationif nums[low] <= nums[mid], thenif target >= nums[low] and target < nums[mid], then high := mid, otherwise low := mid + 1Otherwiseif target <= nums[high - 1] and target > nums[mid], then low := mid + 1, otherwise high := midreturn false
while low < high
mid := low + (high - low)/2
mid := low + (high - low)/2
if nums[mid] = target, then return true
if nums[mid] = target, then return true
if nums[low] = nums[mid] and nums[high - 1] = nums[mid], thenincrease low by 1 and decrease high by 1, and continue for the next iteration
if nums[low] = nums[mid] and nums[high - 1] = nums[mid], then
increase low by 1 and decrease high by 1, and continue for the next iteration
increase low by 1 and decrease high by 1, and continue for the next iteration
if nums[low] <= nums[mid], thenif target >= nums[low] and target < nums[mid], then high := mid, otherwise low := mid + 1
if nums[low] <= nums[mid], then
if target >= nums[low] and target < nums[mid], then high := mid, otherwise low := mid + 1
if target >= nums[low] and target < nums[mid], then high := mid, otherwise low := mid + 1
Otherwiseif target <= nums[high - 1] and target > nums[mid], then low := mid + 1, otherwise high := mid
Otherwise
if target <= nums[high - 1] and target > nums[mid], then low := mid + 1, otherwise high := mid
if target <= nums[high - 1] and target > nums[mid], then low := mid + 1, otherwise high := mid
return false
return false
Let us see the following implementation to get better understanding −
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = len(nums)
while low<high:
mid = low + (high-low)//2
print(mid)
if nums[mid] == target:
return True
if nums[low] == nums[mid] and nums[high-1] == nums[mid]:
low +=1
high -=1
continue
if nums[low]<=nums[mid]:
if target >=nums[low] and target <nums[mid]:
high = mid
else:
low = mid+1
else:
if target<=nums[high-1] and target>nums[mid]:
low = mid+1
else:
high = mid
return False
[2,5,6,0,0,1,2]
0
true | [
{
"code": null,
"e": 1448,
"s": 1062,
"text": "Consider we have an array sorted in ascending order. That is rotated at some pivot unknown to us beforehand. For example, if the array is like [0,0,1,2,2,5,6], this might become [2,5,6,0,0,1,2]. We have a target value to search. If that is found in the array, then return true, otherwise return false. So if the array is like [2,5,6,0,0,1,2], and target is 0, then the output will be 0"
},
{
"code": null,
"e": 1471,
"s": 1448,
"text": "Let us see the steps −"
},
{
"code": null,
"e": 1506,
"s": 1471,
"text": "low := 0 and high := size of array"
},
{
"code": null,
"e": 1541,
"s": 1506,
"text": "low := 0 and high := size of array"
},
{
"code": null,
"e": 1997,
"s": 1541,
"text": "while low < highmid := low + (high - low)/2if nums[mid] = target, then return trueif nums[low] = nums[mid] and nums[high - 1] = nums[mid], thenincrease low by 1 and decrease high by 1, and continue for the next iterationif nums[low] <= nums[mid], thenif target >= nums[low] and target < nums[mid], then high := mid, otherwise low := mid + 1Otherwiseif target <= nums[high - 1] and target > nums[mid], then low := mid + 1, otherwise high := midreturn false"
},
{
"code": null,
"e": 2014,
"s": 1997,
"text": "while low < high"
},
{
"code": null,
"e": 2042,
"s": 2014,
"text": "mid := low + (high - low)/2"
},
{
"code": null,
"e": 2070,
"s": 2042,
"text": "mid := low + (high - low)/2"
},
{
"code": null,
"e": 2110,
"s": 2070,
"text": "if nums[mid] = target, then return true"
},
{
"code": null,
"e": 2150,
"s": 2110,
"text": "if nums[mid] = target, then return true"
},
{
"code": null,
"e": 2289,
"s": 2150,
"text": "if nums[low] = nums[mid] and nums[high - 1] = nums[mid], thenincrease low by 1 and decrease high by 1, and continue for the next iteration"
},
{
"code": null,
"e": 2351,
"s": 2289,
"text": "if nums[low] = nums[mid] and nums[high - 1] = nums[mid], then"
},
{
"code": null,
"e": 2429,
"s": 2351,
"text": "increase low by 1 and decrease high by 1, and continue for the next iteration"
},
{
"code": null,
"e": 2507,
"s": 2429,
"text": "increase low by 1 and decrease high by 1, and continue for the next iteration"
},
{
"code": null,
"e": 2628,
"s": 2507,
"text": "if nums[low] <= nums[mid], thenif target >= nums[low] and target < nums[mid], then high := mid, otherwise low := mid + 1"
},
{
"code": null,
"e": 2660,
"s": 2628,
"text": "if nums[low] <= nums[mid], then"
},
{
"code": null,
"e": 2750,
"s": 2660,
"text": "if target >= nums[low] and target < nums[mid], then high := mid, otherwise low := mid + 1"
},
{
"code": null,
"e": 2840,
"s": 2750,
"text": "if target >= nums[low] and target < nums[mid], then high := mid, otherwise low := mid + 1"
},
{
"code": null,
"e": 2944,
"s": 2840,
"text": "Otherwiseif target <= nums[high - 1] and target > nums[mid], then low := mid + 1, otherwise high := mid"
},
{
"code": null,
"e": 2954,
"s": 2944,
"text": "Otherwise"
},
{
"code": null,
"e": 3049,
"s": 2954,
"text": "if target <= nums[high - 1] and target > nums[mid], then low := mid + 1, otherwise high := mid"
},
{
"code": null,
"e": 3144,
"s": 3049,
"text": "if target <= nums[high - 1] and target > nums[mid], then low := mid + 1, otherwise high := mid"
},
{
"code": null,
"e": 3157,
"s": 3144,
"text": "return false"
},
{
"code": null,
"e": 3170,
"s": 3157,
"text": "return false"
},
{
"code": null,
"e": 3240,
"s": 3170,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3956,
"s": 3240,
"text": "class Solution(object):\n def search(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n low = 0\n high = len(nums)\n while low<high:\n mid = low + (high-low)//2\n print(mid)\n if nums[mid] == target:\n return True\n if nums[low] == nums[mid] and nums[high-1] == nums[mid]:\n low +=1\n high -=1\n continue\n if nums[low]<=nums[mid]:\n if target >=nums[low] and target <nums[mid]:\n high = mid\n else:\n low = mid+1\n else:\n if target<=nums[high-1] and target>nums[mid]:\n low = mid+1\n else:\n high = mid\n return False"
},
{
"code": null,
"e": 3974,
"s": 3956,
"text": "[2,5,6,0,0,1,2]\n0"
},
{
"code": null,
"e": 3979,
"s": 3974,
"text": "true"
}
] |
How to Build an Accounting System using SQLite | by Kenneth Infante | Towards Data Science | Scratch your own itch.
This is the advice that I always give whenever someone asks me how to learn programming. Practically, it means that you have to solve things or choose projects that are relevant to you — either in your work or personal life.
Mindlessly going to tutorials in Youtube, reading programming books, copying code from Reddit posts, etc. will get you nowhere if you’re starting to learn programming.
In this post, I’m going to show you how to build a crude accounting database using SQLite.
So, why create an accounting database? Why not just copy public data, shove them to SQLite, and practice from there?
The reason is that creating an accounting database is advance enough to cover all the aspects of databases and SQL — from queries to joins to views and CTEs.
Coming from an accounting background, I think that this is the best project to learn SQL. After all, programming is a tool to solve problems. Hence, might as well “solve” a difficult one to fully learn SQL.
I got the inspiration to create an accounting system using SQL by observing how Xero works. For those who are not familiar with it, Xero is a cloud accounting software originated in New Zealand. It has now expanded to Australia, the US, Canada, and the UK.
The good thing about Xero is that it has a nice clean interface and a lot of apps to choose from to extend its functionality.
Disclaimer: I’m not an engineer nor developer at Xero and these observations may not exactly correspond to how the system works as it is always updated. Certainly, the SQL presented here is not the exact SQL design that Xero use as their system needs to scale. But this is a very interesting project so let’s do it!
Before you get excited too much, let’s have a crash course first on accounting.
The fundamental accounting equation is
Assets = Liabilities + Equity
That equation has basically three parts
Assets are all the resources of the entity.
Liabilities are what the company owes.
and Equity, the accumulation of all the owner’s investment, drawings, profit or loss.
The right-hand side describes how the assets were financed — either thru Liabilities or Equity.
We can expand the above equation to break down the Equity
Assets = Liabilities + Beginning Equity + Revenues — Expenses
These 5 accounts — Assets, Liabilities, Equity, Revenues, & Expenses — are the account types that you typically see in an accounting system.
Then there’s the concept of Debit and Credit. I could go on and discuss these two in-depth but for this post, all you need to know is that in every transaction:
Debit = Credit
These two equations generally govern what’s happening in the whole accounting cycle. These two equations will also serve as a guide in creating our own accounting database.
Coming from an accounting background, I think that this is the best project to learn SQL. After all, programming is a tool to solve problems. Hence, might as well “solve” a difficult one to fully learn SQL.
The important thing to remember is that Xero is designed in such a way that it will be useful to business owners (not accountants) in the day-to-day operations of the business.
As such, it designed around transaction cycles and internal control.
The basic transaction cycles are the following
Sales Cycle
Purchases Cycle
Cash Cycle
Xero implements these cycles as follows
Sales CycleSales are entered into Xero using Invoices. Imagine the business issuing actual paper invoices for sales (cash sales or on account). This is the exact thing that Xero wants to replicate.
The invoices can be printed directly from the software and they are automatically numbered in increasing order.
Under the hood, invoices increase the Sales account and Accounts Receivable (AR) account.
Purchases CycleBills are entered into Xero using Bills. Again, imagine the business issuing actual bills for purchases (cash purchases or on account). This is the usual case for utilities and Inventory. This is also the thing that Xero wants to replicate.
The bills can be printed directly from the software and can be used to supplement any approval procedures done by the business.
Under the hood, bills increase the Purchases account and Accounts Payable (AP) account.
Cash CycleThis involves all transactions pertaining to Cash. There are 4 types
Invoice Payments — payments of the outstanding Invoices
Bill Payments — payments of the outstanding Bills
Received Money — cash receipts that are not invoice payments. This may involve cash sales but if you’re going to issue an invoice, use the Invoices feature.
Spent Money — cash disbursements that are not bill payments. This may involve cash purchases but if you’re going to issue a bill, use the Bills feature.
That’s the on the transaction cycles part.
For internal control, you need to understand the concept of system accounts.
Xero has a comprehensive article for understanding system accounts here. But for our purposes, we’re only going to discuss the following system accounts
Accounts Receivable
Accounts Payable
Bank Accounts (linked to Bank Feeds)
These accounts cannot be used in Manual journals. This means that Xero wants you to use Invoices, Bills, and Cash Transactions (Invoice Payments, Bill Payments, Received Money, and Spent Money) to support the balance of these accounts. This is Xero’s implementation of internal control if you will.
Of course, you can use the non-system version of the AR, AP, and Bank accounts by creating them in the Chart of Accounts (COA). However, you cannot use the AR, AP, and Bank account types for them.
The important thing to remember is that Xero is designed in such a way that it will be useful to business owners (not accountants) in the day-to-day operations of the business.
Designing an accounting is really complex. It will take multiple blog posts just to cover this topic. Hence, for simplicity, we’re going to create the following assumptions (not exactly how Xero implements these)
Invoice and Bill PaymentsInvoice Payments can pay two or more invoices wholly. Meaning, we’re not going to allow partial payments. The same is true with Bill Payments.
InventoryWe’re not going to use inventory items here. For sales or purchases, we’re going to use the Inventory account directly rather than create inventory items that mapped to the Inventory account.
That’s it for our assumptions. After designing our database, the reader can lift these assumptions and try mimicking Xero as much as possible.
Now before reconstructing our version of Xero’s database structure, let’s have a crash course on databases.
A database is a collection of tables. Each table consists of rows of data called records. The columns are called fields.
The program to work with a database is called a Database Management System or DBMS. As a simple analogy, DBMS is to Excel program, database is to Excel workbook and table is to an Excel worksheet.
There are two main differences between a database and an Excel workbook.
Meaning, you cannot edit data in a database by going over the directly to the data and editing it. (Other DBMS programs have GUIs that allow you to directly access data in a database and edit it like a spreadsheet. But under the hood, that action issues an SQL command).
Relationships can be one-to-one, one-to-many, or many-to-many.
One-to-one relationship means “a table row is related to only one row in another table and vice versa”. An example would be employee name to tax identification number.
This kind is usually included in a single table Employees as there’s really no benefit of separating the data into two tables.
One-to-many on the hand means “a table row is related to only one or more rows in another table but not vice versa”. An example is Invoices to InvoiceLines. An invoice may have multiple lines but an invoice line belongs only to a particular invoice.
And as you might have guessed it, many-to-many means “a table row is related to only one or more rows in another table and vice versa”. An example would be a system that implements partial payments.
An invoice may be paid partially by different payment transactions and a payment may pay different invoices partially.
How would a database knows these relationships?It’s simple. It’s through the use of primary and foreign keys.
Primary keys are necessary to distinguish one row from another. They uniquely identify each row of data in a table.
Foreign keys, on the other hand, are primary keys from another table. Hence, by relating the primary keys and foreign keys, the database relationships are persisted.
For one-to-many, the “one” side contains the primary key and the “many” contains this primary as its foreign key. In our above example, to get all the lines belonging to an invoice, we query the InvoiceLines table where the foreign key equals a particular invoice number.
For many to many, the relationship is broken down into two one-to-many relationships through a use of a third table called the “joining” table. For example, our partial payment system will have the Invoices table, Payments table, and InvoicePayments table as the joining table. The primary keys of the InvoicePayments table will be a composite key consisting of the primary keys for the Invoices and Payments table as follows
Take note that the joining table does not contain any other data as it does not have any other purpose aside from joining the Invoices and Payments tables.
To get the invoices paid by a certain payment transaction, say PAY 1, we join the Invoices and Payments tables through the joining table and query for the payment_id = “PAY 1”.
That’s it for the basics of a database. We’re now ready to design our database.
As a simple analogy, DBMS is to Excel program, database is to Excel workbook and table is to an Excel worksheet.
Now that we have a basic understanding of Xero to start creating a rough sketch of its database structure. Take note that I’m going to use Table_Name format. That’s is capitalized-first-letter words separated by underscores. I’m also going to use pluralized names for the table names.
For the Sales Cycle, we’re going to have the following tables
Invoices
Customers — a customer can have many invoices but an invoice can’t belong to many customers
Invoice_Payments — remember our assumption for now that there’s a one-to-many relationship between Invoice_Payments and Invoices respectively (no partial payments)
Invoice_Lines — this is the joining table between Invoices and COA. An account may appear in multiple invoices and an invoice may have multiple accounts.
Chart of Accounts (COA)
For the Purchases Cycle, we’re going to have the following tables
Bills
Suppliers — a supplier can have many bills but a bill can’t belong to many suppliers
Bill_Payments — remember our assumption for now that there’s a one-to-many relationship between Bill_Payments and Bills respectively
Bill_Lines — this is the joining table between Bills and COA. An account may appear in multiple bills and a bill may have multiple accounts.
COA — same with the above in the Sales Cycle. Just putting here for completeness.
For the Cash Cycle, we’re going to have the following tables (Payment tables we’re already created above)
Received_Moneys — may have an optional Customer
Received_Money_Lines — this is the joining table between Received_Moneys and COA
Spent_Moneys — may have an optional Supplier
Spent_Money_Lines — this is the joining table between Spent_Moneys and COA
Conceptually, our database structure is as follows
This diagram is called Entity-Relationship Diagram or ERD in the database parlance. One-to-many relationships are designated by 1 — M and many-to-many by M — M.
The joining tables are not shown in the above diagram as they are implicit in the tables with many-to-many relationships.
Now it’s time to implement our model in SQL. Let’s start by defining some conventions first.
The primary key will have field/column name of id, and the foreign key will have the format table_id where table is the name of the table of the “many” side in singular form. For example, in the Invoices table, the foreign key will be customer_id.
Time for the SQL code. Here it is.
DROP TABLE IF EXISTS `COA`;CREATE TABLE IF NOT EXISTS `COA` ( id INTEGER PRIMARY KEY, name TEXT);DROP TABLE IF EXISTS `Customers`;CREATE TABLE IF NOT EXISTS `Customers` ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, contact_person TEXT, email TEXT, phone TEXT, fax TEXT, address TEXT);DROP TABLE IF EXISTS `Invoice_Payments`;CREATE TABLE IF NOT EXISTS `Invoice_Payments` ( id INTEGER PRIMARY KEY, tran_date DATE NOT NULL, description TEXT, reference TEXT, total DECIMAL(20,2) NOT NULL, coa_id INTEGER NOT NULL, -- automatically Bank FOREIGN KEY(`coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Invoices`;CREATE TABLE IF NOT EXISTS `Invoices` ( id INTEGER PRIMARY KEY, tran_date DATE NOT NULL, due_date DATE, description TEXT, reference TEXT, total DECIMAL(10,2) NOT NULL, status BOOLEAN, customer_id INTEGER, invoice_payment_id INTEGER, coa_id INTEGER NOT NULL, -- automatically AR FOREIGN KEY(`customer_id`) REFERENCES `Customers`(`id`), FOREIGN KEY(`invoice_payment_id`) REFERENCES `Invoice_Payments`(`id`), FOREIGN KEY(`coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Received_Moneys`;CREATE TABLE IF NOT EXISTS `Received_Moneys` ( id INTEGER PRIMARY KEY, tran_date DATE NOT NULL, description TEXT, reference TEXT, total DECIMAL(20,2) NOT NULL, customer_id INTEGER, coa_id INTEGER NOT NULL, -- automatically Bank FOREIGN KEY(`customer_id`) REFERENCES `Customers`(`id`), FOREIGN KEY(`coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Invoice_Lines`;CREATE TABLE IF NOT EXISTS `Invoice_Lines` ( id INTEGER PRIMARY KEY, line_amount DECIMAL(20,2) NOT NULL, invoice_id INTEGER, line_coa_id INTEGER NOT NULL, FOREIGN KEY(`invoice_id`) REFERENCES `Invoices`(`id`), FOREIGN KEY(`line_coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Received_Money_Lines`;CREATE TABLE IF NOT EXISTS `Received_Money_Lines` ( id INTEGER PRIMARY KEY, line_amount DECIMAL(20,2) NOT NULL, received_money_id INTEGER, line_coa_id INTEGER NOT NULL, FOREIGN KEY(`received_money_id`) REFERENCES `Received_Moneys`(`id`), FOREIGN KEY(`line_coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Suppliers`;CREATE TABLE IF NOT EXISTS `Suppliers` ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, contact_person TEXT, email TEXT, phone TEXT, fax TEXT, address TEXT);DROP TABLE IF EXISTS `Bill_Payments`;CREATE TABLE IF NOT EXISTS `Bill_Payments` ( id INTEGER PRIMARY KEY, tran_date DATE NOT NULL, description TEXT, reference TEXT, total DECIMAL(20,2) NOT NULL, coa_id INTEGER NOT NULL, -- automatically Bank FOREIGN KEY(`coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Bills`;CREATE TABLE IF NOT EXISTS `Bills` ( id INTEGER PRIMARY KEY, tran_date DATE NOT NULL, due_date DATE, description TEXT, reference TEXT, total DECIMAL(10,2) NOT NULL, status BOOLEAN, supplier_id INTEGER, bill_payment_id INTEGER, coa_id INTEGER NOT NULL, -- automatically AP FOREIGN KEY(`supplier_id`) REFERENCES `Suppliers`(`id`), FOREIGN KEY(`bill_payment_id`) REFERENCES `Bill_Payments`(`id`), FOREIGN KEY(`coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Spent_Moneys`;CREATE TABLE IF NOT EXISTS `Spent_Moneys` ( id INTEGER PRIMARY KEY, tran_date DATE NOT NULL, description TEXT, reference TEXT, total DECIMAL(20,2) NOT NULL, supplier_id INTEGER, coa_id INTEGER NOT NULL, -- automatically Bank FOREIGN KEY(`supplier_id`) REFERENCES `Suppliers`(`id`), FOREIGN KEY(`coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Bill_Lines`;CREATE TABLE IF NOT EXISTS `Bill_Lines` ( id INTEGER PRIMARY KEY, line_amount DECIMAL(20,2) NOT NULL, bill_id INTEGER, line_coa_id INTEGER NOT NULL, FOREIGN KEY(`bill_id`) REFERENCES `Bills`(`id`), FOREIGN KEY(`line_coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Spent_Money_Lines`;CREATE TABLE IF NOT EXISTS `Spent_Money_Lines` ( id INTEGER PRIMARY KEY, line_amount DECIMAL(20,2) NOT NULL, spent_money_id INTEGER, line_coa_id INTEGER NOT NULL, FOREIGN KEY(`spent_money_id`) REFERENCES `Spent_Moneys`(`id`), FOREIGN KEY(`line_coa_id`) REFERENCES `COA`(`id`));
A couple of things here:
SQL commands are not case-sensitive, CREATE TABLE is same as create table
The IF EXISTS and IF NOT EXISTS are optional. I’ve just used them to prevent errors in my SQL commands. For example, if I drop a non-existing table, SQLite will give an error. Also, I put IF NOT EXISTS on the create table command so that we don’t accidentally override any existing table.
Be careful with the DROP TABLE command! It will delete an existing table without warning even if it has contents.
Table names can also be written all caps or not. If table names have spaces, they should be enclosed with backticks (`). They are not case-sensitive. SELECT * FROM Customers is same as select * from customers.
Even though SQL is a bit relax with regards to syntax, you should strive to maintain consistency in your SQL code.
Take note also of the relationships shown in the ERD above. Remember also that the foreign key is on the many side.
Order is important as some tables serve as a dependency to another because of the foreign key. For example, you have to create first Invoice_Payments first before the Invoice table as the former is a dependency of the latter. The trick here is to start with the edges of the ERD as those are the ones with the least number of foreign keys.
You could also download a sample database in SQLite with no content in this link.
To view it, you can use the free and open-sourced SQLite Browser. Download it here!
Now that we have the sample database, let’s input data to it. Sample data can be downloaded from here — just break it down to CSVs as needed.
Take note that credits are shown as positives and credits as negatives.
For this post, I just used DB Browser’s import feature to import CSVs from the above Excel file. For example, to import Customers.csv
Select the Customers table
Go to File > Import > Table from CSV file and choose the Customers.csv
Click Ok/Yes to all succeeding prompts to import the data.
If you issue the following SQL command, it should show all the Customers in our database
To prove that our database works as a crude accounting system, let’s create the Trial Balance.
The first step is to create the transaction views for our Invoices, Bills, Received_Moneys, and Spent_Moneys transactions. The code will be as follows
DROP VIEW IF EXISTS Invoice_Trans;CREATE VIEW IF NOT EXISTS Invoice_Trans ASwith recursiveitrans as (SELECT 'INV'||i.id as `tran_id`, i.tran_date, i.coa_id as ar_account, -- ABS(total) as `total`, 'Accounts Receivable' as `coa_name`, i.total, il.id as `line_id`, il.line_coa_id, il.line_amount, ip.id, ip.coa_id as bank_account, 'Business Bank Account' as `bank_name`, i.statusfrom Invoices as ileft join Invoice_Lines as il on i.id = il.invoice_idleft join COA as c on i.coa_id = c.idleft join Invoice_Payments as ip on i.invoice_payment_id = ip.id)selectitrans.*,c.name as `line_coa_name`from itransleft join COA as c on itrans.line_coa_id = c.id;SELECT * from Invoice_Trans;********************************************************************DROP VIEW IF EXISTS Bill_Trans;CREATE VIEW IF NOT EXISTS Bill_Trans ASwith recursivebtrans as (SELECT 'BILL'||b.id as `tran_id`, b.tran_date, b.coa_id as ap_account, -- ABS(total) as `total`, 'Accounts Payable' as `coa_name`, b.total, bl.id as `line_id`, bl.line_coa_id, bl.line_amount, bp.id, bp.coa_id as bank_account, 'Business Bank Account' as `bank_name`, b.statusfrom Bills as bleft join Bill_Lines as bl on b.id = bl.bill_idleft join COA as c on b.coa_id = c.idleft join Bill_Payments as bp on b.bill_payment_id = bp.id)selectbtrans.*,c.name as `line_coa_name`from btransleft join COA as c on btrans.line_coa_id = c.id;SELECT * from Bill_Trans;********************************************************************DROP VIEW IF EXISTS Received_Money_Trans;CREATE VIEW IF NOT EXISTS Received_Money_Trans ASSELECT 'RM'||rm.id as `tran_id`, tran_date, coa_id, 'Business Bank Account' as `coa_name`, total, rml.id as `line_id`, rml.line_coa_id, c.name as `line_coa_name`, rml.line_amountfrom Received_Moneys as rmleft join Received_Money_Lines as rml on rm.id = rml.received_money_idleft join COA as c on c.id = rml.line_coa_id;SELECT * from Received_Money_Trans;********************************************************************DROP VIEW IF EXISTS Spent_Money_Trans;CREATE VIEW IF NOT EXISTS Spent_Money_Trans ASSELECT 'SM'||sm.id as `tran_id`, tran_date, coa_id, 'Business Bank Account' as `coa_name`, total, sml.id as `line_id`, sml.line_coa_id, c.name as `line_coa_name`, sml.line_amountfrom Spent_Moneys as smleft join Spent_Money_Lines as sml on sm.id = sml.spent_money_idleft join COA as c on c.id = sml.line_coa_id;SELECT * from Spent_Money_Trans;
In the first two statements, I’m using a CTE (with the keyword recursive). CTEs are useful as I’m combining 4 tables to get a single view for Invoice transactions and corresponding payments. You could learn more above CTEs in SQLite here.
After executing the above command, your database should have the following 4 views.
Finally, we create the code for the Trial Balance or TB for short. Note that TB is just a collection of the balances of our transactions taking note of the rules we laid down when we designed our database.
The code is as follows
DROP VIEW IF EXISTS Trial_Balance;CREATE VIEW IF NOT EXISTS Trial_Balance as-- CREATE TB-- select all salesselect line_coa_id as acct_code, line_coa_name as acct_name, (case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as debit_bal, (case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as credit_balfrom Invoice_Transgroup by line_coa_id-- select all purchasesunion allselect line_coa_id as acct_code, line_coa_name as acct_name, (case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as debit_bal, (case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as credit_balfrom Bill_Transgroup by line_coa_id-- select all received moneyunion allselect line_coa_id as acct_code, line_coa_name as acct_name, (case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as debit_bal, (case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as credit_balfrom Received_Money_Transgroup by line_coa_id-- select all spent moneyunion allselect line_coa_id as acct_code, line_coa_name as acct_name, (case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as debit_bal, (case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as credit_balfrom Spent_Money_Transgroup by line_coa_id-- select all APunion allselect ap_account as acct_code, coa_name as acct_name, -(case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as debit_bal, -(case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as credit_balfrom Bill_Transwhere status = "0"-- select all ARunion allselect ar_account as acct_code, coa_name as acct_name, -(case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as debit_bal, -(case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as credit_balfrom Invoice_Transwhere status = "0"-- select all bill_paymentsunion allselect bank_account as acct_code, bank_name as acct_name, -(case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as debit_bal, -(case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as credit_balfrom Bill_Transwhere status = "1"-- select all invoice_paymentsunion allselect bank_account as acct_code, bank_name as acct_name, -(case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as debit_bal, -(case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as credit_balfrom Invoice_Transwhere status = "1"-- select all received_moneyunion allselect coa_id as acct_code, coa_name as acct_name, -(case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as debit_bal, -(case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as credit_balfrom Received_Money_Trans-- select all spent_moneyunion allselect coa_id as acct_code, coa_name as acct_name, -(case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as debit_bal, -(case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as credit_balfrom Spent_Money_Transorder by acct_code
The above code contains multiple SQL queries joined by the command union all. I’ve annotated each query to show what each is trying to achieve.
For example, the first query tries to get all the credits for the Invoice transactions (mostly Sales). The second one for the debits of the Bill transactions (mostly Purchases) and so on.
Executing it should result in the following TB.
You can put this in Excel to check that debits equal to credits (which I did). Total debits and credits are 14115 and -14115 respectively.
Creating an accounting system is really complex. We essentially explored the whole gamut of database design — from concepts to ERD to creation to querying it. Pat yourself on the back for reaching this far.
Take note that we deliberately limited our database to focus more on the concepts. You can lift these and try to build another one without the restrictions.
That’s it! You’re now an SQL ninja! Congratulations!
Check out my second book Accounting Database Design soon to be published on Leanpub!
Check out also my first book PowerQuery Guide to Pandas on Leanpub.
Follow me on Twitter and Linkedin. | [
{
"code": null,
"e": 195,
"s": 172,
"text": "Scratch your own itch."
},
{
"code": null,
"e": 420,
"s": 195,
"text": "This is the advice that I always give whenever someone asks me how to learn programming. Practically, it means that you have to solve things or choose projects that are relevant to you — either in your work or personal life."
},
{
"code": null,
"e": 588,
"s": 420,
"text": "Mindlessly going to tutorials in Youtube, reading programming books, copying code from Reddit posts, etc. will get you nowhere if you’re starting to learn programming."
},
{
"code": null,
"e": 679,
"s": 588,
"text": "In this post, I’m going to show you how to build a crude accounting database using SQLite."
},
{
"code": null,
"e": 796,
"s": 679,
"text": "So, why create an accounting database? Why not just copy public data, shove them to SQLite, and practice from there?"
},
{
"code": null,
"e": 954,
"s": 796,
"text": "The reason is that creating an accounting database is advance enough to cover all the aspects of databases and SQL — from queries to joins to views and CTEs."
},
{
"code": null,
"e": 1161,
"s": 954,
"text": "Coming from an accounting background, I think that this is the best project to learn SQL. After all, programming is a tool to solve problems. Hence, might as well “solve” a difficult one to fully learn SQL."
},
{
"code": null,
"e": 1418,
"s": 1161,
"text": "I got the inspiration to create an accounting system using SQL by observing how Xero works. For those who are not familiar with it, Xero is a cloud accounting software originated in New Zealand. It has now expanded to Australia, the US, Canada, and the UK."
},
{
"code": null,
"e": 1544,
"s": 1418,
"text": "The good thing about Xero is that it has a nice clean interface and a lot of apps to choose from to extend its functionality."
},
{
"code": null,
"e": 1860,
"s": 1544,
"text": "Disclaimer: I’m not an engineer nor developer at Xero and these observations may not exactly correspond to how the system works as it is always updated. Certainly, the SQL presented here is not the exact SQL design that Xero use as their system needs to scale. But this is a very interesting project so let’s do it!"
},
{
"code": null,
"e": 1940,
"s": 1860,
"text": "Before you get excited too much, let’s have a crash course first on accounting."
},
{
"code": null,
"e": 1979,
"s": 1940,
"text": "The fundamental accounting equation is"
},
{
"code": null,
"e": 2009,
"s": 1979,
"text": "Assets = Liabilities + Equity"
},
{
"code": null,
"e": 2049,
"s": 2009,
"text": "That equation has basically three parts"
},
{
"code": null,
"e": 2093,
"s": 2049,
"text": "Assets are all the resources of the entity."
},
{
"code": null,
"e": 2132,
"s": 2093,
"text": "Liabilities are what the company owes."
},
{
"code": null,
"e": 2218,
"s": 2132,
"text": "and Equity, the accumulation of all the owner’s investment, drawings, profit or loss."
},
{
"code": null,
"e": 2314,
"s": 2218,
"text": "The right-hand side describes how the assets were financed — either thru Liabilities or Equity."
},
{
"code": null,
"e": 2372,
"s": 2314,
"text": "We can expand the above equation to break down the Equity"
},
{
"code": null,
"e": 2434,
"s": 2372,
"text": "Assets = Liabilities + Beginning Equity + Revenues — Expenses"
},
{
"code": null,
"e": 2575,
"s": 2434,
"text": "These 5 accounts — Assets, Liabilities, Equity, Revenues, & Expenses — are the account types that you typically see in an accounting system."
},
{
"code": null,
"e": 2736,
"s": 2575,
"text": "Then there’s the concept of Debit and Credit. I could go on and discuss these two in-depth but for this post, all you need to know is that in every transaction:"
},
{
"code": null,
"e": 2751,
"s": 2736,
"text": "Debit = Credit"
},
{
"code": null,
"e": 2924,
"s": 2751,
"text": "These two equations generally govern what’s happening in the whole accounting cycle. These two equations will also serve as a guide in creating our own accounting database."
},
{
"code": null,
"e": 3131,
"s": 2924,
"text": "Coming from an accounting background, I think that this is the best project to learn SQL. After all, programming is a tool to solve problems. Hence, might as well “solve” a difficult one to fully learn SQL."
},
{
"code": null,
"e": 3308,
"s": 3131,
"text": "The important thing to remember is that Xero is designed in such a way that it will be useful to business owners (not accountants) in the day-to-day operations of the business."
},
{
"code": null,
"e": 3377,
"s": 3308,
"text": "As such, it designed around transaction cycles and internal control."
},
{
"code": null,
"e": 3424,
"s": 3377,
"text": "The basic transaction cycles are the following"
},
{
"code": null,
"e": 3436,
"s": 3424,
"text": "Sales Cycle"
},
{
"code": null,
"e": 3452,
"s": 3436,
"text": "Purchases Cycle"
},
{
"code": null,
"e": 3463,
"s": 3452,
"text": "Cash Cycle"
},
{
"code": null,
"e": 3503,
"s": 3463,
"text": "Xero implements these cycles as follows"
},
{
"code": null,
"e": 3701,
"s": 3503,
"text": "Sales CycleSales are entered into Xero using Invoices. Imagine the business issuing actual paper invoices for sales (cash sales or on account). This is the exact thing that Xero wants to replicate."
},
{
"code": null,
"e": 3813,
"s": 3701,
"text": "The invoices can be printed directly from the software and they are automatically numbered in increasing order."
},
{
"code": null,
"e": 3903,
"s": 3813,
"text": "Under the hood, invoices increase the Sales account and Accounts Receivable (AR) account."
},
{
"code": null,
"e": 4159,
"s": 3903,
"text": "Purchases CycleBills are entered into Xero using Bills. Again, imagine the business issuing actual bills for purchases (cash purchases or on account). This is the usual case for utilities and Inventory. This is also the thing that Xero wants to replicate."
},
{
"code": null,
"e": 4287,
"s": 4159,
"text": "The bills can be printed directly from the software and can be used to supplement any approval procedures done by the business."
},
{
"code": null,
"e": 4375,
"s": 4287,
"text": "Under the hood, bills increase the Purchases account and Accounts Payable (AP) account."
},
{
"code": null,
"e": 4454,
"s": 4375,
"text": "Cash CycleThis involves all transactions pertaining to Cash. There are 4 types"
},
{
"code": null,
"e": 4510,
"s": 4454,
"text": "Invoice Payments — payments of the outstanding Invoices"
},
{
"code": null,
"e": 4560,
"s": 4510,
"text": "Bill Payments — payments of the outstanding Bills"
},
{
"code": null,
"e": 4717,
"s": 4560,
"text": "Received Money — cash receipts that are not invoice payments. This may involve cash sales but if you’re going to issue an invoice, use the Invoices feature."
},
{
"code": null,
"e": 4870,
"s": 4717,
"text": "Spent Money — cash disbursements that are not bill payments. This may involve cash purchases but if you’re going to issue a bill, use the Bills feature."
},
{
"code": null,
"e": 4913,
"s": 4870,
"text": "That’s the on the transaction cycles part."
},
{
"code": null,
"e": 4990,
"s": 4913,
"text": "For internal control, you need to understand the concept of system accounts."
},
{
"code": null,
"e": 5143,
"s": 4990,
"text": "Xero has a comprehensive article for understanding system accounts here. But for our purposes, we’re only going to discuss the following system accounts"
},
{
"code": null,
"e": 5163,
"s": 5143,
"text": "Accounts Receivable"
},
{
"code": null,
"e": 5180,
"s": 5163,
"text": "Accounts Payable"
},
{
"code": null,
"e": 5217,
"s": 5180,
"text": "Bank Accounts (linked to Bank Feeds)"
},
{
"code": null,
"e": 5516,
"s": 5217,
"text": "These accounts cannot be used in Manual journals. This means that Xero wants you to use Invoices, Bills, and Cash Transactions (Invoice Payments, Bill Payments, Received Money, and Spent Money) to support the balance of these accounts. This is Xero’s implementation of internal control if you will."
},
{
"code": null,
"e": 5713,
"s": 5516,
"text": "Of course, you can use the non-system version of the AR, AP, and Bank accounts by creating them in the Chart of Accounts (COA). However, you cannot use the AR, AP, and Bank account types for them."
},
{
"code": null,
"e": 5890,
"s": 5713,
"text": "The important thing to remember is that Xero is designed in such a way that it will be useful to business owners (not accountants) in the day-to-day operations of the business."
},
{
"code": null,
"e": 6103,
"s": 5890,
"text": "Designing an accounting is really complex. It will take multiple blog posts just to cover this topic. Hence, for simplicity, we’re going to create the following assumptions (not exactly how Xero implements these)"
},
{
"code": null,
"e": 6271,
"s": 6103,
"text": "Invoice and Bill PaymentsInvoice Payments can pay two or more invoices wholly. Meaning, we’re not going to allow partial payments. The same is true with Bill Payments."
},
{
"code": null,
"e": 6472,
"s": 6271,
"text": "InventoryWe’re not going to use inventory items here. For sales or purchases, we’re going to use the Inventory account directly rather than create inventory items that mapped to the Inventory account."
},
{
"code": null,
"e": 6615,
"s": 6472,
"text": "That’s it for our assumptions. After designing our database, the reader can lift these assumptions and try mimicking Xero as much as possible."
},
{
"code": null,
"e": 6723,
"s": 6615,
"text": "Now before reconstructing our version of Xero’s database structure, let’s have a crash course on databases."
},
{
"code": null,
"e": 6844,
"s": 6723,
"text": "A database is a collection of tables. Each table consists of rows of data called records. The columns are called fields."
},
{
"code": null,
"e": 7041,
"s": 6844,
"text": "The program to work with a database is called a Database Management System or DBMS. As a simple analogy, DBMS is to Excel program, database is to Excel workbook and table is to an Excel worksheet."
},
{
"code": null,
"e": 7114,
"s": 7041,
"text": "There are two main differences between a database and an Excel workbook."
},
{
"code": null,
"e": 7385,
"s": 7114,
"text": "Meaning, you cannot edit data in a database by going over the directly to the data and editing it. (Other DBMS programs have GUIs that allow you to directly access data in a database and edit it like a spreadsheet. But under the hood, that action issues an SQL command)."
},
{
"code": null,
"e": 7448,
"s": 7385,
"text": "Relationships can be one-to-one, one-to-many, or many-to-many."
},
{
"code": null,
"e": 7616,
"s": 7448,
"text": "One-to-one relationship means “a table row is related to only one row in another table and vice versa”. An example would be employee name to tax identification number."
},
{
"code": null,
"e": 7743,
"s": 7616,
"text": "This kind is usually included in a single table Employees as there’s really no benefit of separating the data into two tables."
},
{
"code": null,
"e": 7993,
"s": 7743,
"text": "One-to-many on the hand means “a table row is related to only one or more rows in another table but not vice versa”. An example is Invoices to InvoiceLines. An invoice may have multiple lines but an invoice line belongs only to a particular invoice."
},
{
"code": null,
"e": 8192,
"s": 7993,
"text": "And as you might have guessed it, many-to-many means “a table row is related to only one or more rows in another table and vice versa”. An example would be a system that implements partial payments."
},
{
"code": null,
"e": 8311,
"s": 8192,
"text": "An invoice may be paid partially by different payment transactions and a payment may pay different invoices partially."
},
{
"code": null,
"e": 8421,
"s": 8311,
"text": "How would a database knows these relationships?It’s simple. It’s through the use of primary and foreign keys."
},
{
"code": null,
"e": 8537,
"s": 8421,
"text": "Primary keys are necessary to distinguish one row from another. They uniquely identify each row of data in a table."
},
{
"code": null,
"e": 8703,
"s": 8537,
"text": "Foreign keys, on the other hand, are primary keys from another table. Hence, by relating the primary keys and foreign keys, the database relationships are persisted."
},
{
"code": null,
"e": 8975,
"s": 8703,
"text": "For one-to-many, the “one” side contains the primary key and the “many” contains this primary as its foreign key. In our above example, to get all the lines belonging to an invoice, we query the InvoiceLines table where the foreign key equals a particular invoice number."
},
{
"code": null,
"e": 9401,
"s": 8975,
"text": "For many to many, the relationship is broken down into two one-to-many relationships through a use of a third table called the “joining” table. For example, our partial payment system will have the Invoices table, Payments table, and InvoicePayments table as the joining table. The primary keys of the InvoicePayments table will be a composite key consisting of the primary keys for the Invoices and Payments table as follows"
},
{
"code": null,
"e": 9557,
"s": 9401,
"text": "Take note that the joining table does not contain any other data as it does not have any other purpose aside from joining the Invoices and Payments tables."
},
{
"code": null,
"e": 9734,
"s": 9557,
"text": "To get the invoices paid by a certain payment transaction, say PAY 1, we join the Invoices and Payments tables through the joining table and query for the payment_id = “PAY 1”."
},
{
"code": null,
"e": 9814,
"s": 9734,
"text": "That’s it for the basics of a database. We’re now ready to design our database."
},
{
"code": null,
"e": 9927,
"s": 9814,
"text": "As a simple analogy, DBMS is to Excel program, database is to Excel workbook and table is to an Excel worksheet."
},
{
"code": null,
"e": 10212,
"s": 9927,
"text": "Now that we have a basic understanding of Xero to start creating a rough sketch of its database structure. Take note that I’m going to use Table_Name format. That’s is capitalized-first-letter words separated by underscores. I’m also going to use pluralized names for the table names."
},
{
"code": null,
"e": 10274,
"s": 10212,
"text": "For the Sales Cycle, we’re going to have the following tables"
},
{
"code": null,
"e": 10283,
"s": 10274,
"text": "Invoices"
},
{
"code": null,
"e": 10375,
"s": 10283,
"text": "Customers — a customer can have many invoices but an invoice can’t belong to many customers"
},
{
"code": null,
"e": 10539,
"s": 10375,
"text": "Invoice_Payments — remember our assumption for now that there’s a one-to-many relationship between Invoice_Payments and Invoices respectively (no partial payments)"
},
{
"code": null,
"e": 10693,
"s": 10539,
"text": "Invoice_Lines — this is the joining table between Invoices and COA. An account may appear in multiple invoices and an invoice may have multiple accounts."
},
{
"code": null,
"e": 10717,
"s": 10693,
"text": "Chart of Accounts (COA)"
},
{
"code": null,
"e": 10783,
"s": 10717,
"text": "For the Purchases Cycle, we’re going to have the following tables"
},
{
"code": null,
"e": 10789,
"s": 10783,
"text": "Bills"
},
{
"code": null,
"e": 10874,
"s": 10789,
"text": "Suppliers — a supplier can have many bills but a bill can’t belong to many suppliers"
},
{
"code": null,
"e": 11007,
"s": 10874,
"text": "Bill_Payments — remember our assumption for now that there’s a one-to-many relationship between Bill_Payments and Bills respectively"
},
{
"code": null,
"e": 11148,
"s": 11007,
"text": "Bill_Lines — this is the joining table between Bills and COA. An account may appear in multiple bills and a bill may have multiple accounts."
},
{
"code": null,
"e": 11230,
"s": 11148,
"text": "COA — same with the above in the Sales Cycle. Just putting here for completeness."
},
{
"code": null,
"e": 11336,
"s": 11230,
"text": "For the Cash Cycle, we’re going to have the following tables (Payment tables we’re already created above)"
},
{
"code": null,
"e": 11384,
"s": 11336,
"text": "Received_Moneys — may have an optional Customer"
},
{
"code": null,
"e": 11465,
"s": 11384,
"text": "Received_Money_Lines — this is the joining table between Received_Moneys and COA"
},
{
"code": null,
"e": 11510,
"s": 11465,
"text": "Spent_Moneys — may have an optional Supplier"
},
{
"code": null,
"e": 11585,
"s": 11510,
"text": "Spent_Money_Lines — this is the joining table between Spent_Moneys and COA"
},
{
"code": null,
"e": 11636,
"s": 11585,
"text": "Conceptually, our database structure is as follows"
},
{
"code": null,
"e": 11797,
"s": 11636,
"text": "This diagram is called Entity-Relationship Diagram or ERD in the database parlance. One-to-many relationships are designated by 1 — M and many-to-many by M — M."
},
{
"code": null,
"e": 11919,
"s": 11797,
"text": "The joining tables are not shown in the above diagram as they are implicit in the tables with many-to-many relationships."
},
{
"code": null,
"e": 12012,
"s": 11919,
"text": "Now it’s time to implement our model in SQL. Let’s start by defining some conventions first."
},
{
"code": null,
"e": 12260,
"s": 12012,
"text": "The primary key will have field/column name of id, and the foreign key will have the format table_id where table is the name of the table of the “many” side in singular form. For example, in the Invoices table, the foreign key will be customer_id."
},
{
"code": null,
"e": 12295,
"s": 12260,
"text": "Time for the SQL code. Here it is."
},
{
"code": null,
"e": 16562,
"s": 12295,
"text": "DROP TABLE IF EXISTS `COA`;CREATE TABLE IF NOT EXISTS `COA` ( id INTEGER PRIMARY KEY, name TEXT);DROP TABLE IF EXISTS `Customers`;CREATE TABLE IF NOT EXISTS `Customers` ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, contact_person TEXT, email TEXT, phone TEXT, fax TEXT, address TEXT);DROP TABLE IF EXISTS `Invoice_Payments`;CREATE TABLE IF NOT EXISTS `Invoice_Payments` ( id INTEGER PRIMARY KEY, tran_date DATE NOT NULL, description TEXT, reference TEXT, total DECIMAL(20,2) NOT NULL, coa_id INTEGER NOT NULL, -- automatically Bank FOREIGN KEY(`coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Invoices`;CREATE TABLE IF NOT EXISTS `Invoices` ( id INTEGER PRIMARY KEY, tran_date DATE NOT NULL, due_date DATE, description TEXT, reference TEXT, total DECIMAL(10,2) NOT NULL, status BOOLEAN, customer_id INTEGER, invoice_payment_id INTEGER, coa_id INTEGER NOT NULL, -- automatically AR FOREIGN KEY(`customer_id`) REFERENCES `Customers`(`id`), FOREIGN KEY(`invoice_payment_id`) REFERENCES `Invoice_Payments`(`id`), FOREIGN KEY(`coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Received_Moneys`;CREATE TABLE IF NOT EXISTS `Received_Moneys` ( id INTEGER PRIMARY KEY, tran_date DATE NOT NULL, description TEXT, reference TEXT, total DECIMAL(20,2) NOT NULL, customer_id INTEGER, coa_id INTEGER NOT NULL, -- automatically Bank FOREIGN KEY(`customer_id`) REFERENCES `Customers`(`id`), FOREIGN KEY(`coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Invoice_Lines`;CREATE TABLE IF NOT EXISTS `Invoice_Lines` ( id INTEGER PRIMARY KEY, line_amount DECIMAL(20,2) NOT NULL, invoice_id INTEGER, line_coa_id INTEGER NOT NULL, FOREIGN KEY(`invoice_id`) REFERENCES `Invoices`(`id`), FOREIGN KEY(`line_coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Received_Money_Lines`;CREATE TABLE IF NOT EXISTS `Received_Money_Lines` ( id INTEGER PRIMARY KEY, line_amount DECIMAL(20,2) NOT NULL, received_money_id INTEGER, line_coa_id INTEGER NOT NULL, FOREIGN KEY(`received_money_id`) REFERENCES `Received_Moneys`(`id`), FOREIGN KEY(`line_coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Suppliers`;CREATE TABLE IF NOT EXISTS `Suppliers` ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, contact_person TEXT, email TEXT, phone TEXT, fax TEXT, address TEXT);DROP TABLE IF EXISTS `Bill_Payments`;CREATE TABLE IF NOT EXISTS `Bill_Payments` ( id INTEGER PRIMARY KEY, tran_date DATE NOT NULL, description TEXT, reference TEXT, total DECIMAL(20,2) NOT NULL, coa_id INTEGER NOT NULL, -- automatically Bank FOREIGN KEY(`coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Bills`;CREATE TABLE IF NOT EXISTS `Bills` ( id INTEGER PRIMARY KEY, tran_date DATE NOT NULL, due_date DATE, description TEXT, reference TEXT, total DECIMAL(10,2) NOT NULL, status BOOLEAN, supplier_id INTEGER, bill_payment_id INTEGER, coa_id INTEGER NOT NULL, -- automatically AP FOREIGN KEY(`supplier_id`) REFERENCES `Suppliers`(`id`), FOREIGN KEY(`bill_payment_id`) REFERENCES `Bill_Payments`(`id`), FOREIGN KEY(`coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Spent_Moneys`;CREATE TABLE IF NOT EXISTS `Spent_Moneys` ( id INTEGER PRIMARY KEY, tran_date DATE NOT NULL, description TEXT, reference TEXT, total DECIMAL(20,2) NOT NULL, supplier_id INTEGER, coa_id INTEGER NOT NULL, -- automatically Bank FOREIGN KEY(`supplier_id`) REFERENCES `Suppliers`(`id`), FOREIGN KEY(`coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Bill_Lines`;CREATE TABLE IF NOT EXISTS `Bill_Lines` ( id INTEGER PRIMARY KEY, line_amount DECIMAL(20,2) NOT NULL, bill_id INTEGER, line_coa_id INTEGER NOT NULL, FOREIGN KEY(`bill_id`) REFERENCES `Bills`(`id`), FOREIGN KEY(`line_coa_id`) REFERENCES `COA`(`id`));DROP TABLE IF EXISTS `Spent_Money_Lines`;CREATE TABLE IF NOT EXISTS `Spent_Money_Lines` ( id INTEGER PRIMARY KEY, line_amount DECIMAL(20,2) NOT NULL, spent_money_id INTEGER, line_coa_id INTEGER NOT NULL, FOREIGN KEY(`spent_money_id`) REFERENCES `Spent_Moneys`(`id`), FOREIGN KEY(`line_coa_id`) REFERENCES `COA`(`id`));"
},
{
"code": null,
"e": 16587,
"s": 16562,
"text": "A couple of things here:"
},
{
"code": null,
"e": 16661,
"s": 16587,
"text": "SQL commands are not case-sensitive, CREATE TABLE is same as create table"
},
{
"code": null,
"e": 16950,
"s": 16661,
"text": "The IF EXISTS and IF NOT EXISTS are optional. I’ve just used them to prevent errors in my SQL commands. For example, if I drop a non-existing table, SQLite will give an error. Also, I put IF NOT EXISTS on the create table command so that we don’t accidentally override any existing table."
},
{
"code": null,
"e": 17064,
"s": 16950,
"text": "Be careful with the DROP TABLE command! It will delete an existing table without warning even if it has contents."
},
{
"code": null,
"e": 17274,
"s": 17064,
"text": "Table names can also be written all caps or not. If table names have spaces, they should be enclosed with backticks (`). They are not case-sensitive. SELECT * FROM Customers is same as select * from customers."
},
{
"code": null,
"e": 17389,
"s": 17274,
"text": "Even though SQL is a bit relax with regards to syntax, you should strive to maintain consistency in your SQL code."
},
{
"code": null,
"e": 17505,
"s": 17389,
"text": "Take note also of the relationships shown in the ERD above. Remember also that the foreign key is on the many side."
},
{
"code": null,
"e": 17845,
"s": 17505,
"text": "Order is important as some tables serve as a dependency to another because of the foreign key. For example, you have to create first Invoice_Payments first before the Invoice table as the former is a dependency of the latter. The trick here is to start with the edges of the ERD as those are the ones with the least number of foreign keys."
},
{
"code": null,
"e": 17927,
"s": 17845,
"text": "You could also download a sample database in SQLite with no content in this link."
},
{
"code": null,
"e": 18011,
"s": 17927,
"text": "To view it, you can use the free and open-sourced SQLite Browser. Download it here!"
},
{
"code": null,
"e": 18153,
"s": 18011,
"text": "Now that we have the sample database, let’s input data to it. Sample data can be downloaded from here — just break it down to CSVs as needed."
},
{
"code": null,
"e": 18225,
"s": 18153,
"text": "Take note that credits are shown as positives and credits as negatives."
},
{
"code": null,
"e": 18359,
"s": 18225,
"text": "For this post, I just used DB Browser’s import feature to import CSVs from the above Excel file. For example, to import Customers.csv"
},
{
"code": null,
"e": 18386,
"s": 18359,
"text": "Select the Customers table"
},
{
"code": null,
"e": 18457,
"s": 18386,
"text": "Go to File > Import > Table from CSV file and choose the Customers.csv"
},
{
"code": null,
"e": 18516,
"s": 18457,
"text": "Click Ok/Yes to all succeeding prompts to import the data."
},
{
"code": null,
"e": 18605,
"s": 18516,
"text": "If you issue the following SQL command, it should show all the Customers in our database"
},
{
"code": null,
"e": 18700,
"s": 18605,
"text": "To prove that our database works as a crude accounting system, let’s create the Trial Balance."
},
{
"code": null,
"e": 18851,
"s": 18700,
"text": "The first step is to create the transaction views for our Invoices, Bills, Received_Moneys, and Spent_Moneys transactions. The code will be as follows"
},
{
"code": null,
"e": 21392,
"s": 18851,
"text": "DROP VIEW IF EXISTS Invoice_Trans;CREATE VIEW IF NOT EXISTS Invoice_Trans ASwith recursiveitrans as (SELECT 'INV'||i.id as `tran_id`, i.tran_date, i.coa_id as ar_account, -- ABS(total) as `total`, 'Accounts Receivable' as `coa_name`, i.total, il.id as `line_id`, il.line_coa_id, il.line_amount, ip.id, ip.coa_id as bank_account, 'Business Bank Account' as `bank_name`, i.statusfrom Invoices as ileft join Invoice_Lines as il on i.id = il.invoice_idleft join COA as c on i.coa_id = c.idleft join Invoice_Payments as ip on i.invoice_payment_id = ip.id)selectitrans.*,c.name as `line_coa_name`from itransleft join COA as c on itrans.line_coa_id = c.id;SELECT * from Invoice_Trans;********************************************************************DROP VIEW IF EXISTS Bill_Trans;CREATE VIEW IF NOT EXISTS Bill_Trans ASwith recursivebtrans as (SELECT 'BILL'||b.id as `tran_id`, b.tran_date, b.coa_id as ap_account, -- ABS(total) as `total`, 'Accounts Payable' as `coa_name`, b.total, bl.id as `line_id`, bl.line_coa_id, bl.line_amount, bp.id, bp.coa_id as bank_account, 'Business Bank Account' as `bank_name`, b.statusfrom Bills as bleft join Bill_Lines as bl on b.id = bl.bill_idleft join COA as c on b.coa_id = c.idleft join Bill_Payments as bp on b.bill_payment_id = bp.id)selectbtrans.*,c.name as `line_coa_name`from btransleft join COA as c on btrans.line_coa_id = c.id;SELECT * from Bill_Trans;********************************************************************DROP VIEW IF EXISTS Received_Money_Trans;CREATE VIEW IF NOT EXISTS Received_Money_Trans ASSELECT 'RM'||rm.id as `tran_id`, tran_date, coa_id, 'Business Bank Account' as `coa_name`, total, rml.id as `line_id`, rml.line_coa_id, c.name as `line_coa_name`, rml.line_amountfrom Received_Moneys as rmleft join Received_Money_Lines as rml on rm.id = rml.received_money_idleft join COA as c on c.id = rml.line_coa_id;SELECT * from Received_Money_Trans;********************************************************************DROP VIEW IF EXISTS Spent_Money_Trans;CREATE VIEW IF NOT EXISTS Spent_Money_Trans ASSELECT 'SM'||sm.id as `tran_id`, tran_date, coa_id, 'Business Bank Account' as `coa_name`, total, sml.id as `line_id`, sml.line_coa_id, c.name as `line_coa_name`, sml.line_amountfrom Spent_Moneys as smleft join Spent_Money_Lines as sml on sm.id = sml.spent_money_idleft join COA as c on c.id = sml.line_coa_id;SELECT * from Spent_Money_Trans;"
},
{
"code": null,
"e": 21631,
"s": 21392,
"text": "In the first two statements, I’m using a CTE (with the keyword recursive). CTEs are useful as I’m combining 4 tables to get a single view for Invoice transactions and corresponding payments. You could learn more above CTEs in SQLite here."
},
{
"code": null,
"e": 21715,
"s": 21631,
"text": "After executing the above command, your database should have the following 4 views."
},
{
"code": null,
"e": 21921,
"s": 21715,
"text": "Finally, we create the code for the Trial Balance or TB for short. Note that TB is just a collection of the balances of our transactions taking note of the rules we laid down when we designed our database."
},
{
"code": null,
"e": 21944,
"s": 21921,
"text": "The code is as follows"
},
{
"code": null,
"e": 25008,
"s": 21944,
"text": "DROP VIEW IF EXISTS Trial_Balance;CREATE VIEW IF NOT EXISTS Trial_Balance as-- CREATE TB-- select all salesselect line_coa_id as acct_code, line_coa_name as acct_name, (case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as debit_bal, (case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as credit_balfrom Invoice_Transgroup by line_coa_id-- select all purchasesunion allselect line_coa_id as acct_code, line_coa_name as acct_name, (case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as debit_bal, (case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as credit_balfrom Bill_Transgroup by line_coa_id-- select all received moneyunion allselect line_coa_id as acct_code, line_coa_name as acct_name, (case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as debit_bal, (case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as credit_balfrom Received_Money_Transgroup by line_coa_id-- select all spent moneyunion allselect line_coa_id as acct_code, line_coa_name as acct_name, (case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as debit_bal, (case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as credit_balfrom Spent_Money_Transgroup by line_coa_id-- select all APunion allselect ap_account as acct_code, coa_name as acct_name, -(case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as debit_bal, -(case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as credit_balfrom Bill_Transwhere status = \"0\"-- select all ARunion allselect ar_account as acct_code, coa_name as acct_name, -(case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as debit_bal, -(case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as credit_balfrom Invoice_Transwhere status = \"0\"-- select all bill_paymentsunion allselect bank_account as acct_code, bank_name as acct_name, -(case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as debit_bal, -(case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as credit_balfrom Bill_Transwhere status = \"1\"-- select all invoice_paymentsunion allselect bank_account as acct_code, bank_name as acct_name, -(case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as debit_bal, -(case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as credit_balfrom Invoice_Transwhere status = \"1\"-- select all received_moneyunion allselect coa_id as acct_code, coa_name as acct_name, -(case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as debit_bal, -(case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as credit_balfrom Received_Money_Trans-- select all spent_moneyunion allselect coa_id as acct_code, coa_name as acct_name, -(case when sum(line_amount) < 0 then sum(line_amount) else 0 end) as debit_bal, -(case when sum(line_amount) > 0 then sum(line_amount) else 0 end) as credit_balfrom Spent_Money_Transorder by acct_code"
},
{
"code": null,
"e": 25152,
"s": 25008,
"text": "The above code contains multiple SQL queries joined by the command union all. I’ve annotated each query to show what each is trying to achieve."
},
{
"code": null,
"e": 25340,
"s": 25152,
"text": "For example, the first query tries to get all the credits for the Invoice transactions (mostly Sales). The second one for the debits of the Bill transactions (mostly Purchases) and so on."
},
{
"code": null,
"e": 25388,
"s": 25340,
"text": "Executing it should result in the following TB."
},
{
"code": null,
"e": 25527,
"s": 25388,
"text": "You can put this in Excel to check that debits equal to credits (which I did). Total debits and credits are 14115 and -14115 respectively."
},
{
"code": null,
"e": 25734,
"s": 25527,
"text": "Creating an accounting system is really complex. We essentially explored the whole gamut of database design — from concepts to ERD to creation to querying it. Pat yourself on the back for reaching this far."
},
{
"code": null,
"e": 25891,
"s": 25734,
"text": "Take note that we deliberately limited our database to focus more on the concepts. You can lift these and try to build another one without the restrictions."
},
{
"code": null,
"e": 25944,
"s": 25891,
"text": "That’s it! You’re now an SQL ninja! Congratulations!"
},
{
"code": null,
"e": 26029,
"s": 25944,
"text": "Check out my second book Accounting Database Design soon to be published on Leanpub!"
},
{
"code": null,
"e": 26097,
"s": 26029,
"text": "Check out also my first book PowerQuery Guide to Pandas on Leanpub."
}
] |
Shop Order Analysis in Python. Product analysis with the Apriori... | by Michael Whittle | Towards Data Science | The Apriori algorithm is used in data mining to identify frequent items and association rule learning in a dataset. This article will focus on one practical and common use case, the analysis of shop orders. For example, which products are ordered more frequently than others, and which unrelated products are ordered as a consequence of ordering another product. To explain this another way maybe a shopper will buy toothpaste when buying a toothbrush or maybe a shopper will buy butter when buying bread. They are not directly related but it’s not unreasonable to find an association between the two. The Apriori algorithm aids in identifying these association rules.
This article will provide a non-maths heavy walkthrough of how it works using the Python mlxtend library. For further reading I recommend Chapter 11 in “Machine Learning in Action” by “Peter Harrington”.
www.manning.com
I’m going to be using a Jupyter notebook to demonstrate this. If you don’t have Jupyter notebooks installed on your local system you can also use Google Colab which has a free cloud version.
I’m going to be using the “mlxtend” Apriori library for Python. If you don’t have it installed you can install it via the command line or via Jupiter notebooks directly.
# from the command line$ python3 -m pip install pandas mlxtend ploty matplotlib networkx# or, from Jupyter notebooks!python3 -m pip install pandas mlxtend ploty matplotlib networkx
As usual the first step in a Jupyter notebook is to load the required libraries.
import pandas as pdimport networkx as nximport plotly.express as pximport matplotlib.pyplot as pltplt.style.use('default')from mlxtend.frequent_patterns import apriorifrom mlxtend.frequent_patterns import association_rules
For the purpose of this walkthrough I’m going to be using a dataset I found on Kaggle called “Market Basket Optimization”. The dataset has a nice mix of products in orders but not presented in a clean way. I had to carry out some pre-processing to make it workable.
df_orders = pd.read_csv('Market_Basket_Optimisation.csv')df_orders.shape(7500, 20)
Our dataset has 7500 rows and 20 features.
I’m not really sure why the author of the dataset presented the data like this.
The first step is to create a negated regular expression. Replace all non-alphanumeric characters and line breaks with underscores.
df_orders = df_orders.replace(r'[^A-z0-9\n]+','_', regex=True)
Then we need to create a new feature called “combined” that has a CSV form of the columns for each row.
x = df_orders.to_string(header=False, index=False, index_names=False).split('\n')vals = [','.join(e.split()) for e in x]df_orders['combined'] = [','.join(e.split()) for e in x]
The problem now is that the NaN entries are also included like this:burgers,meatballs,eggs,NaN,NaN,NaN etc.
The way we remove these entries is using a regular expression.
df_orders_tmp = df_orders[['combined']].replace(to_replace=r',NaN.*$', value='', regex=True)
So the “combined” feature for the first row now looks like:burgers,meatballs,eggs
I also wanted to include an order number feature which just copies the index number.
df_orders_tmp['orderId'] = df_orders_tmp.index
We will now split each order into separate rows by the comma.
df_orders_tmp = df_orders_tmp.assign(combined=df_orders_tmp.combined.str.split(',')).explode('combined').reset_index(drop=True)
We now want to replace those temporary underscores above with spaces.
df_orders_tmp = df_orders_tmp.replace(r'_',' ', regex=True)
If you are wondering why this was done, there were some unexpected characters in the dataset causing problems with this “implode” process. The solution was to just replace them all with underscores, carry out the split, and put the spaces back.
We will need the quantity of each item purchased in the order. It seems straight forward as each column is one item purchased so I will reflect 1 against each row.
df_orders_tmp['itemQuantity'] = 1
Finalise our new dataframe with the columns we require with meaningful names.
df = df_orders_tmp[['orderId','combined','itemQuantity']]df.columns = ['orderId','itemDescription','itemQuantity']
And let’s take a look...
df
df_table = df.copy()df_table['all'] = 'all'fig = px.treemap(df_table.head(30), path=['all', "itemDescription"], values='itemQuantity', color=df_table["itemQuantity"].head(30), hover_data=['itemDescription'], color_continuous_scale='Blues')fig.show()
df.value_counts()
Another really nice visualisation is a network plot to visualise the top 15 products from orders.
df_network = df.copy()df_network_first = df_network.groupby("itemDescription").sum().sort_values("itemQuantity", ascending=False).reset_index()df_network_first["itemType"] = "groceries"df_network_first = df_network_first.truncate(before=-1, after=15) # top 15plt.rcParams['figure.figsize']=(20,20)first_choice = nx.from_pandas_edgelist(df_network_first, source='itemType', target="itemDescription", edge_attr=True)pos = nx.spring_layout(first_choice)nx.draw_networkx_nodes(first_choice, pos, node_size=12500, node_color="lavender")nx.draw_networkx_edges(first_choice, pos, width=3, alpha=0.6, edge_color='black')nx.draw_networkx_labels(first_choice, pos, font_size=18, font_family='sans-serif')plt.axis('off')plt.grid()plt.title('Top 15 Products', fontsize=25)plt.show()
In order to continue we’ll need to sum up multiple products within the same order.
df_grouped = df.groupby(['orderId','itemDescription']).sum()['itemQuantity']
We will now want to unstack the grouped dataframe.
df_basket = df_grouped.unstack().reset_index().fillna(0).set_index('orderId')
The values in the matrix now need to be encoded to 1’s and 0’s. The way we’ll do this is set value to 0 if the value is less than or equal to 0 and 1 if the value is greater than or equal to 1.
def encode_units(x): if x <= 0: return 0 if x >= 1: return 1basket_sets = df_basket.applymap(encode_units)basket_sets.head()
We will use the function, “apriori” from the, “mlxtend” library on, “basket_sets” to create a dataframe, “frequent_itemsets” with the support for each item. We will set the arguments for, “apriori” to “min_support = 0.05” and “use_colnames = True”.
Important terminology
Antecedent (if) is the first part of the Apriori algorithm. This item or product will be found in the dataset. We say “if” because “if” it exists then it’s likely the “Consequent” will as well, the “then”.
Consequent (then) is the second part of the Apriori algorithm. The item or product found in combination with the “Antecedent”.
Association rules are calculated from datasets (for example shop orders), which are made up of two or more items.
Support is an indication of how frequently the item appears in the dataset E.g. how popular an product is in a shop
Confidence is an indication of how often the rule has been found to be true. It indicates how reliable the rule is. E.g. how likely is it that someone would buy toothpaste when buying a toothbrush
Lift is a metric to measure the ratio of the confidence of products occurring together if they were statistically independent. E.g. how likely is another product purchased when purchasing a product, while controlling how popular the other product is. A lift score that is close to 1 indicates that the antecedent and the consequent are independent and occurrence of antecedent has no impact on occurrence of consequent. A Lift score that is greater than 1 indicates that the antecedent and consequent are dependent to each other, and the occurrence of antecedent has a positive impact on occurrence of consequent. A lift score that is smaller than 1 indicates that the antecedent and the consequent are substitute each other that means the existence of antecedent has a negative impact to consequent or visa versa.
Conviction measures the implied strength of the rule from statistical independence. Conviction score is a ratio between the probability that one product occurs without another while they were dependent and the actual probability of one products existence without another. E.g. if the (oranges) → (apples) association has a conviction score of 1.5; the rule would be incorrect 1.5 times more often (50% more often) if the association between the two were totally independent.
frequent_itemsets = apriori(basket_sets, min_support=0.05, use_colnames=True).sort_values(by=['support'], ascending=False)frequent_itemsets.head()
This is telling us that “mineral water”, “eggs”, and “spaghetti” are the most popular items in this shop. The “min_support” argument needs to be fine tuned based on your dataset. 0.05 worked well here but if you try other datasets you may need to decrease it down as far as 0.01 in some cases.
Use the function, “association_rules” from, “mlxtend” to create the dataframe from, “frequent_itemsets” using the arguments metric, “lift”.
rules = association_rules(frequent_itemsets, metric="lift")rules.head()
Just to reiterate, the “antecedent” is the product being purchased and the “consequent” is the product that is often purchased as well with their associated likelihood.
Ideally we are looking for entries where the lift and confidence are high. Something like a “lift” of ≥ 6 and a “confidence” of ≥ 0.8. Just to recap, “lift” is the ratio between the “actual confidence” and the “predicted confidence”. A lift ratio larger than 1.0 implies that the relationship between the two products is more significant than would be expected if the two sets were independent. The larger the lift ratio, the more significant the association. “confidence” is how often the rule has been found to be true. In order words, how reliable this rule is as a percentage.
What we are looking for are rules where the “lift” and “confidence” is highest. This is easily filtered in Pandas. At a minimum we want a “lift” greater than 1 but as high as possible. For the “confidence” I’ve set the rule to anything equal to or higher than 25%.
rules[ (rules['lift'] > 1) & (rules['confidence'] >= 0.25) ]
This is telling us that in this shop if someone buys “spaghetti” they are 34% likely to buy “mineral water” as well.
The Apriori algorithm can be really useful in data mining. The most common use cases are in the retail market, recommender systems, marketing campaigns, user behaviour analysis, etc.
If you enjoyed this, please follow me on Medium
Interested in collaborating? Let’s connect on LinkedIn | [
{
"code": null,
"e": 716,
"s": 47,
"text": "The Apriori algorithm is used in data mining to identify frequent items and association rule learning in a dataset. This article will focus on one practical and common use case, the analysis of shop orders. For example, which products are ordered more frequently than others, and which unrelated products are ordered as a consequence of ordering another product. To explain this another way maybe a shopper will buy toothpaste when buying a toothbrush or maybe a shopper will buy butter when buying bread. They are not directly related but it’s not unreasonable to find an association between the two. The Apriori algorithm aids in identifying these association rules."
},
{
"code": null,
"e": 920,
"s": 716,
"text": "This article will provide a non-maths heavy walkthrough of how it works using the Python mlxtend library. For further reading I recommend Chapter 11 in “Machine Learning in Action” by “Peter Harrington”."
},
{
"code": null,
"e": 936,
"s": 920,
"text": "www.manning.com"
},
{
"code": null,
"e": 1127,
"s": 936,
"text": "I’m going to be using a Jupyter notebook to demonstrate this. If you don’t have Jupyter notebooks installed on your local system you can also use Google Colab which has a free cloud version."
},
{
"code": null,
"e": 1297,
"s": 1127,
"text": "I’m going to be using the “mlxtend” Apriori library for Python. If you don’t have it installed you can install it via the command line or via Jupiter notebooks directly."
},
{
"code": null,
"e": 1478,
"s": 1297,
"text": "# from the command line$ python3 -m pip install pandas mlxtend ploty matplotlib networkx# or, from Jupyter notebooks!python3 -m pip install pandas mlxtend ploty matplotlib networkx"
},
{
"code": null,
"e": 1559,
"s": 1478,
"text": "As usual the first step in a Jupyter notebook is to load the required libraries."
},
{
"code": null,
"e": 1782,
"s": 1559,
"text": "import pandas as pdimport networkx as nximport plotly.express as pximport matplotlib.pyplot as pltplt.style.use('default')from mlxtend.frequent_patterns import apriorifrom mlxtend.frequent_patterns import association_rules"
},
{
"code": null,
"e": 2048,
"s": 1782,
"text": "For the purpose of this walkthrough I’m going to be using a dataset I found on Kaggle called “Market Basket Optimization”. The dataset has a nice mix of products in orders but not presented in a clean way. I had to carry out some pre-processing to make it workable."
},
{
"code": null,
"e": 2131,
"s": 2048,
"text": "df_orders = pd.read_csv('Market_Basket_Optimisation.csv')df_orders.shape(7500, 20)"
},
{
"code": null,
"e": 2174,
"s": 2131,
"text": "Our dataset has 7500 rows and 20 features."
},
{
"code": null,
"e": 2254,
"s": 2174,
"text": "I’m not really sure why the author of the dataset presented the data like this."
},
{
"code": null,
"e": 2386,
"s": 2254,
"text": "The first step is to create a negated regular expression. Replace all non-alphanumeric characters and line breaks with underscores."
},
{
"code": null,
"e": 2449,
"s": 2386,
"text": "df_orders = df_orders.replace(r'[^A-z0-9\\n]+','_', regex=True)"
},
{
"code": null,
"e": 2553,
"s": 2449,
"text": "Then we need to create a new feature called “combined” that has a CSV form of the columns for each row."
},
{
"code": null,
"e": 2730,
"s": 2553,
"text": "x = df_orders.to_string(header=False, index=False, index_names=False).split('\\n')vals = [','.join(e.split()) for e in x]df_orders['combined'] = [','.join(e.split()) for e in x]"
},
{
"code": null,
"e": 2838,
"s": 2730,
"text": "The problem now is that the NaN entries are also included like this:burgers,meatballs,eggs,NaN,NaN,NaN etc."
},
{
"code": null,
"e": 2901,
"s": 2838,
"text": "The way we remove these entries is using a regular expression."
},
{
"code": null,
"e": 2994,
"s": 2901,
"text": "df_orders_tmp = df_orders[['combined']].replace(to_replace=r',NaN.*$', value='', regex=True)"
},
{
"code": null,
"e": 3076,
"s": 2994,
"text": "So the “combined” feature for the first row now looks like:burgers,meatballs,eggs"
},
{
"code": null,
"e": 3161,
"s": 3076,
"text": "I also wanted to include an order number feature which just copies the index number."
},
{
"code": null,
"e": 3208,
"s": 3161,
"text": "df_orders_tmp['orderId'] = df_orders_tmp.index"
},
{
"code": null,
"e": 3270,
"s": 3208,
"text": "We will now split each order into separate rows by the comma."
},
{
"code": null,
"e": 3398,
"s": 3270,
"text": "df_orders_tmp = df_orders_tmp.assign(combined=df_orders_tmp.combined.str.split(',')).explode('combined').reset_index(drop=True)"
},
{
"code": null,
"e": 3468,
"s": 3398,
"text": "We now want to replace those temporary underscores above with spaces."
},
{
"code": null,
"e": 3528,
"s": 3468,
"text": "df_orders_tmp = df_orders_tmp.replace(r'_',' ', regex=True)"
},
{
"code": null,
"e": 3773,
"s": 3528,
"text": "If you are wondering why this was done, there were some unexpected characters in the dataset causing problems with this “implode” process. The solution was to just replace them all with underscores, carry out the split, and put the spaces back."
},
{
"code": null,
"e": 3937,
"s": 3773,
"text": "We will need the quantity of each item purchased in the order. It seems straight forward as each column is one item purchased so I will reflect 1 against each row."
},
{
"code": null,
"e": 3971,
"s": 3937,
"text": "df_orders_tmp['itemQuantity'] = 1"
},
{
"code": null,
"e": 4049,
"s": 3971,
"text": "Finalise our new dataframe with the columns we require with meaningful names."
},
{
"code": null,
"e": 4164,
"s": 4049,
"text": "df = df_orders_tmp[['orderId','combined','itemQuantity']]df.columns = ['orderId','itemDescription','itemQuantity']"
},
{
"code": null,
"e": 4189,
"s": 4164,
"text": "And let’s take a look..."
},
{
"code": null,
"e": 4192,
"s": 4189,
"text": "df"
},
{
"code": null,
"e": 4442,
"s": 4192,
"text": "df_table = df.copy()df_table['all'] = 'all'fig = px.treemap(df_table.head(30), path=['all', \"itemDescription\"], values='itemQuantity', color=df_table[\"itemQuantity\"].head(30), hover_data=['itemDescription'], color_continuous_scale='Blues')fig.show()"
},
{
"code": null,
"e": 4460,
"s": 4442,
"text": "df.value_counts()"
},
{
"code": null,
"e": 4558,
"s": 4460,
"text": "Another really nice visualisation is a network plot to visualise the top 15 products from orders."
},
{
"code": null,
"e": 5329,
"s": 4558,
"text": "df_network = df.copy()df_network_first = df_network.groupby(\"itemDescription\").sum().sort_values(\"itemQuantity\", ascending=False).reset_index()df_network_first[\"itemType\"] = \"groceries\"df_network_first = df_network_first.truncate(before=-1, after=15) # top 15plt.rcParams['figure.figsize']=(20,20)first_choice = nx.from_pandas_edgelist(df_network_first, source='itemType', target=\"itemDescription\", edge_attr=True)pos = nx.spring_layout(first_choice)nx.draw_networkx_nodes(first_choice, pos, node_size=12500, node_color=\"lavender\")nx.draw_networkx_edges(first_choice, pos, width=3, alpha=0.6, edge_color='black')nx.draw_networkx_labels(first_choice, pos, font_size=18, font_family='sans-serif')plt.axis('off')plt.grid()plt.title('Top 15 Products', fontsize=25)plt.show()"
},
{
"code": null,
"e": 5412,
"s": 5329,
"text": "In order to continue we’ll need to sum up multiple products within the same order."
},
{
"code": null,
"e": 5489,
"s": 5412,
"text": "df_grouped = df.groupby(['orderId','itemDescription']).sum()['itemQuantity']"
},
{
"code": null,
"e": 5540,
"s": 5489,
"text": "We will now want to unstack the grouped dataframe."
},
{
"code": null,
"e": 5618,
"s": 5540,
"text": "df_basket = df_grouped.unstack().reset_index().fillna(0).set_index('orderId')"
},
{
"code": null,
"e": 5812,
"s": 5618,
"text": "The values in the matrix now need to be encoded to 1’s and 0’s. The way we’ll do this is set value to 0 if the value is less than or equal to 0 and 1 if the value is greater than or equal to 1."
},
{
"code": null,
"e": 5957,
"s": 5812,
"text": "def encode_units(x): if x <= 0: return 0 if x >= 1: return 1basket_sets = df_basket.applymap(encode_units)basket_sets.head()"
},
{
"code": null,
"e": 6206,
"s": 5957,
"text": "We will use the function, “apriori” from the, “mlxtend” library on, “basket_sets” to create a dataframe, “frequent_itemsets” with the support for each item. We will set the arguments for, “apriori” to “min_support = 0.05” and “use_colnames = True”."
},
{
"code": null,
"e": 6228,
"s": 6206,
"text": "Important terminology"
},
{
"code": null,
"e": 6434,
"s": 6228,
"text": "Antecedent (if) is the first part of the Apriori algorithm. This item or product will be found in the dataset. We say “if” because “if” it exists then it’s likely the “Consequent” will as well, the “then”."
},
{
"code": null,
"e": 6561,
"s": 6434,
"text": "Consequent (then) is the second part of the Apriori algorithm. The item or product found in combination with the “Antecedent”."
},
{
"code": null,
"e": 6675,
"s": 6561,
"text": "Association rules are calculated from datasets (for example shop orders), which are made up of two or more items."
},
{
"code": null,
"e": 6791,
"s": 6675,
"text": "Support is an indication of how frequently the item appears in the dataset E.g. how popular an product is in a shop"
},
{
"code": null,
"e": 6988,
"s": 6791,
"text": "Confidence is an indication of how often the rule has been found to be true. It indicates how reliable the rule is. E.g. how likely is it that someone would buy toothpaste when buying a toothbrush"
},
{
"code": null,
"e": 7803,
"s": 6988,
"text": "Lift is a metric to measure the ratio of the confidence of products occurring together if they were statistically independent. E.g. how likely is another product purchased when purchasing a product, while controlling how popular the other product is. A lift score that is close to 1 indicates that the antecedent and the consequent are independent and occurrence of antecedent has no impact on occurrence of consequent. A Lift score that is greater than 1 indicates that the antecedent and consequent are dependent to each other, and the occurrence of antecedent has a positive impact on occurrence of consequent. A lift score that is smaller than 1 indicates that the antecedent and the consequent are substitute each other that means the existence of antecedent has a negative impact to consequent or visa versa."
},
{
"code": null,
"e": 8278,
"s": 7803,
"text": "Conviction measures the implied strength of the rule from statistical independence. Conviction score is a ratio between the probability that one product occurs without another while they were dependent and the actual probability of one products existence without another. E.g. if the (oranges) → (apples) association has a conviction score of 1.5; the rule would be incorrect 1.5 times more often (50% more often) if the association between the two were totally independent."
},
{
"code": null,
"e": 8425,
"s": 8278,
"text": "frequent_itemsets = apriori(basket_sets, min_support=0.05, use_colnames=True).sort_values(by=['support'], ascending=False)frequent_itemsets.head()"
},
{
"code": null,
"e": 8719,
"s": 8425,
"text": "This is telling us that “mineral water”, “eggs”, and “spaghetti” are the most popular items in this shop. The “min_support” argument needs to be fine tuned based on your dataset. 0.05 worked well here but if you try other datasets you may need to decrease it down as far as 0.01 in some cases."
},
{
"code": null,
"e": 8859,
"s": 8719,
"text": "Use the function, “association_rules” from, “mlxtend” to create the dataframe from, “frequent_itemsets” using the arguments metric, “lift”."
},
{
"code": null,
"e": 8931,
"s": 8859,
"text": "rules = association_rules(frequent_itemsets, metric=\"lift\")rules.head()"
},
{
"code": null,
"e": 9100,
"s": 8931,
"text": "Just to reiterate, the “antecedent” is the product being purchased and the “consequent” is the product that is often purchased as well with their associated likelihood."
},
{
"code": null,
"e": 9681,
"s": 9100,
"text": "Ideally we are looking for entries where the lift and confidence are high. Something like a “lift” of ≥ 6 and a “confidence” of ≥ 0.8. Just to recap, “lift” is the ratio between the “actual confidence” and the “predicted confidence”. A lift ratio larger than 1.0 implies that the relationship between the two products is more significant than would be expected if the two sets were independent. The larger the lift ratio, the more significant the association. “confidence” is how often the rule has been found to be true. In order words, how reliable this rule is as a percentage."
},
{
"code": null,
"e": 9946,
"s": 9681,
"text": "What we are looking for are rules where the “lift” and “confidence” is highest. This is easily filtered in Pandas. At a minimum we want a “lift” greater than 1 but as high as possible. For the “confidence” I’ve set the rule to anything equal to or higher than 25%."
},
{
"code": null,
"e": 10007,
"s": 9946,
"text": "rules[ (rules['lift'] > 1) & (rules['confidence'] >= 0.25) ]"
},
{
"code": null,
"e": 10124,
"s": 10007,
"text": "This is telling us that in this shop if someone buys “spaghetti” they are 34% likely to buy “mineral water” as well."
},
{
"code": null,
"e": 10307,
"s": 10124,
"text": "The Apriori algorithm can be really useful in data mining. The most common use cases are in the retail market, recommender systems, marketing campaigns, user behaviour analysis, etc."
},
{
"code": null,
"e": 10355,
"s": 10307,
"text": "If you enjoyed this, please follow me on Medium"
}
] |
Machine Learning with Python - Histograms | Histograms group the data in bins and is the fastest way to get idea about the distribution of each attribute in dataset. The following are some of the characteristics of histograms −
It provides us a count of the number of observations in each bin created for visualization.
It provides us a count of the number of observations in each bin created for visualization.
From the shape of the bin, we can easily observe the distribution i.e. weather it is Gaussian, skewed or exponential.
From the shape of the bin, we can easily observe the distribution i.e. weather it is Gaussian, skewed or exponential.
Histograms also help us to see possible outliers.
Histograms also help us to see possible outliers.
The code shown below is an example of Python script creating the histogram of the attributes of Pima Indian Diabetes dataset. Here, we will be using hist() function on Pandas DataFrame to generate histograms and matplotlib for ploting them.
from matplotlib import pyplot
from pandas import read_csv
path = r"C:\pima-indians-diabetes.csv"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(path, names=names)
data.hist()
pyplot.show()
The above output shows that it created the histogram for each attribute in the dataset. From this, we can observe that perhaps age, pedi and test attribute may have exponential distribution while mass and plas have Gaussian distribution.
168 Lectures
13.5 hours
Er. Himanshu Vasishta
64 Lectures
10.5 hours
Eduonix Learning Solutions
91 Lectures
10 hours
Abhilash Nelson
54 Lectures
6 hours
Abhishek And Pukhraj
49 Lectures
5 hours
Abhishek And Pukhraj
35 Lectures
4 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2488,
"s": 2304,
"text": "Histograms group the data in bins and is the fastest way to get idea about the distribution of each attribute in dataset. The following are some of the characteristics of histograms −"
},
{
"code": null,
"e": 2580,
"s": 2488,
"text": "It provides us a count of the number of observations in each bin created for visualization."
},
{
"code": null,
"e": 2672,
"s": 2580,
"text": "It provides us a count of the number of observations in each bin created for visualization."
},
{
"code": null,
"e": 2790,
"s": 2672,
"text": "From the shape of the bin, we can easily observe the distribution i.e. weather it is Gaussian, skewed or exponential."
},
{
"code": null,
"e": 2908,
"s": 2790,
"text": "From the shape of the bin, we can easily observe the distribution i.e. weather it is Gaussian, skewed or exponential."
},
{
"code": null,
"e": 2958,
"s": 2908,
"text": "Histograms also help us to see possible outliers."
},
{
"code": null,
"e": 3008,
"s": 2958,
"text": "Histograms also help us to see possible outliers."
},
{
"code": null,
"e": 3249,
"s": 3008,
"text": "The code shown below is an example of Python script creating the histogram of the attributes of Pima Indian Diabetes dataset. Here, we will be using hist() function on Pandas DataFrame to generate histograms and matplotlib for ploting them."
},
{
"code": null,
"e": 3488,
"s": 3249,
"text": "from matplotlib import pyplot\nfrom pandas import read_csv\npath = r\"C:\\pima-indians-diabetes.csv\"\nnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndata = read_csv(path, names=names)\ndata.hist()\npyplot.show()"
},
{
"code": null,
"e": 3726,
"s": 3488,
"text": "The above output shows that it created the histogram for each attribute in the dataset. From this, we can observe that perhaps age, pedi and test attribute may have exponential distribution while mass and plas have Gaussian distribution."
},
{
"code": null,
"e": 3763,
"s": 3726,
"text": "\n 168 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 3786,
"s": 3763,
"text": " Er. Himanshu Vasishta"
},
{
"code": null,
"e": 3822,
"s": 3786,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 3850,
"s": 3822,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3884,
"s": 3850,
"text": "\n 91 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3901,
"s": 3884,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3934,
"s": 3901,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3956,
"s": 3934,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 3989,
"s": 3956,
"text": "\n 49 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4011,
"s": 3989,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4044,
"s": 4011,
"text": "\n 35 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4066,
"s": 4044,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4073,
"s": 4066,
"text": " Print"
},
{
"code": null,
"e": 4084,
"s": 4073,
"text": " Add Notes"
}
] |
Python Comments | Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Comments starts with a #, and Python will
ignore them:
Comments can be placed at the end of a line, and Python will ignore the rest
of the line:
A comment does not have to be text that explains the code, it can also be used to
prevent Python from executing code:
Python does not really have a syntax for multi line comments.
To add a multiline comment you could insert a # for each line:
Or, not quite as intended, you can use a multiline string.
Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it:
As long as the string is not assigned to a variable, Python will read the code, but then ignore it, and you have made a multiline comment.
Comments in Python are written with a special character, which one?
This is a comment
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:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 45,
"s": 0,
"text": "Comments can be used to explain Python code."
},
{
"code": null,
"e": 98,
"s": 45,
"text": "Comments can be used to make the code more readable."
},
{
"code": null,
"e": 159,
"s": 98,
"text": "Comments can be used to prevent execution when testing code."
},
{
"code": null,
"e": 215,
"s": 159,
"text": "Comments starts with a #, and Python will \nignore them:"
},
{
"code": null,
"e": 306,
"s": 215,
"text": "Comments can be placed at the end of a line, and Python will ignore the rest \nof the line:"
},
{
"code": null,
"e": 425,
"s": 306,
"text": "A comment does not have to be text that explains the code, it can also be used to \nprevent Python from executing code:"
},
{
"code": null,
"e": 487,
"s": 425,
"text": "Python does not really have a syntax for multi line comments."
},
{
"code": null,
"e": 550,
"s": 487,
"text": "To add a multiline comment you could insert a # for each line:"
},
{
"code": null,
"e": 609,
"s": 550,
"text": "Or, not quite as intended, you can use a multiline string."
},
{
"code": null,
"e": 782,
"s": 609,
"text": "Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it:"
},
{
"code": null,
"e": 921,
"s": 782,
"text": "As long as the string is not assigned to a variable, Python will read the code, but then ignore it, and you have made a multiline comment."
},
{
"code": null,
"e": 989,
"s": 921,
"text": "Comments in Python are written with a special character, which one?"
},
{
"code": null,
"e": 1008,
"s": 989,
"text": "This is a comment\n"
},
{
"code": null,
"e": 1027,
"s": 1008,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1060,
"s": 1027,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1102,
"s": 1060,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1209,
"s": 1102,
"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": 1228,
"s": 1209,
"text": "[email protected]"
}
] |
C++ Program to Check whether Graph is a Bipartite using BFS | A bipartite graph is a graph in which if the graph coloring is possible using two colors i.e; vertices in a set are colored with the same color. This is a C++ program to Check whether a graph bipartite or not using BFS.
Begin
Function Bipartite():
1) Assign a color to the source vertex
2) Color all the neighbors with another color except first one color.
3) Color all neighbor’s neighbor with First color.
4) Like this way, assign color to all vertices such that it satisfies all the constraints of k way coloring problem where k = 2.
5) While assigning colors, if we find a neighbor which is colored with same color as current vertex, then the graph cannot be colored with 2 vertices i.e.; graph is not Bipartite
End
#include <iostream>
#include <queue>
#define V 5
using namespace std;
bool Bipartite(int G[][V], int s) {
int colorA[V];
for (int i = 0; i < V; ++i)
colorA[i] = -1;
colorA[s] = 1; //Assign a color to the source vertex
queue <int> q; //Create a queue of vertex numbers and enqueue source vertex for BFS traversal
q.push(s);
while (!q.empty()) {
int w = q.front(); //dequeue a vertex
q.pop();
for (int v = 0; v < V; ++v) //Find all non-colored adjacent vertices {
if (G[w][v] && colorA[v] == -1) //An edge from w to v exists and destination v is not colored {
colorA[v] = 1 - colorA[w]; //Assign alternate color to this adjacent v of w
q.push(v);
} else if (G[w][v] && colorA[v] == colorA[w]) //An edge from w to v exists and destination
//v is colored with same color as u
return false;
}
}
return true; //if all adjacent vertices can be colored with alternate color
}
int main() {
int G[][V] = {{ 0, 1, 0, 0},
{ 1, 0, 0, 0},
{ 0, 0, 0, 1},
{ 1, 0, 1, 0}};
if (Bipartite(G, 0))
cout << "The Graph is Bipartite"<<endl;
else
cout << "The Graph is Not Bipartite"<<endl;
return 0;
}
The Graph is Bipartite | [
{
"code": null,
"e": 1282,
"s": 1062,
"text": "A bipartite graph is a graph in which if the graph coloring is possible using two colors i.e; vertices in a set are colored with the same color. This is a C++ program to Check whether a graph bipartite or not using BFS."
},
{
"code": null,
"e": 1800,
"s": 1282,
"text": "Begin\n Function Bipartite():\n 1) Assign a color to the source vertex\n 2) Color all the neighbors with another color except first one color.\n 3) Color all neighbor’s neighbor with First color.\n 4) Like this way, assign color to all vertices such that it satisfies all the constraints of k way coloring problem where k = 2.\n 5) While assigning colors, if we find a neighbor which is colored with same color as current vertex, then the graph cannot be colored with 2 vertices i.e.; graph is not Bipartite\nEnd"
},
{
"code": null,
"e": 3067,
"s": 1800,
"text": "#include <iostream>\n#include <queue>\n#define V 5\nusing namespace std;\nbool Bipartite(int G[][V], int s) {\n int colorA[V];\n for (int i = 0; i < V; ++i)\n colorA[i] = -1;\n colorA[s] = 1; //Assign a color to the source vertex\n queue <int> q; //Create a queue of vertex numbers and enqueue source vertex for BFS traversal\n q.push(s);\n while (!q.empty()) {\n int w = q.front(); //dequeue a vertex\n q.pop();\n for (int v = 0; v < V; ++v) //Find all non-colored adjacent vertices {\n if (G[w][v] && colorA[v] == -1) //An edge from w to v exists and destination v is not colored {\n colorA[v] = 1 - colorA[w]; //Assign alternate color to this adjacent v of w\n q.push(v);\n } else if (G[w][v] && colorA[v] == colorA[w]) //An edge from w to v exists and destination\n //v is colored with same color as u\n return false;\n }\n }\n return true; //if all adjacent vertices can be colored with alternate color\n}\nint main() {\n int G[][V] = {{ 0, 1, 0, 0},\n { 1, 0, 0, 0},\n { 0, 0, 0, 1},\n { 1, 0, 1, 0}};\n if (Bipartite(G, 0))\n cout << \"The Graph is Bipartite\"<<endl;\n else\n cout << \"The Graph is Not Bipartite\"<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 3090,
"s": 3067,
"text": "The Graph is Bipartite"
}
] |
Introduction to ML5.js. A Beginner's Friendly Machine Learning... | by Akshay Lamba | Towards Data Science | This article is 1st part on ML5.js learning series, The complete series shall be available both on text readable forms on Medium and in video explanatory Form on my channel on YouTube. A Complete Playlist of Views are being updated.
ML5.js is a recently developed high level Library which aims to make machine learning approachable for a broad audience of artists, creative coders, and students. The Library is developed at the New York University and has been publicly released on July 2018.The library provides access to machine learning algorithms ,task and models in the browser, building on top of TensorFlow.js with no other external dependencies.So, It can be compared to Keras. ML5.js is built over TensorFlow.js and it uses the functionality of TensorFlow.js at the backend but makes life easier for people who are new to Machine Learning arena.
ML5.js is built with a Motive to simplify things out for beginners. We can compare this to Keras. The Motivation behind Keras was to make ML/DL in python so Simple that it can be used by Beginners. Similar is the case with ML5.js..
This is possible by making a wrapper around the Tensorflow.js library and use all the functionality at the backend. So Intuitively, It is an Easy to use API for TensorFlow.js.
We can use ML5.js by Referencing the latest version of it in our project, by just using a script tag in an HTML file as below:
<html> <head> <title>Getting Started</title> <script src="https://unpkg.com/[email protected]/dist/ml5.min.js"></script> </head> <body> <script> // Your code will go here </script> </body> </html>
That’s all! 💥
You are ready to go..
Pls Consider watching this Video for Detailed explanation on ML5.js :-
ML5.js supports both error-first callbacks and Promises in all methods.
ML5.js uses a pattern referred to as an error-first callback:
For example — if you are using the imageClassifier() method, you will need to construct it in the following way:
Error first callbacks is a convention common to many JavaScript libraries that is implemented in ML5.js. The language JavaScript itself does not enforce this pattern. Before implementation, we need to understand that most ML5.js methods and functions are asynchronous ( because machine learning models can take significant amounts of time to process inputs and generate outputs!).
ML5.js also supports Promises. If no callback is provided to any asynchronous function then a Promise is returned.
With Promises, the image classification example can be used in the following way:
ML5.js can use neural networks to recognize the content of images. ml5.imageClassifier() is a default method to create an object that classifies an image using a pre-trained models like MobileNet etc.
The ML5.js library accesses these model from the cloud.
Let us build a concrete example:-
We will use the p5 Library along with ML5.js. p5 is a Powerful yet simple library to use in Javascript.You can find more details here. You can always use Vanilla JavaScript or other frame works of your choice with ML5.js.
Before we start with the Javascript part,We will need to host a local server using NodeJS.
Below is the Code:-
After the Local server is Successfully up and Running, We can start off with the coding of HTML and JS files.
Index.html
main.js
That’s it..We have Successfully Implemented a Image classifier using ML5.js.
You can go to http://localhost:8081/index.html and check the results. The Screenshot is as below :-
Here is the Github Repo for the above code:-
github.com
Note : This Tutorials was not focused on UI rather it was focused basically on getting the Basics of ML5.js clear. UI can be improved and there is no limit to UI.
Using ML5.js for Image Classification is simple, In my next Article,We will Focus on Web Cam Videos Classification & other NLP jobs using ML5.js.
Pls Consider watching this Video for Detailed explanation on Image Classification using ML5.js :-
This is excellent for coders who are familiar with JavaScript & HTML and are trying to find their way in the ML/DL world!
It makes things a lot simpler for people coming from a non-ML/DL background, but who are looking to understand this field.It makes machine learning approachable for a broad audience of artists, creative coders, and students.
The use cases for this are many, and I personally think it’s something we need at the moment.
If you find my articles useful, you would also find my You Tube Channel on AI useful and interesting . Please Consider subscribing to my Channel
Enjoy AI. 😉
If you liked my article, please click the 👏 below And follow me on Medium & :
If you have any questions, please let me know in a comment below or Twitter. Subscribe to my YouTube Channel For More Tech videos : ADL . | [
{
"code": null,
"e": 404,
"s": 171,
"text": "This article is 1st part on ML5.js learning series, The complete series shall be available both on text readable forms on Medium and in video explanatory Form on my channel on YouTube. A Complete Playlist of Views are being updated."
},
{
"code": null,
"e": 1026,
"s": 404,
"text": "ML5.js is a recently developed high level Library which aims to make machine learning approachable for a broad audience of artists, creative coders, and students. The Library is developed at the New York University and has been publicly released on July 2018.The library provides access to machine learning algorithms ,task and models in the browser, building on top of TensorFlow.js with no other external dependencies.So, It can be compared to Keras. ML5.js is built over TensorFlow.js and it uses the functionality of TensorFlow.js at the backend but makes life easier for people who are new to Machine Learning arena."
},
{
"code": null,
"e": 1258,
"s": 1026,
"text": "ML5.js is built with a Motive to simplify things out for beginners. We can compare this to Keras. The Motivation behind Keras was to make ML/DL in python so Simple that it can be used by Beginners. Similar is the case with ML5.js.."
},
{
"code": null,
"e": 1434,
"s": 1258,
"text": "This is possible by making a wrapper around the Tensorflow.js library and use all the functionality at the backend. So Intuitively, It is an Easy to use API for TensorFlow.js."
},
{
"code": null,
"e": 1561,
"s": 1434,
"text": "We can use ML5.js by Referencing the latest version of it in our project, by just using a script tag in an HTML file as below:"
},
{
"code": null,
"e": 1791,
"s": 1561,
"text": " <html> <head> <title>Getting Started</title> <script src=\"https://unpkg.com/[email protected]/dist/ml5.min.js\"></script> </head> <body> <script> // Your code will go here </script> </body> </html>"
},
{
"code": null,
"e": 1805,
"s": 1791,
"text": "That’s all! 💥"
},
{
"code": null,
"e": 1827,
"s": 1805,
"text": "You are ready to go.."
},
{
"code": null,
"e": 1898,
"s": 1827,
"text": "Pls Consider watching this Video for Detailed explanation on ML5.js :-"
},
{
"code": null,
"e": 1970,
"s": 1898,
"text": "ML5.js supports both error-first callbacks and Promises in all methods."
},
{
"code": null,
"e": 2032,
"s": 1970,
"text": "ML5.js uses a pattern referred to as an error-first callback:"
},
{
"code": null,
"e": 2145,
"s": 2032,
"text": "For example — if you are using the imageClassifier() method, you will need to construct it in the following way:"
},
{
"code": null,
"e": 2526,
"s": 2145,
"text": "Error first callbacks is a convention common to many JavaScript libraries that is implemented in ML5.js. The language JavaScript itself does not enforce this pattern. Before implementation, we need to understand that most ML5.js methods and functions are asynchronous ( because machine learning models can take significant amounts of time to process inputs and generate outputs!)."
},
{
"code": null,
"e": 2641,
"s": 2526,
"text": "ML5.js also supports Promises. If no callback is provided to any asynchronous function then a Promise is returned."
},
{
"code": null,
"e": 2723,
"s": 2641,
"text": "With Promises, the image classification example can be used in the following way:"
},
{
"code": null,
"e": 2924,
"s": 2723,
"text": "ML5.js can use neural networks to recognize the content of images. ml5.imageClassifier() is a default method to create an object that classifies an image using a pre-trained models like MobileNet etc."
},
{
"code": null,
"e": 2980,
"s": 2924,
"text": "The ML5.js library accesses these model from the cloud."
},
{
"code": null,
"e": 3014,
"s": 2980,
"text": "Let us build a concrete example:-"
},
{
"code": null,
"e": 3236,
"s": 3014,
"text": "We will use the p5 Library along with ML5.js. p5 is a Powerful yet simple library to use in Javascript.You can find more details here. You can always use Vanilla JavaScript or other frame works of your choice with ML5.js."
},
{
"code": null,
"e": 3327,
"s": 3236,
"text": "Before we start with the Javascript part,We will need to host a local server using NodeJS."
},
{
"code": null,
"e": 3347,
"s": 3327,
"text": "Below is the Code:-"
},
{
"code": null,
"e": 3457,
"s": 3347,
"text": "After the Local server is Successfully up and Running, We can start off with the coding of HTML and JS files."
},
{
"code": null,
"e": 3468,
"s": 3457,
"text": "Index.html"
},
{
"code": null,
"e": 3476,
"s": 3468,
"text": "main.js"
},
{
"code": null,
"e": 3553,
"s": 3476,
"text": "That’s it..We have Successfully Implemented a Image classifier using ML5.js."
},
{
"code": null,
"e": 3653,
"s": 3553,
"text": "You can go to http://localhost:8081/index.html and check the results. The Screenshot is as below :-"
},
{
"code": null,
"e": 3698,
"s": 3653,
"text": "Here is the Github Repo for the above code:-"
},
{
"code": null,
"e": 3709,
"s": 3698,
"text": "github.com"
},
{
"code": null,
"e": 3872,
"s": 3709,
"text": "Note : This Tutorials was not focused on UI rather it was focused basically on getting the Basics of ML5.js clear. UI can be improved and there is no limit to UI."
},
{
"code": null,
"e": 4018,
"s": 3872,
"text": "Using ML5.js for Image Classification is simple, In my next Article,We will Focus on Web Cam Videos Classification & other NLP jobs using ML5.js."
},
{
"code": null,
"e": 4116,
"s": 4018,
"text": "Pls Consider watching this Video for Detailed explanation on Image Classification using ML5.js :-"
},
{
"code": null,
"e": 4238,
"s": 4116,
"text": "This is excellent for coders who are familiar with JavaScript & HTML and are trying to find their way in the ML/DL world!"
},
{
"code": null,
"e": 4463,
"s": 4238,
"text": "It makes things a lot simpler for people coming from a non-ML/DL background, but who are looking to understand this field.It makes machine learning approachable for a broad audience of artists, creative coders, and students."
},
{
"code": null,
"e": 4557,
"s": 4463,
"text": "The use cases for this are many, and I personally think it’s something we need at the moment."
},
{
"code": null,
"e": 4702,
"s": 4557,
"text": "If you find my articles useful, you would also find my You Tube Channel on AI useful and interesting . Please Consider subscribing to my Channel"
},
{
"code": null,
"e": 4714,
"s": 4702,
"text": "Enjoy AI. 😉"
},
{
"code": null,
"e": 4792,
"s": 4714,
"text": "If you liked my article, please click the 👏 below And follow me on Medium & :"
}
] |
jQuery - ajax events | Ajax requests produce a number of different events that you can subscribe to. Here's a full list of the events and in what order they are broadcast.
There are two types of events −
These are callbacks that you can subscribe to within the Ajax request object.
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......
});
These events are broadcast to all elements in the DOM, triggering any handlers which may be listening. You can listen for these events like so −
$("#loading").bind("ajaxSend", function(){
$(this).show();
}).bind("ajaxComplete", function(){
$(this).hide();
});
Global events can be disabled, for a particular Ajax request, by passing in the global option, like so −
$.ajax({
url: "test.html",
global: false,
// ...
});
Here is the full list of Ajax events. The ajaxStart and ajaxStop events are events that relate to all Ajax requests together.
ajaxStart (Global Event) This event is broadcast if an Ajax request is started and no other Ajax requests are currently running.
ajaxStart (Global Event) This event is broadcast if an Ajax request is started and no other Ajax requests are currently running.
beforeSend (Local Event) This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)
beforeSend (Local Event) This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)
ajaxSend (Global Event) This global event is also triggered before the request is run.
ajaxSend (Global Event) This global event is also triggered before the request is run.
success (Local Event) This event is only called if the request was successful (no errors from the server, no errors with the data).
success (Local Event) This event is only called if the request was successful (no errors from the server, no errors with the data).
ajaxSuccess (Global Event) This event is also only called if the request was successful.
ajaxSuccess (Global Event) This event is also only called if the request was successful.
error (Local Event) This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).
error (Local Event) This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).
ajaxError (Global Event) This global event behaves the same as the local error event.
ajaxError (Global Event) This global event behaves the same as the local error event.
complete (Local Event) This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.
complete (Local Event) This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.
ajaxComplete (Global Event) This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.
ajaxComplete (Global Event) This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.
ajaxStop (Global Event) This global event is triggered if there are no more Ajax requests being processed.
ajaxStop (Global Event) This global event is triggered if there are no more Ajax requests being processed.
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2471,
"s": 2322,
"text": "Ajax requests produce a number of different events that you can subscribe to. Here's a full list of the events and in what order they are broadcast."
},
{
"code": null,
"e": 2503,
"s": 2471,
"text": "There are two types of events −"
},
{
"code": null,
"e": 2581,
"s": 2503,
"text": "These are callbacks that you can subscribe to within the Ajax request object."
},
{
"code": null,
"e": 2741,
"s": 2581,
"text": "$.ajax({\n beforeSend: function(){\n // Handle the beforeSend event\n },\n complete: function(){\n // Handle the complete event\n }\n // ......\n});"
},
{
"code": null,
"e": 2886,
"s": 2741,
"text": "These events are broadcast to all elements in the DOM, triggering any handlers which may be listening. You can listen for these events like so −"
},
{
"code": null,
"e": 3007,
"s": 2886,
"text": "$(\"#loading\").bind(\"ajaxSend\", function(){\n $(this).show();\n}).bind(\"ajaxComplete\", function(){\n $(this).hide();\n});"
},
{
"code": null,
"e": 3112,
"s": 3007,
"text": "Global events can be disabled, for a particular Ajax request, by passing in the global option, like so −"
},
{
"code": null,
"e": 3174,
"s": 3112,
"text": "$.ajax({\n url: \"test.html\",\n global: false,\n // ...\n});"
},
{
"code": null,
"e": 3300,
"s": 3174,
"text": "Here is the full list of Ajax events. The ajaxStart and ajaxStop events are events that relate to all Ajax requests together."
},
{
"code": null,
"e": 3429,
"s": 3300,
"text": "ajaxStart (Global Event) This event is broadcast if an Ajax request is started and no other Ajax requests are currently running."
},
{
"code": null,
"e": 3558,
"s": 3429,
"text": "ajaxStart (Global Event) This event is broadcast if an Ajax request is started and no other Ajax requests are currently running."
},
{
"code": null,
"e": 3738,
"s": 3558,
"text": "beforeSend (Local Event) This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)"
},
{
"code": null,
"e": 3918,
"s": 3738,
"text": "beforeSend (Local Event) This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)"
},
{
"code": null,
"e": 4005,
"s": 3918,
"text": "ajaxSend (Global Event) This global event is also triggered before the request is run."
},
{
"code": null,
"e": 4092,
"s": 4005,
"text": "ajaxSend (Global Event) This global event is also triggered before the request is run."
},
{
"code": null,
"e": 4224,
"s": 4092,
"text": "success (Local Event) This event is only called if the request was successful (no errors from the server, no errors with the data)."
},
{
"code": null,
"e": 4356,
"s": 4224,
"text": "success (Local Event) This event is only called if the request was successful (no errors from the server, no errors with the data)."
},
{
"code": null,
"e": 4445,
"s": 4356,
"text": "ajaxSuccess (Global Event) This event is also only called if the request was successful."
},
{
"code": null,
"e": 4534,
"s": 4445,
"text": "ajaxSuccess (Global Event) This event is also only called if the request was successful."
},
{
"code": null,
"e": 4692,
"s": 4534,
"text": "error (Local Event) This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request)."
},
{
"code": null,
"e": 4850,
"s": 4692,
"text": "error (Local Event) This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request)."
},
{
"code": null,
"e": 4936,
"s": 4850,
"text": "ajaxError (Global Event) This global event behaves the same as the local error event."
},
{
"code": null,
"e": 5022,
"s": 4936,
"text": "ajaxError (Global Event) This global event behaves the same as the local error event."
},
{
"code": null,
"e": 5195,
"s": 5022,
"text": "complete (Local Event) This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests."
},
{
"code": null,
"e": 5368,
"s": 5195,
"text": "complete (Local Event) This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests."
},
{
"code": null,
"e": 5505,
"s": 5368,
"text": "ajaxComplete (Global Event) This event behaves the same as the complete event and will be triggered every time an Ajax request finishes."
},
{
"code": null,
"e": 5642,
"s": 5505,
"text": "ajaxComplete (Global Event) This event behaves the same as the complete event and will be triggered every time an Ajax request finishes."
},
{
"code": null,
"e": 5749,
"s": 5642,
"text": "ajaxStop (Global Event) This global event is triggered if there are no more Ajax requests being processed."
},
{
"code": null,
"e": 5856,
"s": 5749,
"text": "ajaxStop (Global Event) This global event is triggered if there are no more Ajax requests being processed."
},
{
"code": null,
"e": 5889,
"s": 5856,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5903,
"s": 5889,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 5938,
"s": 5903,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5952,
"s": 5938,
"text": " Pratik Singh"
},
{
"code": null,
"e": 5987,
"s": 5952,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6004,
"s": 5987,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6037,
"s": 6004,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6065,
"s": 6037,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6098,
"s": 6065,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6119,
"s": 6098,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 6151,
"s": 6119,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 6168,
"s": 6151,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 6175,
"s": 6168,
"text": " Print"
},
{
"code": null,
"e": 6186,
"s": 6175,
"text": " Add Notes"
}
] |
WebRTC - Mobile Support | In the mobile world, the WebRTC support is not on the same level as it is on desktops. Mobile devices have their own way, so WebRTC is also something different on the mobile platforms.
When developing a WebRTC application for desktop, we consider using Chrome, Firefox or Opera. All of them support WebRTC out of the box. In general, you just need a browser and not bother about the desktop's hardware.
In the mobile world there are three possible modes for WebRTC today −
The native application
The browser application
The native browser
In 2013, the Firefox web browser for Android was presented with WebRTC support out of the box. Now you can make video calls on Android devices using the Firefox mobile browser.
It has three main WebRTC components −
PeerConnection − enables calls between browsers
PeerConnection − enables calls between browsers
getUserMedia − provides access to the camera and microphone
getUserMedia − provides access to the camera and microphone
DataChannels − provides peer-to-peer data transfer
DataChannels − provides peer-to-peer data transfer
Google Chrome for Android provides WebRTC support as well. As you've already noticed, the most interesting features usually first appear in Chrome.
In the past year, the Opera mobile browser appeared with WebRTC support. So for Android you have Chrome, Firefox, and Opera. Other browsers don't support WebRTC.
Unfortunately, WebRTC is not supported on iOS now. Although WebRTC works well on Mac when using Firefox, Opera, or Chrome, it is not supported on iOS.
Nowadays, your WebRTC application won't work on Apple mobile devices out of the box. But there is a browser − Bowser. It is a web browser developed by Ericsson and it supports WebRTC out of the box. You can check its homepage at http://www.openwebrtc.org/bowser/.
Today, it is the only friendly way to support your WebRTC application on iOS. Another way is to develop a native application yourself.
Microsoft doesn't support WebRTC on mobile platforms. But they have officially confirmed that they are going to implement ORTC (Object Realtime Communications) in future versions of IE. They are not planning to support WebRTC 1.0. They labeled their ORTC as WebRTC 1.1, although it is just a community enhancement and not the official standard.
So today Window Phone users can't use WebRTC applications and there is no way to beat this situation.
WebRTC applications are not supported on Blackberry either, in any way.
The most convenient and comfortable case for users to utilize WebRTC is using the native browser of the device. In this case, the device is ready to work any additional configurations.
Today only Android devices that are version 4 or higher provide this feature. Apple still doesn't show any activity with WebRTC support. So Safari users can't use WebRTC applications. Microsoft also did not introduce it in Windows Phone 8.
This means using a third-party applications (non-native web browsers) in order to provide the WebRTC features. For now, there are two such third-party applications. Bowser, which is the only way to bring WebRTC features to the iOS device and Opera, which is a nice alternative for Android platform. The rest of the available mobile browsers don't support WebRTC.
As you can see, WebRTC does not have a large support in the mobile world yet. So, one of the possible solutions is to develop a native applications that utilize the WebRTC API. But it is not the better choice because the main WebRTC feature is a cross-platform solution. Anyway, in some cases this is the only way because a native application can utilize device-specific functions or features that are not supported by HTML5 browsers.
The first parameter of the getUserMedia API expects an object of keys and values telling the browser how to process streams. You can check the full set of constraints at https://tools.ietf.org/html/draft-alvestrand-constraints-resolution-03. You can setup video aspect ration, frameRate, and other optional parameters.
Supporting mobile devices is one of the biggest pains because mobile devices have limited screen space along with limited resources. You might want the mobile device to only capture a 480x320 resolution or smaller video stream to save power and bandwidth. Using the user agent string in the browser is a good way to test whether the user is on a mobile device or not. Let's see an example. Create the index.html file −
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8" />
</head>
<body>
<video autoplay></video>
<script src = "client.js"></script>
</body>
</html>
Then create the following client.js file −
//constraints for desktop browser
var desktopConstraints = {
video: {
mandatory: {
maxWidth:800,
maxHeight:600
}
},
audio: true
};
//constraints for mobile browser
var mobileConstraints = {
video: {
mandatory: {
maxWidth: 480,
maxHeight: 320,
}
},
audio: true
}
//if a user is using a mobile browser
if(/Android|iPhone|iPad/i.test(navigator.userAgent)) {
var constraints = mobileConstraints;
} else {
var constraints = desktopConstraints;
}
function hasUserMedia() {
//check if the browser supports the WebRTC
return !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia);
}
if (hasUserMedia()) {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
//enabling video and audio channels
navigator.getUserMedia(constraints, function (stream) {
var video = document.querySelector('video');
//inserting our stream to the video tag
video.src = window.URL.createObjectURL(stream);
}, function (err) {});
} else {
alert("WebRTC is not supported");
}
Run the web server using the static command and open the page. You should see it is 800x600. Then open this page in a mobile viewport using chrome tools and check the resolution. It should be 480x320.
Constraints are the easiest way to increase the performance of your WebRTC application.
In this chapter, we learned about the issues that can occur when developing WebRTC applications for mobile devices. We discovered different limitations of supporting the WebRTC API on mobile platforms. We also launched a demo application where we set different constraints for desktop and mobile browsers.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2072,
"s": 1887,
"text": "In the mobile world, the WebRTC support is not on the same level as it is on desktops. Mobile devices have their own way, so WebRTC is also something different on the mobile platforms."
},
{
"code": null,
"e": 2290,
"s": 2072,
"text": "When developing a WebRTC application for desktop, we consider using Chrome, Firefox or Opera. All of them support WebRTC out of the box. In general, you just need a browser and not bother about the desktop's hardware."
},
{
"code": null,
"e": 2360,
"s": 2290,
"text": "In the mobile world there are three possible modes for WebRTC today −"
},
{
"code": null,
"e": 2383,
"s": 2360,
"text": "The native application"
},
{
"code": null,
"e": 2407,
"s": 2383,
"text": "The browser application"
},
{
"code": null,
"e": 2426,
"s": 2407,
"text": "The native browser"
},
{
"code": null,
"e": 2603,
"s": 2426,
"text": "In 2013, the Firefox web browser for Android was presented with WebRTC support out of the box. Now you can make video calls on Android devices using the Firefox mobile browser."
},
{
"code": null,
"e": 2641,
"s": 2603,
"text": "It has three main WebRTC components −"
},
{
"code": null,
"e": 2689,
"s": 2641,
"text": "PeerConnection − enables calls between browsers"
},
{
"code": null,
"e": 2737,
"s": 2689,
"text": "PeerConnection − enables calls between browsers"
},
{
"code": null,
"e": 2797,
"s": 2737,
"text": "getUserMedia − provides access to the camera and microphone"
},
{
"code": null,
"e": 2857,
"s": 2797,
"text": "getUserMedia − provides access to the camera and microphone"
},
{
"code": null,
"e": 2908,
"s": 2857,
"text": "DataChannels − provides peer-to-peer data transfer"
},
{
"code": null,
"e": 2959,
"s": 2908,
"text": "DataChannels − provides peer-to-peer data transfer"
},
{
"code": null,
"e": 3107,
"s": 2959,
"text": "Google Chrome for Android provides WebRTC support as well. As you've already noticed, the most interesting features usually first appear in Chrome."
},
{
"code": null,
"e": 3269,
"s": 3107,
"text": "In the past year, the Opera mobile browser appeared with WebRTC support. So for Android you have Chrome, Firefox, and Opera. Other browsers don't support WebRTC."
},
{
"code": null,
"e": 3420,
"s": 3269,
"text": "Unfortunately, WebRTC is not supported on iOS now. Although WebRTC works well on Mac when using Firefox, Opera, or Chrome, it is not supported on iOS."
},
{
"code": null,
"e": 3684,
"s": 3420,
"text": "Nowadays, your WebRTC application won't work on Apple mobile devices out of the box. But there is a browser − Bowser. It is a web browser developed by Ericsson and it supports WebRTC out of the box. You can check its homepage at http://www.openwebrtc.org/bowser/."
},
{
"code": null,
"e": 3819,
"s": 3684,
"text": "Today, it is the only friendly way to support your WebRTC application on iOS. Another way is to develop a native application yourself."
},
{
"code": null,
"e": 4164,
"s": 3819,
"text": "Microsoft doesn't support WebRTC on mobile platforms. But they have officially confirmed that they are going to implement ORTC (Object Realtime Communications) in future versions of IE. They are not planning to support WebRTC 1.0. They labeled their ORTC as WebRTC 1.1, although it is just a community enhancement and not the official standard."
},
{
"code": null,
"e": 4266,
"s": 4164,
"text": "So today Window Phone users can't use WebRTC applications and there is no way to beat this situation."
},
{
"code": null,
"e": 4338,
"s": 4266,
"text": "WebRTC applications are not supported on Blackberry either, in any way."
},
{
"code": null,
"e": 4523,
"s": 4338,
"text": "The most convenient and comfortable case for users to utilize WebRTC is using the native browser of the device. In this case, the device is ready to work any additional configurations."
},
{
"code": null,
"e": 4763,
"s": 4523,
"text": "Today only Android devices that are version 4 or higher provide this feature. Apple still doesn't show any activity with WebRTC support. So Safari users can't use WebRTC applications. Microsoft also did not introduce it in Windows Phone 8."
},
{
"code": null,
"e": 5126,
"s": 4763,
"text": "This means using a third-party applications (non-native web browsers) in order to provide the WebRTC features. For now, there are two such third-party applications. Bowser, which is the only way to bring WebRTC features to the iOS device and Opera, which is a nice alternative for Android platform. The rest of the available mobile browsers don't support WebRTC."
},
{
"code": null,
"e": 5561,
"s": 5126,
"text": "As you can see, WebRTC does not have a large support in the mobile world yet. So, one of the possible solutions is to develop a native applications that utilize the WebRTC API. But it is not the better choice because the main WebRTC feature is a cross-platform solution. Anyway, in some cases this is the only way because a native application can utilize device-specific functions or features that are not supported by HTML5 browsers."
},
{
"code": null,
"e": 5880,
"s": 5561,
"text": "The first parameter of the getUserMedia API expects an object of keys and values telling the browser how to process streams. You can check the full set of constraints at https://tools.ietf.org/html/draft-alvestrand-constraints-resolution-03. You can setup video aspect ration, frameRate, and other optional parameters."
},
{
"code": null,
"e": 6299,
"s": 5880,
"text": "Supporting mobile devices is one of the biggest pains because mobile devices have limited screen space along with limited resources. You might want the mobile device to only capture a 480x320 resolution or smaller video stream to save power and bandwidth. Using the user agent string in the browser is a good way to test whether the user is on a mobile device or not. Let's see an example. Create the index.html file −"
},
{
"code": null,
"e": 6503,
"s": 6299,
"text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\" /> \n </head> \n\t\n <body> \n <video autoplay></video> \n <script src = \"client.js\"></script> \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 6546,
"s": 6503,
"text": "Then create the following client.js file −"
},
{
"code": null,
"e": 7785,
"s": 6546,
"text": "//constraints for desktop browser \nvar desktopConstraints = { \n\n video: { \n mandatory: { \n maxWidth:800,\n maxHeight:600 \n } \n }, \n\t\n audio: true \n}; \n \n//constraints for mobile browser \nvar mobileConstraints = { \n\n video: { \n mandatory: { \n maxWidth: 480, \n maxHeight: 320, \n } \n }, \n\t\n audio: true \n}\n \n//if a user is using a mobile browser \nif(/Android|iPhone|iPad/i.test(navigator.userAgent)) { \n var constraints = mobileConstraints; \n} else { \n var constraints = desktopConstraints; \n}\n \nfunction hasUserMedia() { \n //check if the browser supports the WebRTC \n return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || \n navigator.mozGetUserMedia); \n}\n \nif (hasUserMedia()) {\n \n navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || \n navigator.mozGetUserMedia;\n\t\n //enabling video and audio channels \n navigator.getUserMedia(constraints, function (stream) { \n var video = document.querySelector('video');\n\t\t\n //inserting our stream to the video tag \n video.src = window.URL.createObjectURL(stream);\n\t\t\n }, function (err) {}); \n} else { \n alert(\"WebRTC is not supported\"); \n}"
},
{
"code": null,
"e": 7986,
"s": 7785,
"text": "Run the web server using the static command and open the page. You should see it is 800x600. Then open this page in a mobile viewport using chrome tools and check the resolution. It should be 480x320."
},
{
"code": null,
"e": 8074,
"s": 7986,
"text": "Constraints are the easiest way to increase the performance of your WebRTC application."
},
{
"code": null,
"e": 8380,
"s": 8074,
"text": "In this chapter, we learned about the issues that can occur when developing WebRTC applications for mobile devices. We discovered different limitations of supporting the WebRTC API on mobile platforms. We also launched a demo application where we set different constraints for desktop and mobile browsers."
},
{
"code": null,
"e": 8387,
"s": 8380,
"text": " Print"
},
{
"code": null,
"e": 8398,
"s": 8387,
"text": " Add Notes"
}
] |
Fine-tuning pretrained NLP models with Huggingface’s Trainer | by Vincent Tan | Towards Data Science | Motivation: While working on a data science competition, I was fine-tuning a pre-trained model and realised how tedious it was to fine-tune a model using native PyTorch or Tensorflow. I experimented with Huggingface’s Trainer API and was surprised by how easy it was. As there are very few examples online on how to use Huggingface’s Trainer API, I hope to contribute a simple example of how Trainer could be used to fine-tune your pretrained model.
Before we start, here are some prerequisites to understand this article:
Intermediate understanding of PythonBasic understanding in training neural network modelsBasic understanding of transfer learning
Intermediate understanding of Python
Basic understanding in training neural network models
Basic understanding of transfer learning
To save your time, I will just provide you the code which can be used to train and predict your model with Trainer API. However, if you are interested in understanding how it works, feel free to read on further.
Step 1: Initialise pretrained model and tokenizer
In the code above, the data used is a IMDB movie sentiments dataset. The data allows us to train a model to detect the sentiment of the movie review- 1 being positive while 0 being negative. This is a NLP task of sequence classification, as we want to classify each review(sequence of text) into positive or negative.
There are many pretrained models which we can use to train our sentiment analysis model, let us use pretrained BERT as an example. There are many variants of pretrained BERT model, bert-base-uncased is just one of the variants. You can search for more pretrained model to use from Huggingface Models page.
model_name = "bert-base-uncased"tokenizer = BertTokenizer.from_pretrained(model_name)model = BertForSequenceClassification.from_pretrained(model_name, num_labels=2)
Since we are using a pretrained model, we need to ensure that the input data is in the same form as what the pretrained model was trained on. Thus, we would need to instantiate the tokenizer using the name of the model.
Now that the model and tokenizer have been initialised, we can proceed to preprocess the data.
Step 2: Preprocess text using pretrained tokenizer
X_train_tokenized = tokenizer(X_train, padding=True, truncation=True, max_length=512)X_val_tokenized = tokenizer(X_val, padding=True, truncation=True, max_length=512)
Let us preprocess the text using the tokenizer intialised earlier.
The input text that we are using for the tokenizer is a list of strings.
We have set padding=True, truncation=True, max_length=512 so that we can get same length inputs for the model- the long texts will be truncated to 512 tokens while the short texts will have extra tokens added to make it 512 tokens.
512 tokens is used because this is the maximum token length that the BERT model can take.
After tokenizing your text, you will get a python dictionary with 3 keys:
Input_idstoken_type_idsattention_mask
Input_ids
token_type_ids
attention_mask
Step 3: Creating a torch dataset
The Trainer API requires the model to be in a torch.utils.data.Dataset class. Hence, we would need to create a new class that inherits from the torch Dataset class.
In the inherited class, we need to have the __getitem__and __len__ method which allows Trainer to create batches of data and to obtain the length respectively.
class Dataset(torch.utils.data.Dataset): def __init__(self, encodings, labels=None): self.encodings = encodings self.labels = labels def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()} if self.labels: item["labels"] = torch.tensor(self.labels[idx]) return item def __len__(self): return len(self.encodings["input_ids"])train_dataset = Dataset(X_train_tokenized, y_train)val_dataset = Dataset(X_val_tokenized, y_val)
The purpose of setting the default labels parameter as None is so that we can reuse the class to make prediction on unseen data as these data do not have labels.
The __getitem__ method basically returns a dictionary of values for each text. By running the method, it creates a dictionary with input_ids , attention_mask and token_type_ids for each text when the data is batched during the training process.
The __len__method needs to return the length of the input data.
Step 4: Defining TrainingArguments and Trainer
def compute_metrics(p): pred, labels = p pred = np.argmax(pred, axis=1) accuracy = accuracy_score(y_true=labels, y_pred=pred) recall = recall_score(y_true=labels, y_pred=pred) precision = precision_score(y_true=labels, y_pred=pred) f1 = f1_score(y_true=labels, y_pred=pred) return {"accuracy": accuracy, "precision": precision, "recall": recall, "f1": f1} # Define Trainerargs = TrainingArguments( output_dir="output", evaluation_strategy="steps", eval_steps=500, per_device_train_batch_size=8, per_device_eval_batch_size=8, num_train_epochs=3, seed=0, load_best_model_at_end=True,)trainer = Trainer( model=model, args=args, train_dataset=train_dataset, eval_dataset=val_dataset, compute_metrics=compute_metrics, callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],) # Train pre-trained modeltrainer.train()
Here is where the magic of the Trainer function is. We can define the training parameters in the TrainingArguments and Trainer class as well as train the model with a single command.
We need to first define a function to calculate the metrics of the validation set. Since this is a binary classification problem, we can use accuracy, precision, recall and f1 score.
Next, we specify some training parameters, set the pretrained model, train data and evaluation data in the TrainingArgs and Trainer class.
After we have defined the parameters , simply run trainer.train() to train the model.
Step 5: Making prediction
# Tokenize test dataX_test_tokenized = tokenizer(X_test, padding=True, truncation=True, max_length=512) # Create torch datasettest_dataset = Dataset(X_test_tokenized) # Load trained modelmodel_path = "output/checkpoint-50000"model = BertForSequenceClassification.from_pretrained(model_path, num_labels=2) # Define test trainertest_trainer = Trainer(model) # Make predictionraw_pred, _, _ = test_trainer.predict(test_dataset) # Preprocess raw predictionsy_pred = np.argmax(raw_pred, axis=1)
After the model is trained, we repeat the same steps for the test data:
Tokenize test data with pretrained tokenizerCreate torch datasetLoad trained modelDefine Trainer
Tokenize test data with pretrained tokenizer
Create torch dataset
Load trained model
Define Trainer
To load the trained model from the previous steps, set the model_path to the path containing the trained model weights.
To make prediction, only a single command is needed as well test_trainer.predict(test_dataset) .
After making a prediction, you will only get the raw prediction. Additional preprocessing steps will be needed to get it to a usable format.
Since the task is just a simple sequence classification task, we can just obtain the argmax across axis 1. Note that other NLP tasks may require different ways to preprocess the raw predictions.
I hope this post will help to simplify your process of fine-tuning pretrained NLP models. Feel free to read more into official Huggingface documentation to understand the code better and learn about what other features it could do.
Edit 1 (23/6/21): Removed save_steps parameter from TrainingArgument as it is ignored when load_best_model_at_end is set to True. Thanks 杨程 for the feedback! | [
{
"code": null,
"e": 622,
"s": 172,
"text": "Motivation: While working on a data science competition, I was fine-tuning a pre-trained model and realised how tedious it was to fine-tune a model using native PyTorch or Tensorflow. I experimented with Huggingface’s Trainer API and was surprised by how easy it was. As there are very few examples online on how to use Huggingface’s Trainer API, I hope to contribute a simple example of how Trainer could be used to fine-tune your pretrained model."
},
{
"code": null,
"e": 695,
"s": 622,
"text": "Before we start, here are some prerequisites to understand this article:"
},
{
"code": null,
"e": 825,
"s": 695,
"text": "Intermediate understanding of PythonBasic understanding in training neural network modelsBasic understanding of transfer learning"
},
{
"code": null,
"e": 862,
"s": 825,
"text": "Intermediate understanding of Python"
},
{
"code": null,
"e": 916,
"s": 862,
"text": "Basic understanding in training neural network models"
},
{
"code": null,
"e": 957,
"s": 916,
"text": "Basic understanding of transfer learning"
},
{
"code": null,
"e": 1169,
"s": 957,
"text": "To save your time, I will just provide you the code which can be used to train and predict your model with Trainer API. However, if you are interested in understanding how it works, feel free to read on further."
},
{
"code": null,
"e": 1219,
"s": 1169,
"text": "Step 1: Initialise pretrained model and tokenizer"
},
{
"code": null,
"e": 1537,
"s": 1219,
"text": "In the code above, the data used is a IMDB movie sentiments dataset. The data allows us to train a model to detect the sentiment of the movie review- 1 being positive while 0 being negative. This is a NLP task of sequence classification, as we want to classify each review(sequence of text) into positive or negative."
},
{
"code": null,
"e": 1843,
"s": 1537,
"text": "There are many pretrained models which we can use to train our sentiment analysis model, let us use pretrained BERT as an example. There are many variants of pretrained BERT model, bert-base-uncased is just one of the variants. You can search for more pretrained model to use from Huggingface Models page."
},
{
"code": null,
"e": 2008,
"s": 1843,
"text": "model_name = \"bert-base-uncased\"tokenizer = BertTokenizer.from_pretrained(model_name)model = BertForSequenceClassification.from_pretrained(model_name, num_labels=2)"
},
{
"code": null,
"e": 2228,
"s": 2008,
"text": "Since we are using a pretrained model, we need to ensure that the input data is in the same form as what the pretrained model was trained on. Thus, we would need to instantiate the tokenizer using the name of the model."
},
{
"code": null,
"e": 2323,
"s": 2228,
"text": "Now that the model and tokenizer have been initialised, we can proceed to preprocess the data."
},
{
"code": null,
"e": 2374,
"s": 2323,
"text": "Step 2: Preprocess text using pretrained tokenizer"
},
{
"code": null,
"e": 2541,
"s": 2374,
"text": "X_train_tokenized = tokenizer(X_train, padding=True, truncation=True, max_length=512)X_val_tokenized = tokenizer(X_val, padding=True, truncation=True, max_length=512)"
},
{
"code": null,
"e": 2608,
"s": 2541,
"text": "Let us preprocess the text using the tokenizer intialised earlier."
},
{
"code": null,
"e": 2681,
"s": 2608,
"text": "The input text that we are using for the tokenizer is a list of strings."
},
{
"code": null,
"e": 2913,
"s": 2681,
"text": "We have set padding=True, truncation=True, max_length=512 so that we can get same length inputs for the model- the long texts will be truncated to 512 tokens while the short texts will have extra tokens added to make it 512 tokens."
},
{
"code": null,
"e": 3003,
"s": 2913,
"text": "512 tokens is used because this is the maximum token length that the BERT model can take."
},
{
"code": null,
"e": 3077,
"s": 3003,
"text": "After tokenizing your text, you will get a python dictionary with 3 keys:"
},
{
"code": null,
"e": 3115,
"s": 3077,
"text": "Input_idstoken_type_idsattention_mask"
},
{
"code": null,
"e": 3125,
"s": 3115,
"text": "Input_ids"
},
{
"code": null,
"e": 3140,
"s": 3125,
"text": "token_type_ids"
},
{
"code": null,
"e": 3155,
"s": 3140,
"text": "attention_mask"
},
{
"code": null,
"e": 3188,
"s": 3155,
"text": "Step 3: Creating a torch dataset"
},
{
"code": null,
"e": 3353,
"s": 3188,
"text": "The Trainer API requires the model to be in a torch.utils.data.Dataset class. Hence, we would need to create a new class that inherits from the torch Dataset class."
},
{
"code": null,
"e": 3513,
"s": 3353,
"text": "In the inherited class, we need to have the __getitem__and __len__ method which allows Trainer to create batches of data and to obtain the length respectively."
},
{
"code": null,
"e": 4071,
"s": 3513,
"text": "class Dataset(torch.utils.data.Dataset): def __init__(self, encodings, labels=None): self.encodings = encodings self.labels = labels def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()} if self.labels: item[\"labels\"] = torch.tensor(self.labels[idx]) return item def __len__(self): return len(self.encodings[\"input_ids\"])train_dataset = Dataset(X_train_tokenized, y_train)val_dataset = Dataset(X_val_tokenized, y_val)"
},
{
"code": null,
"e": 4233,
"s": 4071,
"text": "The purpose of setting the default labels parameter as None is so that we can reuse the class to make prediction on unseen data as these data do not have labels."
},
{
"code": null,
"e": 4478,
"s": 4233,
"text": "The __getitem__ method basically returns a dictionary of values for each text. By running the method, it creates a dictionary with input_ids , attention_mask and token_type_ids for each text when the data is batched during the training process."
},
{
"code": null,
"e": 4542,
"s": 4478,
"text": "The __len__method needs to return the length of the input data."
},
{
"code": null,
"e": 4589,
"s": 4542,
"text": "Step 4: Defining TrainingArguments and Trainer"
},
{
"code": null,
"e": 5473,
"s": 4589,
"text": "def compute_metrics(p): pred, labels = p pred = np.argmax(pred, axis=1) accuracy = accuracy_score(y_true=labels, y_pred=pred) recall = recall_score(y_true=labels, y_pred=pred) precision = precision_score(y_true=labels, y_pred=pred) f1 = f1_score(y_true=labels, y_pred=pred) return {\"accuracy\": accuracy, \"precision\": precision, \"recall\": recall, \"f1\": f1} # Define Trainerargs = TrainingArguments( output_dir=\"output\", evaluation_strategy=\"steps\", eval_steps=500, per_device_train_batch_size=8, per_device_eval_batch_size=8, num_train_epochs=3, seed=0, load_best_model_at_end=True,)trainer = Trainer( model=model, args=args, train_dataset=train_dataset, eval_dataset=val_dataset, compute_metrics=compute_metrics, callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],) # Train pre-trained modeltrainer.train()"
},
{
"code": null,
"e": 5656,
"s": 5473,
"text": "Here is where the magic of the Trainer function is. We can define the training parameters in the TrainingArguments and Trainer class as well as train the model with a single command."
},
{
"code": null,
"e": 5839,
"s": 5656,
"text": "We need to first define a function to calculate the metrics of the validation set. Since this is a binary classification problem, we can use accuracy, precision, recall and f1 score."
},
{
"code": null,
"e": 5978,
"s": 5839,
"text": "Next, we specify some training parameters, set the pretrained model, train data and evaluation data in the TrainingArgs and Trainer class."
},
{
"code": null,
"e": 6064,
"s": 5978,
"text": "After we have defined the parameters , simply run trainer.train() to train the model."
},
{
"code": null,
"e": 6090,
"s": 6064,
"text": "Step 5: Making prediction"
},
{
"code": null,
"e": 6580,
"s": 6090,
"text": "# Tokenize test dataX_test_tokenized = tokenizer(X_test, padding=True, truncation=True, max_length=512) # Create torch datasettest_dataset = Dataset(X_test_tokenized) # Load trained modelmodel_path = \"output/checkpoint-50000\"model = BertForSequenceClassification.from_pretrained(model_path, num_labels=2) # Define test trainertest_trainer = Trainer(model) # Make predictionraw_pred, _, _ = test_trainer.predict(test_dataset) # Preprocess raw predictionsy_pred = np.argmax(raw_pred, axis=1)"
},
{
"code": null,
"e": 6652,
"s": 6580,
"text": "After the model is trained, we repeat the same steps for the test data:"
},
{
"code": null,
"e": 6749,
"s": 6652,
"text": "Tokenize test data with pretrained tokenizerCreate torch datasetLoad trained modelDefine Trainer"
},
{
"code": null,
"e": 6794,
"s": 6749,
"text": "Tokenize test data with pretrained tokenizer"
},
{
"code": null,
"e": 6815,
"s": 6794,
"text": "Create torch dataset"
},
{
"code": null,
"e": 6834,
"s": 6815,
"text": "Load trained model"
},
{
"code": null,
"e": 6849,
"s": 6834,
"text": "Define Trainer"
},
{
"code": null,
"e": 6969,
"s": 6849,
"text": "To load the trained model from the previous steps, set the model_path to the path containing the trained model weights."
},
{
"code": null,
"e": 7066,
"s": 6969,
"text": "To make prediction, only a single command is needed as well test_trainer.predict(test_dataset) ."
},
{
"code": null,
"e": 7207,
"s": 7066,
"text": "After making a prediction, you will only get the raw prediction. Additional preprocessing steps will be needed to get it to a usable format."
},
{
"code": null,
"e": 7402,
"s": 7207,
"text": "Since the task is just a simple sequence classification task, we can just obtain the argmax across axis 1. Note that other NLP tasks may require different ways to preprocess the raw predictions."
},
{
"code": null,
"e": 7634,
"s": 7402,
"text": "I hope this post will help to simplify your process of fine-tuning pretrained NLP models. Feel free to read more into official Huggingface documentation to understand the code better and learn about what other features it could do."
}
] |
How to Create a Simple Gantt Chart Using JavaScript | by Alfrick Opidi | Towards Data Science | Use a JavaScript library to create a Gantt chart and take your project management efforts to the next level
Earlier this year, my team was looking for a project management tool that could assist us in charting the various tasks related to our app development project against some specific timelines. After doing some research, we finally settled on Gantt charts.
However, some people think Gantts are complicated to create.
Not true!
Thanks to numerous JavaScript chart libraries, data visualization is now simple, flexible, and embeddable.
In our situation, we settled on AnyChart’s JS Charts library because of its ease of use, extensive documentation, flexible code playground for trying out stuff, and other powerful features.
In this tutorial, I’ll walk you through how to create a simple interactive Gantt chart using this data visualization library.
Here’s what we’ll be making and you can get the entire code for creating such a Gantt chart at the end of the tutorial:
Let’s get our hands dirty and use the JavaScript library to create a simple Gantt chart for scheduling and monitoring project activities.
In this JS charting tutorial, we’ll follow these four steps:
Step 1: Preparing the data
Step 2: Getting dependencies
Step 3: Declaring the chart container
Step 4: Rendering the Gantt chart
The first step in building a Gantt chart using JavaScript is to prepare the data that will be displayed. The AnyChart library requires data to be represented using the tree data model.
In this model, the data is organized as a hierarchical tree-like structure in which parent-child relationships are used to connect the various data items.
As such, the parent data item will have a children data field in which the child items are stated as an array.
Let me show you an example of what I’m talking about:
var data = [{ id: "1", name: "Development Life Cycle", actualStart: Date.UTC(2018, 01, 02), actualEnd: Date.UTC(2018, 06, 15), children: [{ id: "1_1", name: "Planning", actualStart: Date.UTC(2018, 01, 02), actualEnd: Date.UTC(2018, 01, 22), connectTo: "1_2", connectorType: "finish-start", progressValue: "75%" }, // more data goes here ]}];
AnyChart utilizes a minimalist, modular-based approach that lets you get only those dependencies that are essential for your project, which greatly shrinks the size of the deployed code, leading to enhanced performance.
For creating the Gantt chart, we’ll add the following Core and Gantt modules in the <head> section of our web page.
<head><script src="https://cdn.anychart.com/releases/8.6.0/js/anychart-core.min.js"> </script> <script src ="https://cdn.anychart.com/releases/8.6.0/js/anychart-gantt.min.js"></script></head>
Then, let’s create a container where the Gantt chart will load to.
<body><div id="container"></div><body>
Notice that I’ve given the <div> element and id of “container” to be referenced in the next step.
Lastly, we’ll follow these steps to render the Gantt chart:
Create the data tree by passing the prepared data to the anychart.data.tree() method. For the second parameter, we’ll specify it as “as-tree”.
var treeData = anychart.data.tree(data, "as-tree");
Create the project Gantt chart by calling the anychart.ganttProject() chart constructor:
var chart = anychart.ganttProject();
Set the data by passing the created data tree to the chart’s data() method:
chart.data(treeData);
Configure the timeline’s scale up to the date that the project will end:
chart.getTimeline().scale().maximum(Date.UTC(2018, 06, 30));
Reference the chart container id we’d set previously:
chart.container("container");
Initiate drawing the chart:
chart.draw();
Fitt the specified activities within the width of the timeline:
chart.fitAll();
Here is the entire code I used for creating the Gantt chart on the picture above:
(You can also view the code on this CodePen repository).
<html><head><script src="https://cdn.anychart.com/releases/8.6.0/js/anychart-core.min.js"> </script> <script src ="https://cdn.anychart.com/releases/8.6.0/js/anychart-gantt.min.js"></script></head><body><div id = "container" > </div><script>anychart.onDocumentReady(function () { // create data var data = [{ id: "1", name: "Development Life Cycle", actualStart: Date.UTC(2018, 01, 02), actualEnd: Date.UTC(2018, 06, 15), children: [{ id: "1_1", name: "Planning", actualStart: Date.UTC(2018, 01, 02), actualEnd: Date.UTC(2018, 01, 22), connectTo: "1_2", connectorType: "finish-start", progressValue: "75%" }, { id: "1_2", name: "Design and Prototyping", actualStart: Date.UTC(2018, 01, 23), actualEnd: Date.UTC(2018, 02, 20), connectTo: "1_3", connectorType: "start-start", progressValue: "60%" }, { id: "1_3", name: "Evaluation Meeting", actualStart: Date.UTC(2018, 02, 23), actualEnd: Date.UTC(2018, 02, 23), connectTo: "1_4", connectorType: "start-start", progressValue: "80%" }, { id: "1_4", name: "Application Development", actualStart: Date.UTC(2018, 02, 26), actualEnd: Date.UTC(2018, 04, 26), connectTo: "1_5", connectorType: "finish-finish", progressValue: "90%" }, { id: "1_5", name: "Testing", actualStart: Date.UTC(2018, 04, 29), actualEnd: Date.UTC(2018, 05, 15), connectTo: "1_6", connectorType: "start-finish", progressValue: "60%" }, { id: "1_6", name: "Deployment", actualStart: Date.UTC(2018, 05, 20), actualEnd: Date.UTC(2018, 05, 27), connectTo: "1_7", connectorType: "start-finish", progressValue: "100%" }, { id: "1_7", name: "Maintenance", actualStart: Date.UTC(2018, 05, 30), actualEnd: Date.UTC(2018, 06, 11), progressValue: "40%" }, ] }]; // create a data tree var treeData = anychart.data.tree(data, "as-tree"); // create a chart var chart = anychart.ganttProject(); // set the data chart.data(treeData); // configure the scale chart.getTimeline().scale().maximum(Date.UTC(2018, 06, 30)); // set the container id chart.container("container"); // initiate drawing the chart chart.draw(); // fit elements to the width of the timeline chart.fitAll();});</script></body></html>
AnyChart provides a wide range of options to customize the design of data visualizations to suit your individual preferences and needs. In the data fields, you can set various attributes to customize the look and feel of your Gantt chart.
For example, here are some data fields I specified in the above Gantt chart example:
id — sets the unique identifier of every task;
name — sets the name of every task;
actualStart — sets the start date of every task;
actualEnd — sets the end date of every task;
connectTo — is a type of connector that sets the target task;
connectorType — sets the type of connector, which can be “start-start,” “start-finish,” “finish-start,” or “finish-finish”;
progressValue — sets the progress value of every task as a percentage.
Furthermore, AnyChart allows the following types of tasks, which can be visualized in different ways:
regular tasks — do not have relationships with other tasks;
parent tasks — have parent-child relationships with other tasks;
milestones — visualize events with zero duration. They can be specified by setting the same date on the actualStart and actualEnd fields.
If you want to create a chart by loading data from a relational database, you can organize the data as a table with parent/child links.
In that case, the parent field of every item should have the id value of its parent specified. Also, you should set the parent of a root item to null, or just fail to specify it.
Here is what I’m talking about:
(You can also view the code on this CodePen repository).
var data = [{ id: 1, parent: null, name: "Root", actualStart: Date.UTC(2018, 01, 02), actualEnd: Date.UTC(2018, 06, 15), }, { id: 2, parent: 1, name: "Parent 1", actualStart: Date.UTC(2018, 01, 02), actualEnd: Date.UTC(2018, 01, 22), progressValue: "90%" }, { id: 3, parent: 2, name: "Child 1–1", actualStart: Date.UTC(2018, 01, 23), actualEnd: Date.UTC(2018, 02, 20), progressValue: "75%" }, { id: 4, parent: 2, name: "Child 1–2", actualStart: Date.UTC(2018, 02, 23), actualEnd: Date.UTC(2018, 02, 23), progressValue: "60%" }, { id: 5, parent: 1, name: "Parent 2", actualStart: Date.UTC(2018, 02, 26), actualEnd: Date.UTC(2018, 04, 26), progressValue: "80%" }, { id: 7, parent: 6, name: "Child 2–1", actualStart: Date.UTC(2018, 04, 29), actualEnd: Date.UTC(2018, 05, 15), progressValue: "30%" },];
Also, when you load data as a table, don’t forget to change the second parameter in the anychart.data.tree() method from”as-tree” to “as-table”, so the whole line looks as follows:
var treeData = anychart.data.tree(data, "as-table");
Here is a screenshot of the Gantt chart created when data is loaded as a table:
That’s it!
As you can see, creating a Gantt chart using the AnyChart JavaScript charting library is simple and straightforward.
In this tutorial, I’ve just scratched the surface about what you can accomplish with Gantt charts. I hope you’ve learnt the amazing capabilities of this type of chart and how it can assist you in managing your web development tasks.
Of course, you can have a look at the easy to follow AnyChart’s Gantt chart documentation to learn more ways of tweaking the Gantt chart to fit your design requirements and assist you in tracking your project management activities.
All the best. | [
{
"code": null,
"e": 280,
"s": 172,
"text": "Use a JavaScript library to create a Gantt chart and take your project management efforts to the next level"
},
{
"code": null,
"e": 535,
"s": 280,
"text": "Earlier this year, my team was looking for a project management tool that could assist us in charting the various tasks related to our app development project against some specific timelines. After doing some research, we finally settled on Gantt charts."
},
{
"code": null,
"e": 596,
"s": 535,
"text": "However, some people think Gantts are complicated to create."
},
{
"code": null,
"e": 606,
"s": 596,
"text": "Not true!"
},
{
"code": null,
"e": 713,
"s": 606,
"text": "Thanks to numerous JavaScript chart libraries, data visualization is now simple, flexible, and embeddable."
},
{
"code": null,
"e": 903,
"s": 713,
"text": "In our situation, we settled on AnyChart’s JS Charts library because of its ease of use, extensive documentation, flexible code playground for trying out stuff, and other powerful features."
},
{
"code": null,
"e": 1029,
"s": 903,
"text": "In this tutorial, I’ll walk you through how to create a simple interactive Gantt chart using this data visualization library."
},
{
"code": null,
"e": 1149,
"s": 1029,
"text": "Here’s what we’ll be making and you can get the entire code for creating such a Gantt chart at the end of the tutorial:"
},
{
"code": null,
"e": 1287,
"s": 1149,
"text": "Let’s get our hands dirty and use the JavaScript library to create a simple Gantt chart for scheduling and monitoring project activities."
},
{
"code": null,
"e": 1348,
"s": 1287,
"text": "In this JS charting tutorial, we’ll follow these four steps:"
},
{
"code": null,
"e": 1375,
"s": 1348,
"text": "Step 1: Preparing the data"
},
{
"code": null,
"e": 1404,
"s": 1375,
"text": "Step 2: Getting dependencies"
},
{
"code": null,
"e": 1442,
"s": 1404,
"text": "Step 3: Declaring the chart container"
},
{
"code": null,
"e": 1476,
"s": 1442,
"text": "Step 4: Rendering the Gantt chart"
},
{
"code": null,
"e": 1661,
"s": 1476,
"text": "The first step in building a Gantt chart using JavaScript is to prepare the data that will be displayed. The AnyChart library requires data to be represented using the tree data model."
},
{
"code": null,
"e": 1816,
"s": 1661,
"text": "In this model, the data is organized as a hierarchical tree-like structure in which parent-child relationships are used to connect the various data items."
},
{
"code": null,
"e": 1927,
"s": 1816,
"text": "As such, the parent data item will have a children data field in which the child items are stated as an array."
},
{
"code": null,
"e": 1981,
"s": 1927,
"text": "Let me show you an example of what I’m talking about:"
},
{
"code": null,
"e": 2339,
"s": 1981,
"text": "var data = [{\tid: \"1\",\tname: \"Development Life Cycle\",\tactualStart: Date.UTC(2018, 01, 02),\tactualEnd: Date.UTC(2018, 06, 15),\tchildren: [{\t\t\tid: \"1_1\",\t\t\tname: \"Planning\",\t\t\tactualStart: Date.UTC(2018, 01, 02),\t\t\tactualEnd: Date.UTC(2018, 01, 22),\t\t\tconnectTo: \"1_2\",\t\t\tconnectorType: \"finish-start\",\t\t\tprogressValue: \"75%\"\t\t},\t\t// more data goes here\t]}];"
},
{
"code": null,
"e": 2559,
"s": 2339,
"text": "AnyChart utilizes a minimalist, modular-based approach that lets you get only those dependencies that are essential for your project, which greatly shrinks the size of the deployed code, leading to enhanced performance."
},
{
"code": null,
"e": 2675,
"s": 2559,
"text": "For creating the Gantt chart, we’ll add the following Core and Gantt modules in the <head> section of our web page."
},
{
"code": null,
"e": 2867,
"s": 2675,
"text": "<head><script src=\"https://cdn.anychart.com/releases/8.6.0/js/anychart-core.min.js\"> </script> <script src =\"https://cdn.anychart.com/releases/8.6.0/js/anychart-gantt.min.js\"></script></head>"
},
{
"code": null,
"e": 2934,
"s": 2867,
"text": "Then, let’s create a container where the Gantt chart will load to."
},
{
"code": null,
"e": 2973,
"s": 2934,
"text": "<body><div id=\"container\"></div><body>"
},
{
"code": null,
"e": 3071,
"s": 2973,
"text": "Notice that I’ve given the <div> element and id of “container” to be referenced in the next step."
},
{
"code": null,
"e": 3131,
"s": 3071,
"text": "Lastly, we’ll follow these steps to render the Gantt chart:"
},
{
"code": null,
"e": 3274,
"s": 3131,
"text": "Create the data tree by passing the prepared data to the anychart.data.tree() method. For the second parameter, we’ll specify it as “as-tree”."
},
{
"code": null,
"e": 3326,
"s": 3274,
"text": "var treeData = anychart.data.tree(data, \"as-tree\");"
},
{
"code": null,
"e": 3415,
"s": 3326,
"text": "Create the project Gantt chart by calling the anychart.ganttProject() chart constructor:"
},
{
"code": null,
"e": 3452,
"s": 3415,
"text": "var chart = anychart.ganttProject();"
},
{
"code": null,
"e": 3528,
"s": 3452,
"text": "Set the data by passing the created data tree to the chart’s data() method:"
},
{
"code": null,
"e": 3550,
"s": 3528,
"text": "chart.data(treeData);"
},
{
"code": null,
"e": 3623,
"s": 3550,
"text": "Configure the timeline’s scale up to the date that the project will end:"
},
{
"code": null,
"e": 3684,
"s": 3623,
"text": "chart.getTimeline().scale().maximum(Date.UTC(2018, 06, 30));"
},
{
"code": null,
"e": 3738,
"s": 3684,
"text": "Reference the chart container id we’d set previously:"
},
{
"code": null,
"e": 3768,
"s": 3738,
"text": "chart.container(\"container\");"
},
{
"code": null,
"e": 3796,
"s": 3768,
"text": "Initiate drawing the chart:"
},
{
"code": null,
"e": 3810,
"s": 3796,
"text": "chart.draw();"
},
{
"code": null,
"e": 3874,
"s": 3810,
"text": "Fitt the specified activities within the width of the timeline:"
},
{
"code": null,
"e": 3890,
"s": 3874,
"text": "chart.fitAll();"
},
{
"code": null,
"e": 3972,
"s": 3890,
"text": "Here is the entire code I used for creating the Gantt chart on the picture above:"
},
{
"code": null,
"e": 4029,
"s": 3972,
"text": "(You can also view the code on this CodePen repository)."
},
{
"code": null,
"e": 6303,
"s": 4029,
"text": "<html><head><script src=\"https://cdn.anychart.com/releases/8.6.0/js/anychart-core.min.js\"> </script> <script src =\"https://cdn.anychart.com/releases/8.6.0/js/anychart-gantt.min.js\"></script></head><body><div id = \"container\" > </div><script>anychart.onDocumentReady(function () {\t// create data\tvar data = [{\t\tid: \"1\",\t\tname: \"Development Life Cycle\",\t\tactualStart: Date.UTC(2018, 01, 02),\t\tactualEnd: Date.UTC(2018, 06, 15),\t\tchildren: [{\t\t\t\tid: \"1_1\",\t\t\t\tname: \"Planning\",\t\t\t\tactualStart: Date.UTC(2018, 01, 02),\t\t\t\tactualEnd: Date.UTC(2018, 01, 22),\t\t\t\tconnectTo: \"1_2\",\t\t\t\tconnectorType: \"finish-start\",\t\t\t\tprogressValue: \"75%\"\t\t\t},\t\t\t{\t\t\t\tid: \"1_2\",\t\t\t\tname: \"Design and Prototyping\",\t\t\t\tactualStart: Date.UTC(2018, 01, 23),\t\t\t\tactualEnd: Date.UTC(2018, 02, 20),\t\t\t\tconnectTo: \"1_3\",\t\t\t\tconnectorType: \"start-start\",\t\t\t\tprogressValue: \"60%\"\t\t\t},\t\t\t{\t\t\t\tid: \"1_3\",\t\t\t\tname: \"Evaluation Meeting\",\t\t\t\tactualStart: Date.UTC(2018, 02, 23),\t\t\t\tactualEnd: Date.UTC(2018, 02, 23),\t\t\t\tconnectTo: \"1_4\",\t\t\t\tconnectorType: \"start-start\",\t\t\t\tprogressValue: \"80%\"\t\t\t},\t\t\t{\t\t\t\tid: \"1_4\",\t\t\t\tname: \"Application Development\",\t\t\t\tactualStart: Date.UTC(2018, 02, 26),\t\t\t\tactualEnd: Date.UTC(2018, 04, 26),\t\t\t\tconnectTo: \"1_5\",\t\t\t\tconnectorType: \"finish-finish\",\t\t\t\tprogressValue: \"90%\"\t\t\t},\t\t\t{\t\t\t\tid: \"1_5\",\t\t\t\tname: \"Testing\",\t\t\t\tactualStart: Date.UTC(2018, 04, 29),\t\t\t\tactualEnd: Date.UTC(2018, 05, 15),\t\t\t\tconnectTo: \"1_6\",\t\t\t\tconnectorType: \"start-finish\",\t\t\t\tprogressValue: \"60%\"\t\t\t},\t\t\t{\t\t\t\tid: \"1_6\",\t\t\t\tname: \"Deployment\",\t\t\t\tactualStart: Date.UTC(2018, 05, 20),\t\t\t\tactualEnd: Date.UTC(2018, 05, 27),\t\t\t\tconnectTo: \"1_7\",\t\t\t\tconnectorType: \"start-finish\",\t\t\t\tprogressValue: \"100%\"\t\t\t},\t\t\t{\t\t\t\tid: \"1_7\",\t\t\t\tname: \"Maintenance\",\t\t\t\tactualStart: Date.UTC(2018, 05, 30),\t\t\t\tactualEnd: Date.UTC(2018, 06, 11),\t\t\t\tprogressValue: \"40%\"\t\t\t},\t\t]\t}];\t// create a data tree\tvar treeData = anychart.data.tree(data, \"as-tree\");\t// create a chart\tvar chart = anychart.ganttProject();\t// set the data\tchart.data(treeData);\t// configure the scale\tchart.getTimeline().scale().maximum(Date.UTC(2018, 06, 30));\t// set the container id\tchart.container(\"container\");\t// initiate drawing the chart\tchart.draw();\t// fit elements to the width of the timeline\tchart.fitAll();});</script></body></html>"
},
{
"code": null,
"e": 6542,
"s": 6303,
"text": "AnyChart provides a wide range of options to customize the design of data visualizations to suit your individual preferences and needs. In the data fields, you can set various attributes to customize the look and feel of your Gantt chart."
},
{
"code": null,
"e": 6627,
"s": 6542,
"text": "For example, here are some data fields I specified in the above Gantt chart example:"
},
{
"code": null,
"e": 6674,
"s": 6627,
"text": "id — sets the unique identifier of every task;"
},
{
"code": null,
"e": 6710,
"s": 6674,
"text": "name — sets the name of every task;"
},
{
"code": null,
"e": 6759,
"s": 6710,
"text": "actualStart — sets the start date of every task;"
},
{
"code": null,
"e": 6804,
"s": 6759,
"text": "actualEnd — sets the end date of every task;"
},
{
"code": null,
"e": 6866,
"s": 6804,
"text": "connectTo — is a type of connector that sets the target task;"
},
{
"code": null,
"e": 6990,
"s": 6866,
"text": "connectorType — sets the type of connector, which can be “start-start,” “start-finish,” “finish-start,” or “finish-finish”;"
},
{
"code": null,
"e": 7061,
"s": 6990,
"text": "progressValue — sets the progress value of every task as a percentage."
},
{
"code": null,
"e": 7163,
"s": 7061,
"text": "Furthermore, AnyChart allows the following types of tasks, which can be visualized in different ways:"
},
{
"code": null,
"e": 7223,
"s": 7163,
"text": "regular tasks — do not have relationships with other tasks;"
},
{
"code": null,
"e": 7288,
"s": 7223,
"text": "parent tasks — have parent-child relationships with other tasks;"
},
{
"code": null,
"e": 7426,
"s": 7288,
"text": "milestones — visualize events with zero duration. They can be specified by setting the same date on the actualStart and actualEnd fields."
},
{
"code": null,
"e": 7562,
"s": 7426,
"text": "If you want to create a chart by loading data from a relational database, you can organize the data as a table with parent/child links."
},
{
"code": null,
"e": 7741,
"s": 7562,
"text": "In that case, the parent field of every item should have the id value of its parent specified. Also, you should set the parent of a root item to null, or just fail to specify it."
},
{
"code": null,
"e": 7773,
"s": 7741,
"text": "Here is what I’m talking about:"
},
{
"code": null,
"e": 7830,
"s": 7773,
"text": "(You can also view the code on this CodePen repository)."
},
{
"code": null,
"e": 8664,
"s": 7830,
"text": "var data = [{\t\tid: 1,\t\tparent: null,\t\tname: \"Root\",\t\tactualStart: Date.UTC(2018, 01, 02),\t\tactualEnd: Date.UTC(2018, 06, 15),\t},\t{\t\tid: 2,\t\tparent: 1,\t\tname: \"Parent 1\",\t\tactualStart: Date.UTC(2018, 01, 02),\t\tactualEnd: Date.UTC(2018, 01, 22),\t\tprogressValue: \"90%\"\t},\t{\t\tid: 3,\t\tparent: 2,\t\tname: \"Child 1–1\",\t\tactualStart: Date.UTC(2018, 01, 23),\t\tactualEnd: Date.UTC(2018, 02, 20),\t\tprogressValue: \"75%\"\t},\t{\t\tid: 4,\t\tparent: 2,\t\tname: \"Child 1–2\",\t\tactualStart: Date.UTC(2018, 02, 23),\t\tactualEnd: Date.UTC(2018, 02, 23),\t\tprogressValue: \"60%\"\t},\t{\t\tid: 5,\t\tparent: 1,\t\tname: \"Parent 2\",\t\tactualStart: Date.UTC(2018, 02, 26),\t\tactualEnd: Date.UTC(2018, 04, 26),\t\tprogressValue: \"80%\"\t},\t{\t\tid: 7,\t\tparent: 6,\t\tname: \"Child 2–1\",\t\tactualStart: Date.UTC(2018, 04, 29),\t\tactualEnd: Date.UTC(2018, 05, 15),\t\tprogressValue: \"30%\"\t},];"
},
{
"code": null,
"e": 8845,
"s": 8664,
"text": "Also, when you load data as a table, don’t forget to change the second parameter in the anychart.data.tree() method from”as-tree” to “as-table”, so the whole line looks as follows:"
},
{
"code": null,
"e": 8898,
"s": 8845,
"text": "var treeData = anychart.data.tree(data, \"as-table\");"
},
{
"code": null,
"e": 8978,
"s": 8898,
"text": "Here is a screenshot of the Gantt chart created when data is loaded as a table:"
},
{
"code": null,
"e": 8989,
"s": 8978,
"text": "That’s it!"
},
{
"code": null,
"e": 9106,
"s": 8989,
"text": "As you can see, creating a Gantt chart using the AnyChart JavaScript charting library is simple and straightforward."
},
{
"code": null,
"e": 9339,
"s": 9106,
"text": "In this tutorial, I’ve just scratched the surface about what you can accomplish with Gantt charts. I hope you’ve learnt the amazing capabilities of this type of chart and how it can assist you in managing your web development tasks."
},
{
"code": null,
"e": 9571,
"s": 9339,
"text": "Of course, you can have a look at the easy to follow AnyChart’s Gantt chart documentation to learn more ways of tweaking the Gantt chart to fit your design requirements and assist you in tracking your project management activities."
}
] |
implement real time object detection | Towards Data Science | The Self-Driving car might still be having difficulties understanding the difference between humans and garbage can, but that does not take anything away from the amazing progress state-of-the-art object detection models have made in the last decade.
Combine that with the image processing abilities of libraries like OpenCV, it is much easier today to build a real-time object detection system prototype in hours. In this guide, I will try to show you how to develop sub-systems that go into a simple object detection application and how to put all of that together.
I know some of you might be thinking why I am using Python, isn't it too slow for a real-time application, and you are right; to some extent.
The most compute-heavy operations, like predictions or image processing, are being performed by PyTorch and OpenCV both of which use c++ behind the scene to implement these operations, therefore it won't make much difference if we use c++ or python for our use case here.
But again, it is just a prototype that has very little infrastructure code and overhead attached to it. If you wish to learn production-grade real-time implementation I would suggest python is not the way to go, at least not yet.
Your input video stream source can be anything, you might want to read from your webcam, or parse an already existing video, or from an external camera connected to the network. No matter what the problem is OpenCV is the solution. In this example, I will show how to read a video stream from youtube or a webcam.
For your prototype, you might not want to go out and create a new video, but use one of many available online. In such a case, you can read the video stream from youtube.
import cv2 # opencv2 package for python.import pafy # pafy allows us to read videos from youtube.URL = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" #URL to parseplay = pafy.new(self._URL).streams[-1] #'-1' means read the lowest quality of video.assert play is not None # we want to make sure their is a input to read.stream = cv2.VideoCapture(play.url) #create a opencv video stream.
Sometimes you just want to look at your own face. for such cases feel free to use the internal WebCam.
import cv2stream = cv2.VideoCapture(0) # 0 means read from local camera.
If you are building an application that will be deployed on a server your camera will have an IP address from which you can access the Video Stream.
import cv2camera_ip = "rtsp://username:password@IP/port"stream = cv2.VideoCapture(camera_ip)
Machine learning engineers today are spoiled for choice or should I say confused by choice. There are many great object detection models out there each with its pros and cons. To keep things simple we will go with YoloV5 as it provides us with fast inferences which are critical for our real-time application. You can also look into other models like FasterRCNN.
We can directly load the model from the PyTorch hub, the first time you run the code it might take few minutes as it will download the model from the internet, but next time onwards it will be loaded directly from the disk.
from torch import hub # Hub contains other models like FasterRCNNmodel = torch.hub.load( \ 'ultralytics/yolov5', \ 'yolov5s', \ pretrained=True)
As the saying goes, “journey of thousand miles, start with a single step”, so we can say “Parsing of a video stream, starts by a single frame”. So let us see how we can score and parse a single frame.
The device we use to perform the inference makes a huge difference in our inference speed, modern deep learning models work best when working with GPU’s so if you have a GPU with a CUDA kernel it will improve your performance by a huge margin. In my experience system with even a single GPU can achieve 45–60 frames per second, where a CPU might give you 25–30 frames at best.
"""The function below identifies the device which is availabe to make the prediction and uses it to load and infer the frame. Once it has results it will extract the labels and cordinates(Along with scores) for each object detected in the frame."""def score_frame(frame, model): device = 'cuda' if torch.cuda.is_available() else 'cpu' model.to(device) frame = [torch.tensor(frame)] results = self.model(frame) labels = results.xyxyn[0][:, -1].numpy() cord = results.xyxyn[0][:, :-1].numpy() return labels, cord
Once we have scored the frame, we would need to plot the identified objects along with their boxes over the frame before writing the frame into the output stream. To do this we can use OpenCV's image processing toolkit.
"""The function below takes the results and the frame as input and plots boxes over all the objects which have a score higer than our threshold."""def plot_boxes(self, results, frame): labels, cord = results n = len(labels) x_shape, y_shape = frame.shape[1], frame.shape[0] for i in range(n): row = cord[i] # If score is less than 0.2 we avoid making a prediction. if row[4] < 0.2: continue x1 = int(row[0]*x_shape) y1 = int(row[1]*y_shape) x2 = int(row[2]*x_shape) y2 = int(row[3]*y_shape) bgr = (0, 255, 0) # color of the box classes = self.model.names # Get the name of label index label_font = cv2.FONT_HERSHEY_SIMPLEX #Font for the label. cv2.rectangle(frame, \ (x1, y1), (x2, y2), \ bgr, 2) #Plot the boxes cv2.putText(frame,\ classes[labels[i]], \ (x1, y1), \ label_font, 0.9, bgr, 2) #Put a label over box. return frame
Once done this function would produce output something like this.
Sorry for the Lord of the rings reference, but yes, now we bring it all together into a single call function that performs the entire operation in a loop.
So let's go over the steps that our main function will have to perform to successfully run the application.
Create a Video Streaming Input.Load the model.While Input is available, read the next frame.Score the frame to get labels and coordinates.Plot the boxes over the objects detected.Write the processed frame onto the output video stream.
Create a Video Streaming Input.
Load the model.
While Input is available, read the next frame.
Score the frame to get labels and coordinates.
Plot the boxes over the objects detected.
Write the processed frame onto the output video stream.
Six simple steps to operate, although we will add some infrastructure code to help us make the application more robust, the basics are the same. So let's do it.
"""The Function below oracestrates the entire operation and performs the real-time parsing for video stream."""def __call__(self): player = self.get_video_stream() #Get your video stream. assert player.isOpened() # Make sure that their is a stream. #Below code creates a new video writer object to write our #output stream. x_shape = int(player.get(cv2.CAP_PROP_FRAME_WIDTH)) y_shape = int(player.get(cv2.CAP_PROP_FRAME_HEIGHT)) four_cc = cv2.VideoWriter_fourcc(*"MJPG") #Using MJPEG codex out = cv2.VideoWriter(out_file, four_cc, 20, \ (x_shape, y_shape)) ret, frame = player.read() # Read the first frame. while rect: # Run until stream is out of frames start_time = time() # We would like to measure the FPS. results = self.score_frame(frame) # Score the Frame frame = self.plot_boxes(results, frame) # Plot the boxes. end_time = time() fps = 1/np.round(end_time - start_time, 3) #Measure the FPS. print(f"Frames Per Second : {fps}") out.write(frame) # Write the frame onto the output. ret, frame = player.read() # Read next frame.
You should take all these components and pack them into a nice class which can be called along with the URL and output file you wish to write the output stream onto. Your final product will look something like this.
Of course production level real-time applications are way more complicated than this, but this guide does not intend to teach that. It is to show you the amazing power of Python which allows us to build such a complicated application prototype in hours. The possibilities from here are only limited by your imagination.
You can check the full code and more such awesome applications on my Github profile.
Leave a comment to let me know what you think.
Connect with me over Twitter, Linkedin, or Medium.
Share the article with your network. | [
{
"code": null,
"e": 423,
"s": 172,
"text": "The Self-Driving car might still be having difficulties understanding the difference between humans and garbage can, but that does not take anything away from the amazing progress state-of-the-art object detection models have made in the last decade."
},
{
"code": null,
"e": 740,
"s": 423,
"text": "Combine that with the image processing abilities of libraries like OpenCV, it is much easier today to build a real-time object detection system prototype in hours. In this guide, I will try to show you how to develop sub-systems that go into a simple object detection application and how to put all of that together."
},
{
"code": null,
"e": 882,
"s": 740,
"text": "I know some of you might be thinking why I am using Python, isn't it too slow for a real-time application, and you are right; to some extent."
},
{
"code": null,
"e": 1154,
"s": 882,
"text": "The most compute-heavy operations, like predictions or image processing, are being performed by PyTorch and OpenCV both of which use c++ behind the scene to implement these operations, therefore it won't make much difference if we use c++ or python for our use case here."
},
{
"code": null,
"e": 1384,
"s": 1154,
"text": "But again, it is just a prototype that has very little infrastructure code and overhead attached to it. If you wish to learn production-grade real-time implementation I would suggest python is not the way to go, at least not yet."
},
{
"code": null,
"e": 1698,
"s": 1384,
"text": "Your input video stream source can be anything, you might want to read from your webcam, or parse an already existing video, or from an external camera connected to the network. No matter what the problem is OpenCV is the solution. In this example, I will show how to read a video stream from youtube or a webcam."
},
{
"code": null,
"e": 1869,
"s": 1698,
"text": "For your prototype, you might not want to go out and create a new video, but use one of many available online. In such a case, you can read the video stream from youtube."
},
{
"code": null,
"e": 2254,
"s": 1869,
"text": "import cv2 # opencv2 package for python.import pafy # pafy allows us to read videos from youtube.URL = \"https://www.youtube.com/watch?v=dQw4w9WgXcQ\" #URL to parseplay = pafy.new(self._URL).streams[-1] #'-1' means read the lowest quality of video.assert play is not None # we want to make sure their is a input to read.stream = cv2.VideoCapture(play.url) #create a opencv video stream."
},
{
"code": null,
"e": 2357,
"s": 2254,
"text": "Sometimes you just want to look at your own face. for such cases feel free to use the internal WebCam."
},
{
"code": null,
"e": 2430,
"s": 2357,
"text": "import cv2stream = cv2.VideoCapture(0) # 0 means read from local camera."
},
{
"code": null,
"e": 2579,
"s": 2430,
"text": "If you are building an application that will be deployed on a server your camera will have an IP address from which you can access the Video Stream."
},
{
"code": null,
"e": 2672,
"s": 2579,
"text": "import cv2camera_ip = \"rtsp://username:password@IP/port\"stream = cv2.VideoCapture(camera_ip)"
},
{
"code": null,
"e": 3035,
"s": 2672,
"text": "Machine learning engineers today are spoiled for choice or should I say confused by choice. There are many great object detection models out there each with its pros and cons. To keep things simple we will go with YoloV5 as it provides us with fast inferences which are critical for our real-time application. You can also look into other models like FasterRCNN."
},
{
"code": null,
"e": 3259,
"s": 3035,
"text": "We can directly load the model from the PyTorch hub, the first time you run the code it might take few minutes as it will download the model from the internet, but next time onwards it will be loaded directly from the disk."
},
{
"code": null,
"e": 3467,
"s": 3259,
"text": "from torch import hub # Hub contains other models like FasterRCNNmodel = torch.hub.load( \\ 'ultralytics/yolov5', \\ 'yolov5s', \\ pretrained=True)"
},
{
"code": null,
"e": 3668,
"s": 3467,
"text": "As the saying goes, “journey of thousand miles, start with a single step”, so we can say “Parsing of a video stream, starts by a single frame”. So let us see how we can score and parse a single frame."
},
{
"code": null,
"e": 4045,
"s": 3668,
"text": "The device we use to perform the inference makes a huge difference in our inference speed, modern deep learning models work best when working with GPU’s so if you have a GPU with a CUDA kernel it will improve your performance by a huge margin. In my experience system with even a single GPU can achieve 45–60 frames per second, where a CPU might give you 25–30 frames at best."
},
{
"code": null,
"e": 4577,
"s": 4045,
"text": "\"\"\"The function below identifies the device which is availabe to make the prediction and uses it to load and infer the frame. Once it has results it will extract the labels and cordinates(Along with scores) for each object detected in the frame.\"\"\"def score_frame(frame, model): device = 'cuda' if torch.cuda.is_available() else 'cpu' model.to(device) frame = [torch.tensor(frame)] results = self.model(frame) labels = results.xyxyn[0][:, -1].numpy() cord = results.xyxyn[0][:, :-1].numpy() return labels, cord"
},
{
"code": null,
"e": 4797,
"s": 4577,
"text": "Once we have scored the frame, we would need to plot the identified objects along with their boxes over the frame before writing the frame into the output stream. To do this we can use OpenCV's image processing toolkit."
},
{
"code": null,
"e": 5840,
"s": 4797,
"text": "\"\"\"The function below takes the results and the frame as input and plots boxes over all the objects which have a score higer than our threshold.\"\"\"def plot_boxes(self, results, frame): labels, cord = results n = len(labels) x_shape, y_shape = frame.shape[1], frame.shape[0] for i in range(n): row = cord[i] # If score is less than 0.2 we avoid making a prediction. if row[4] < 0.2: continue x1 = int(row[0]*x_shape) y1 = int(row[1]*y_shape) x2 = int(row[2]*x_shape) y2 = int(row[3]*y_shape) bgr = (0, 255, 0) # color of the box classes = self.model.names # Get the name of label index label_font = cv2.FONT_HERSHEY_SIMPLEX #Font for the label. cv2.rectangle(frame, \\ (x1, y1), (x2, y2), \\ bgr, 2) #Plot the boxes cv2.putText(frame,\\ classes[labels[i]], \\ (x1, y1), \\ label_font, 0.9, bgr, 2) #Put a label over box. return frame"
},
{
"code": null,
"e": 5906,
"s": 5840,
"text": "Once done this function would produce output something like this."
},
{
"code": null,
"e": 6061,
"s": 5906,
"text": "Sorry for the Lord of the rings reference, but yes, now we bring it all together into a single call function that performs the entire operation in a loop."
},
{
"code": null,
"e": 6169,
"s": 6061,
"text": "So let's go over the steps that our main function will have to perform to successfully run the application."
},
{
"code": null,
"e": 6404,
"s": 6169,
"text": "Create a Video Streaming Input.Load the model.While Input is available, read the next frame.Score the frame to get labels and coordinates.Plot the boxes over the objects detected.Write the processed frame onto the output video stream."
},
{
"code": null,
"e": 6436,
"s": 6404,
"text": "Create a Video Streaming Input."
},
{
"code": null,
"e": 6452,
"s": 6436,
"text": "Load the model."
},
{
"code": null,
"e": 6499,
"s": 6452,
"text": "While Input is available, read the next frame."
},
{
"code": null,
"e": 6546,
"s": 6499,
"text": "Score the frame to get labels and coordinates."
},
{
"code": null,
"e": 6588,
"s": 6546,
"text": "Plot the boxes over the objects detected."
},
{
"code": null,
"e": 6644,
"s": 6588,
"text": "Write the processed frame onto the output video stream."
},
{
"code": null,
"e": 6805,
"s": 6644,
"text": "Six simple steps to operate, although we will add some infrastructure code to help us make the application more robust, the basics are the same. So let's do it."
},
{
"code": null,
"e": 7953,
"s": 6805,
"text": "\"\"\"The Function below oracestrates the entire operation and performs the real-time parsing for video stream.\"\"\"def __call__(self): player = self.get_video_stream() #Get your video stream. assert player.isOpened() # Make sure that their is a stream. #Below code creates a new video writer object to write our #output stream. x_shape = int(player.get(cv2.CAP_PROP_FRAME_WIDTH)) y_shape = int(player.get(cv2.CAP_PROP_FRAME_HEIGHT)) four_cc = cv2.VideoWriter_fourcc(*\"MJPG\") #Using MJPEG codex out = cv2.VideoWriter(out_file, four_cc, 20, \\ (x_shape, y_shape)) ret, frame = player.read() # Read the first frame. while rect: # Run until stream is out of frames start_time = time() # We would like to measure the FPS. results = self.score_frame(frame) # Score the Frame frame = self.plot_boxes(results, frame) # Plot the boxes. end_time = time() fps = 1/np.round(end_time - start_time, 3) #Measure the FPS. print(f\"Frames Per Second : {fps}\") out.write(frame) # Write the frame onto the output. ret, frame = player.read() # Read next frame."
},
{
"code": null,
"e": 8169,
"s": 7953,
"text": "You should take all these components and pack them into a nice class which can be called along with the URL and output file you wish to write the output stream onto. Your final product will look something like this."
},
{
"code": null,
"e": 8489,
"s": 8169,
"text": "Of course production level real-time applications are way more complicated than this, but this guide does not intend to teach that. It is to show you the amazing power of Python which allows us to build such a complicated application prototype in hours. The possibilities from here are only limited by your imagination."
},
{
"code": null,
"e": 8574,
"s": 8489,
"text": "You can check the full code and more such awesome applications on my Github profile."
},
{
"code": null,
"e": 8621,
"s": 8574,
"text": "Leave a comment to let me know what you think."
},
{
"code": null,
"e": 8672,
"s": 8621,
"text": "Connect with me over Twitter, Linkedin, or Medium."
}
] |
Generate a list of Primes less than n in Python | Suppose we have a number n, we have to generate a list of all prime numbers smaller than or
equal to n in ascending order. We have to keep in mind that 1 is not a prime number.
So, if the input is like 12, then the output will be [2, 3, 5, 7, 11].
To solve this, we will follow these steps −
sieve := a list of size n+1 and fill with True
primes := a new list, initially blank
for i in range 2 to n, doif sieve[i] is True, theninsert i at the end of primesfor j in range i to n, update in each step by i, dosieve[j] := False
if sieve[i] is True, theninsert i at the end of primesfor j in range i to n, update in each step by i, dosieve[j] := False
insert i at the end of primes
for j in range i to n, update in each step by i, dosieve[j] := False
sieve[j] := False
return primes
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, n):
sieve = [True] * (n + 1)
primes = []
for i in range(2, n + 1):
if sieve[i]:
primes.append(i)
for j in range(i, n + 1, i):
sieve[j] = False
return primes
ob = Solution()
print(ob.solve(12))
12
[2, 3, 5, 7, 11] | [
{
"code": null,
"e": 1239,
"s": 1062,
"text": "Suppose we have a number n, we have to generate a list of all prime numbers smaller than or\nequal to n in ascending order. We have to keep in mind that 1 is not a prime number."
},
{
"code": null,
"e": 1310,
"s": 1239,
"text": "So, if the input is like 12, then the output will be [2, 3, 5, 7, 11]."
},
{
"code": null,
"e": 1354,
"s": 1310,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1401,
"s": 1354,
"text": "sieve := a list of size n+1 and fill with True"
},
{
"code": null,
"e": 1439,
"s": 1401,
"text": "primes := a new list, initially blank"
},
{
"code": null,
"e": 1587,
"s": 1439,
"text": "for i in range 2 to n, doif sieve[i] is True, theninsert i at the end of primesfor j in range i to n, update in each step by i, dosieve[j] := False"
},
{
"code": null,
"e": 1710,
"s": 1587,
"text": "if sieve[i] is True, theninsert i at the end of primesfor j in range i to n, update in each step by i, dosieve[j] := False"
},
{
"code": null,
"e": 1740,
"s": 1710,
"text": "insert i at the end of primes"
},
{
"code": null,
"e": 1809,
"s": 1740,
"text": "for j in range i to n, update in each step by i, dosieve[j] := False"
},
{
"code": null,
"e": 1827,
"s": 1809,
"text": "sieve[j] := False"
},
{
"code": null,
"e": 1841,
"s": 1827,
"text": "return primes"
},
{
"code": null,
"e": 1911,
"s": 1841,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1922,
"s": 1911,
"text": " Live Demo"
},
{
"code": null,
"e": 2222,
"s": 1922,
"text": "class Solution:\n def solve(self, n):\n sieve = [True] * (n + 1)\n primes = []\n for i in range(2, n + 1):\n if sieve[i]:\n primes.append(i)\n for j in range(i, n + 1, i):\n sieve[j] = False\n return primes\nob = Solution()\nprint(ob.solve(12))"
},
{
"code": null,
"e": 2225,
"s": 2222,
"text": "12"
},
{
"code": null,
"e": 2242,
"s": 2225,
"text": "[2, 3, 5, 7, 11]"
}
] |
How to get the current GPS location programmatically on Android using Kotlin? | This example demonstrates how to get the current GPS location programmatically on 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"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Current GPS Location"
android:textColor="@color/colorPrimary"
android:textSize="24sp"
android:textStyle="bold" />
<Button
android:id="@+id/getLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/text"
android:layout_centerInParent="true"
android:layout_marginTop="40dp"
android:text="Get location" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class MainActivity : AppCompatActivity(), LocationListener {
private lateinit var locationManager: LocationManager
private lateinit var tvGpsLocation: TextView
private val locationPermissionCode = 2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val button: Button = findViewById(R.id.getLocation)
button.setOnClickListener {
getLocation()
}
}
private fun getLocation() {
locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), locationPermissionCode)
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5f, this)
}
override fun onLocationChanged(location: Location) {
tvGpsLocation = findViewById(R.id.textView)
tvGpsLocation.text = "Latitude: " + location.latitude + " , Longitude: " + location.longitude
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == locationPermissionCode) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show()
}
else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
}
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<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.
Click here to download the project code. | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "This example demonstrates how to get the current GPS location programmatically on Android using Kotlin."
},
{
"code": null,
"e": 1295,
"s": 1166,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1360,
"s": 1295,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2675,
"s": 1360,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Current GPS Location\"\n android:textColor=\"@color/colorPrimary\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n<Button\n android:id=\"@+id/getLocation\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/text\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"40dp\"\n android:text=\"Get location\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2730,
"s": 2675,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 4863,
"s": 2730,
"text": "import android.Manifest\nimport android.content.Context\nimport android.content.pm.PackageManager\nimport android.location.Location\nimport android.location.LocationListener\nimport android.location.LocationManager\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.TextView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.core.app.ActivityCompat\nimport androidx.core.content.ContextCompat\nclass MainActivity : AppCompatActivity(), LocationListener {\n private lateinit var locationManager: LocationManager\n private lateinit var tvGpsLocation: TextView\n private val locationPermissionCode = 2\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val button: Button = findViewById(R.id.getLocation)\n button.setOnClickListener {\n getLocation()\n }\n }\n private fun getLocation() {\n locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager\n if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {\n ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), locationPermissionCode)\n }\n locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5f, this)\n }\n override fun onLocationChanged(location: Location) {\n tvGpsLocation = findViewById(R.id.textView)\n tvGpsLocation.text = \"Latitude: \" + location.latitude + \" , Longitude: \" + location.longitude\n }\n override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {\n if (requestCode == locationPermissionCode) {\n if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n Toast.makeText(this, \"Permission Granted\", Toast.LENGTH_SHORT).show()\n }\n else {\n Toast.makeText(this, \"Permission Denied\", Toast.LENGTH_SHORT).show()\n }\n }\n }\n}\n"
},
{
"code": null,
"e": 4918,
"s": 4863,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5741,
"s": 4918,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n<uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\" />\n<uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" />\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": 6091,
"s": 5741,
"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."
},
{
"code": null,
"e": 6132,
"s": 6091,
"text": "Click here to download the project code."
}
] |
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks | 19 Nov, 2018
For computers based on three-address instruction formats, each address field can be used to specify which of the following:
S1: A memory operand
S2: A processor register
S3: An implied accumulator register
(A) Either S1 or S2(B) Either S2 or S3(C) Only S2 and S3(D) All of S1, S2 and S3Answer: (A)Explanation: In Three address instruction format, each operand specifies either a memory address or a register. See
http://homepage.cs.uiowa.edu/~ghosh/1-19-06.pdfQuiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
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-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25695,
"s": 25667,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 25819,
"s": 25695,
"text": "For computers based on three-address instruction formats, each address field can be used to specify which of the following:"
},
{
"code": null,
"e": 25901,
"s": 25819,
"text": "S1: A memory operand\nS2: A processor register\nS3: An implied accumulator register"
},
{
"code": null,
"e": 26108,
"s": 25901,
"text": "(A) Either S1 or S2(B) Either S2 or S3(C) Only S2 and S3(D) All of S1, S2 and S3Answer: (A)Explanation: In Three address instruction format, each operand specifies either a memory address or a register. See"
},
{
"code": null,
"e": 26177,
"s": 26108,
"text": "http://homepage.cs.uiowa.edu/~ghosh/1-19-06.pdfQuiz of this Question"
},
{
"code": null,
"e": 26198,
"s": 26177,
"text": "GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 26224,
"s": 26198,
"text": "GATE-GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 26229,
"s": 26224,
"text": "GATE"
},
{
"code": null,
"e": 26327,
"s": 26229,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26361,
"s": 26327,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26395,
"s": 26361,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26429,
"s": 26395,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26462,
"s": 26429,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26498,
"s": 26462,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26532,
"s": 26498,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26568,
"s": 26532,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26602,
"s": 26568,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26636,
"s": 26602,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
__getitem__ and __setitem__ in Python - GeeksforGeeks | 23 Mar, 2020
Dunder methods are double underscored methods that are used to emulate the behavior of built-in types. They are predefined methods that simplify many operations that can be performed on a class instance, like __init__(), __str__(), __call__() etc. These methods are very helpful because they are used in binary operations, assignment operations, unary and binary comparison operations.
Note: For more information, refer to Dunder or magic methods in Python
There are getter and setter methods as a part of these magical methods. They are implemented by __getitem__() and __setitem__() methods. But, these methods are used only in indexed attributes like arrays, dictionaries, lists e.t.c. Instead of directly accessing and manipulating class attributes, it provides such methods, so these attributes can be modified only by its own instances and thus implements abstraction.
Instead of making class attributes as public, these methods make them private, provide validation that only correct values are set to the attributes and the only correct caller has access to these attributes.
Let’s take the example of a bank record of a person. It contains balance, transaction history, and other confidential records as part of it. Now, this bank record needs to be handled as a built-in data type to facilitate many operations. There are several methods which need access for balance and transaction history. If they directly modify the balance, they might end up inserting null values, or negative values that are very vulnerable. So, the __getitem__() and __setitem__() helps in presenting the details securely.
Example:
class bank_record: def __init__(self, name): self.record = { "name": name, "balance": 100, "transaction":[100] } def __getitem__(self, key): return self.record[key] def __setitem__(self, key, newvalue): if key =="balance" and newvalue != None and newvalue>= 100: self.record[key] += newvalue elif key =="transaction" and newvalue != None: self.record[key].append(newvalue) def getBalance(self): return self.__getitem__("balance") def updateBalance(self, new_balance): self.__setitem__("balance", new_balance) self.__setitem__("transaction", new_balance) def getTransactions(self): return self.__getitem__("transaction") def numTransactions(self): return len(self.record["transaction"]) sam = bank_record("Sam")print("The balance is : "+str(sam.getBalance())) sam.updateBalance(200)print("The new balance is : "+str(sam.getBalance()))print("The no. of transactions are: "+str(sam.numTransactions())) sam.updateBalance(300)print("The new balance is : "+str(sam.getBalance()))print("The no. of transactions are: "+str(sam.numTransactions()))print("The transaction history is: "+ str(sam.getTransactions()))
Output
The balance is : 100
The new balance is : 300
The no. of transactions are: 2
The new balance is : 600
The no. of transactions are: 3
The transaction history is: [100, 200, 300]
Here you can see, how easy to implement numTransactions(), getTransactions(), getBalance(), setBalance(), just by implementing __getitem__() and __setitem__() methods. Also, it takes care of validation of balance and transaction history.
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24352,
"s": 24324,
"text": "\n23 Mar, 2020"
},
{
"code": null,
"e": 24738,
"s": 24352,
"text": "Dunder methods are double underscored methods that are used to emulate the behavior of built-in types. They are predefined methods that simplify many operations that can be performed on a class instance, like __init__(), __str__(), __call__() etc. These methods are very helpful because they are used in binary operations, assignment operations, unary and binary comparison operations."
},
{
"code": null,
"e": 24809,
"s": 24738,
"text": "Note: For more information, refer to Dunder or magic methods in Python"
},
{
"code": null,
"e": 25227,
"s": 24809,
"text": "There are getter and setter methods as a part of these magical methods. They are implemented by __getitem__() and __setitem__() methods. But, these methods are used only in indexed attributes like arrays, dictionaries, lists e.t.c. Instead of directly accessing and manipulating class attributes, it provides such methods, so these attributes can be modified only by its own instances and thus implements abstraction."
},
{
"code": null,
"e": 25436,
"s": 25227,
"text": "Instead of making class attributes as public, these methods make them private, provide validation that only correct values are set to the attributes and the only correct caller has access to these attributes."
},
{
"code": null,
"e": 25960,
"s": 25436,
"text": "Let’s take the example of a bank record of a person. It contains balance, transaction history, and other confidential records as part of it. Now, this bank record needs to be handled as a built-in data type to facilitate many operations. There are several methods which need access for balance and transaction history. If they directly modify the balance, they might end up inserting null values, or negative values that are very vulnerable. So, the __getitem__() and __setitem__() helps in presenting the details securely."
},
{
"code": null,
"e": 25969,
"s": 25960,
"text": "Example:"
},
{
"code": "class bank_record: def __init__(self, name): self.record = { \"name\": name, \"balance\": 100, \"transaction\":[100] } def __getitem__(self, key): return self.record[key] def __setitem__(self, key, newvalue): if key ==\"balance\" and newvalue != None and newvalue>= 100: self.record[key] += newvalue elif key ==\"transaction\" and newvalue != None: self.record[key].append(newvalue) def getBalance(self): return self.__getitem__(\"balance\") def updateBalance(self, new_balance): self.__setitem__(\"balance\", new_balance) self.__setitem__(\"transaction\", new_balance) def getTransactions(self): return self.__getitem__(\"transaction\") def numTransactions(self): return len(self.record[\"transaction\"]) sam = bank_record(\"Sam\")print(\"The balance is : \"+str(sam.getBalance())) sam.updateBalance(200)print(\"The new balance is : \"+str(sam.getBalance()))print(\"The no. of transactions are: \"+str(sam.numTransactions())) sam.updateBalance(300)print(\"The new balance is : \"+str(sam.getBalance()))print(\"The no. of transactions are: \"+str(sam.numTransactions()))print(\"The transaction history is: \"+ str(sam.getTransactions()))",
"e": 27358,
"s": 25969,
"text": null
},
{
"code": null,
"e": 27365,
"s": 27358,
"text": "Output"
},
{
"code": null,
"e": 27542,
"s": 27365,
"text": "The balance is : 100\nThe new balance is : 300\nThe no. of transactions are: 2\nThe new balance is : 600\nThe no. of transactions are: 3\nThe transaction history is: [100, 200, 300]"
},
{
"code": null,
"e": 27780,
"s": 27542,
"text": "Here you can see, how easy to implement numTransactions(), getTransactions(), getBalance(), setBalance(), just by implementing __getitem__() and __setitem__() methods. Also, it takes care of validation of balance and transaction history."
},
{
"code": null,
"e": 27800,
"s": 27780,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 27807,
"s": 27800,
"text": "Python"
},
{
"code": null,
"e": 27905,
"s": 27807,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27914,
"s": 27905,
"text": "Comments"
},
{
"code": null,
"e": 27927,
"s": 27914,
"text": "Old Comments"
},
{
"code": null,
"e": 27945,
"s": 27927,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27980,
"s": 27945,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28002,
"s": 27980,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28032,
"s": 28002,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28064,
"s": 28032,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28106,
"s": 28064,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28132,
"s": 28106,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28169,
"s": 28132,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28212,
"s": 28169,
"text": "Python program to convert a list to string"
}
] |
Reverse alternate K nodes in a Singly Linked List - Iterative Solution - GeeksforGeeks | 11 Nov, 2021
Given a linked list and an integer K, the task is to reverse every alternate K nodes.Examples:
Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> NULL, K = 3 Output: 3 2 1 4 5 6 9 8 7Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> NULL, K = 5 Output: 5 4 3 2 1 6 7 8 9
Approach: We have already discussed a recursive solution here. In this post, we will discuss an iterative solution to the above problem. While traversing we process 2k nodes in one iteration and keep track of the first and last node of the group of k-nodes in the given linked list using the join and tail pointer. After reversing the k nodes of the linked list, we join the last node of the reversed list, pointed by the tail pointer, with the first node of the original list, pointed by the join pointer. We then move the current pointer until we skip the next k nodes. The tail now becomes the last node of the normal list (which is pointed by the updated tail pointer) and join points to the first of the reversed list and they are then joined. We repeat this process until all the nodes are processed in the same way.Below is the implementation of the above approach:
C++
Java
Python
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Link list nodeclass Node {public: int data; Node* next;}; /* Function to reverse alternate k nodes andreturn the pointer to the new head node */Node* kAltReverse(struct Node* head, int k){ Node* prev = NULL; Node* curr = head; Node* temp = NULL; Node* tail = NULL; Node* newHead = NULL; Node* join = NULL; int t = 0; // Traverse till the end of the linked list while (curr) { t = k; join = curr; prev = NULL; /* Reverse alternative group of k nodes // of the given linked list */ while (curr && t--) { temp = curr->next; curr->next = prev; prev = curr; curr = temp; } // Sets the new head of the input list if (!newHead) newHead = prev; /* Tail pointer keeps track of the last node of the k-reversed linked list. The tail pointer is then joined with the first node of the next k-nodes of the linked list */ if (tail) tail->next = prev; tail = join; tail->next = curr; t = k; /* Traverse through the next k nodes which will not be reversed */ while (curr && t--) { prev = curr; curr = curr->next; } /* Tail pointer keeps track of the last node of the k nodes traversed above */ tail = prev; } // newHead is new head of the modified list return newHead;} // Function to insert a node at// the head of the linked listvoid push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Function to print the linked listvoid printList(Node* node){ int count = 0; while (node != NULL) { cout << node->data << " "; node = node->next; count++; }} // Driver codeint main(void){ // Start with the empty list Node* head = NULL; int i; // Create a list 1->2->3->4->...->10 for (i = 10; i > 0; i--) push(&head, i); int k = 3; cout << "Given linked list \n"; printList(head); head = kAltReverse(head, k); cout << "\n Modified Linked list \n"; printList(head); return (0);}
// Java implementation of the approachclass GFG{ // Link list nodestatic class Node{ int data; Node next;};static Node head; /* Function to reverse alternate k nodes andreturn the pointer to the new head node */static Node kAltReverse(Node head, int k){ Node prev = null; Node curr = head; Node temp = null; Node tail = null; Node newHead = null; Node join = null; int t = 0; // Traverse till the end of the linked list while (curr != null) { t = k; join = curr; prev = null; /* Reverse alternative group of k nodes // of the given linked list */ while (curr != null && t-- >0) { temp = curr.next; curr.next = prev; prev = curr; curr = temp; } // Sets the new head of the input list if (newHead == null) newHead = prev; /* Tail pointer keeps track of the last node of the k-reversed linked list. The tail pointer is then joined with the first node of the next k-nodes of the linked list */ if (tail != null) tail.next = prev; tail = join; tail.next = curr; t = k; /* Traverse through the next k nodes which will not be reversed */ while (curr != null && t-- >0) { prev = curr; curr = curr.next; } /* Tail pointer keeps track of the last node of the k nodes traversed above */ tail = prev; } // newHead is new head of the modified list return newHead;} // Function to insert a node at// the head of the linked liststatic void push(Node head_ref, int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; head = head_ref;} // Function to print the linked liststatic void printList(Node node){ int count = 0; while (node != null) { System.out.print(node.data + " "); node = node.next; count++; }} // Driver codepublic static void main(String[] args){ // Start with the empty list head = null; int i; // Create a list 1->2->3->4->...->10 for (i = 10; i > 0; i--) push(head, i); int k = 3; System.out.print("Given linked list \n"); printList(head); head = kAltReverse(head, k); System.out.print("\n Modified Linked list \n"); printList(head);}} // This code is contributed by Rajput-Ji
# Python implementation of the approach # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None head = None # Function to reverse alternate k nodes and# return the pointer to the new head nodedef kAltReverse(head, k): prev = None curr = head temp = None tail = None newHead = None join = None t = 0 # Traverse till the end of the linked list while (curr != None) : t = k join = curr prev = None # Reverse alternative group of k nodes # of the given linked list while (curr != None and t > 0): t = t - 1 temp = curr.next curr.next = prev prev = curr curr = temp # Sets the new head of the input list if (newHead == None): newHead = prev # Tail pointer keeps track of the last node # of the k-reversed linked list. The tail pointer # is then joined with the first node of the # next k-nodes of the linked list if (tail != None): tail.next = prev tail = join tail.next = curr t = k # Traverse through the next k nodes # which will not be reversed while (curr != None and t > 0): t = t - 1 prev = curr curr = curr.next # Tail pointer keeps track of the last # node of the k nodes traversed above tail = prev # newHead is new head of the modified list return newHead # Function to insert a node at# the head of the linked listdef push(head_ref, new_data): global head # allocate node new_node = Node(0) # put in the data new_node.data = new_data # link the old list off the new node new_node.next = head_ref # move the head to point to the new node head_ref = new_node head = head_ref # Function to print the linked listdef printList(node): count = 0 while (node != None): print(node.data ,end= " ") node = node.next count = count + 1 # Driver code # Start with the empty listhead = Nonei = 10 # Create a list 1->2->3->4->...->10while ( i > 0 ): push(head, i) i = i - 1 k = 3 print("Given linked list ")printList(head)head = kAltReverse(head, k) print("\n Modified Linked list ")printList(head) # This code is contributed by Arnab Kundu
// C# implementation of the approachusing System; class GFG{ // Link list nodepublic class Node{ public int data; public Node next;};static Node head; /* Function to reverse alternate k nodes andreturn the pointer to the new head node */static Node kAltReverse(Node head, int k){ Node prev = null; Node curr = head; Node temp = null; Node tail = null; Node newHead = null; Node join = null; int t = 0; // Traverse till the end of the linked list while (curr != null) { t = k; join = curr; prev = null; /* Reverse alternative group of k nodes // of the given linked list */ while (curr != null && t-- >0) { temp = curr.next; curr.next = prev; prev = curr; curr = temp; } // Sets the new head of the input list if (newHead == null) newHead = prev; /* Tail pointer keeps track of the last node of the k-reversed linked list. The tail pointer is then joined with the first node of the next k-nodes of the linked list */ if (tail != null) tail.next = prev; tail = join; tail.next = curr; t = k; /* Traverse through the next k nodes which will not be reversed */ while (curr != null && t-- >0) { prev = curr; curr = curr.next; } /* Tail pointer keeps track of the last node of the k nodes traversed above */ tail = prev; } // newHead is new head of the modified list return newHead;} // Function to insert a node at// the head of the linked liststatic void push(Node head_ref, int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; head = head_ref;} // Function to print the linked liststatic void printList(Node node){ int count = 0; while (node != null) { Console.Write(node.data + " "); node = node.next; count++; }} // Driver codepublic static void Main(String[] args){ // Start with the empty list head = null; int i; // Create a list 1->2->3->4->...->10 for (i = 10; i > 0; i--) push(head, i); int k = 3; Console.Write("Given linked list \n"); printList(head); head = kAltReverse(head, k); Console.Write("\nModified Linked list \n"); printList(head);}} // This code is contributed by Rajput-Ji
<script>// javascript implementation of the approach // Link list nodeclass Node { constructor(val) { this.data = val; this.next = null; }} var head; /* * Function to reverse alternate k nodes and return the pointer to the new head * node */ function kAltReverse(head , k) {var prev = null;var curr = head;var temp = null;var tail = null;var newHead = null;var join = null; var t = 0; // Traverse till the end of the linked list while (curr != null) { t = k; join = curr; prev = null; /* * Reverse alternative group of k nodes // of the given linked list */ while (curr != null && t-- > 0) { temp = curr.next; curr.next = prev; prev = curr; curr = temp; } // Sets the new head of the input list if (newHead == null) newHead = prev; /* * Tail pointer keeps track of the last node of the k-reversed linked list. The * tail pointer is then joined with the first node of the next k-nodes of the * linked list */ if (tail != null) tail.next = prev; tail = join; tail.next = curr; t = k; /* * Traverse through the next k nodes which will not be reversed */ while (curr != null && t-- > 0) { prev = curr; curr = curr.next; } /* * Tail pointer keeps track of the last node of the k nodes traversed above */ tail = prev; } // newHead is new head of the modified list return newHead; } // Function to insert a node at // the head of the linked list function push(head_ref , new_data) { /* allocate node */var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; head = head_ref; } // Function to print the linked list function printList(node) { var count = 0; while (node != null) { document.write(node.data + " "); node = node.next; count++; } } // Driver code // Start with the empty list head = null; var i; // Create a list 1->2->3->4->...->10 for (i = 10; i > 0; i--) push(head, i); var k = 3; document.write("Given linked list <br/>"); printList(head); head = kAltReverse(head, k); document.write("<br/>Modified Linked list <br/>"); printList(head); // This code contributed by gauravrajput1</script>
Given linked list
1 2 3 4 5 6 7 8 9 10
Modified Linked list
3 2 1 4 5 6 9 8 7 10
Time Complexity: O(n) Space Complexity: O(1)
Rajput-Ji
andrew1234
GauravRajput1
ankita_saini
simranarora5sos
Data Structures
Linked List
Data Structures
Linked List
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
Insertion in a B+ tree
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node) | [
{
"code": null,
"e": 26409,
"s": 26381,
"text": "\n11 Nov, 2021"
},
{
"code": null,
"e": 26506,
"s": 26409,
"text": "Given a linked list and an integer K, the task is to reverse every alternate K nodes.Examples: "
},
{
"code": null,
"e": 26687,
"s": 26506,
"text": "Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> NULL, K = 3 Output: 3 2 1 4 5 6 9 8 7Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> NULL, K = 5 Output: 5 4 3 2 1 6 7 8 9 "
},
{
"code": null,
"e": 27564,
"s": 26689,
"text": "Approach: We have already discussed a recursive solution here. In this post, we will discuss an iterative solution to the above problem. While traversing we process 2k nodes in one iteration and keep track of the first and last node of the group of k-nodes in the given linked list using the join and tail pointer. After reversing the k nodes of the linked list, we join the last node of the reversed list, pointed by the tail pointer, with the first node of the original list, pointed by the join pointer. We then move the current pointer until we skip the next k nodes. The tail now becomes the last node of the normal list (which is pointed by the updated tail pointer) and join points to the first of the reversed list and they are then joined. We repeat this process until all the nodes are processed in the same way.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27568,
"s": 27564,
"text": "C++"
},
{
"code": null,
"e": 27573,
"s": 27568,
"text": "Java"
},
{
"code": null,
"e": 27580,
"s": 27573,
"text": "Python"
},
{
"code": null,
"e": 27583,
"s": 27580,
"text": "C#"
},
{
"code": null,
"e": 27594,
"s": 27583,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Link list nodeclass Node {public: int data; Node* next;}; /* Function to reverse alternate k nodes andreturn the pointer to the new head node */Node* kAltReverse(struct Node* head, int k){ Node* prev = NULL; Node* curr = head; Node* temp = NULL; Node* tail = NULL; Node* newHead = NULL; Node* join = NULL; int t = 0; // Traverse till the end of the linked list while (curr) { t = k; join = curr; prev = NULL; /* Reverse alternative group of k nodes // of the given linked list */ while (curr && t--) { temp = curr->next; curr->next = prev; prev = curr; curr = temp; } // Sets the new head of the input list if (!newHead) newHead = prev; /* Tail pointer keeps track of the last node of the k-reversed linked list. The tail pointer is then joined with the first node of the next k-nodes of the linked list */ if (tail) tail->next = prev; tail = join; tail->next = curr; t = k; /* Traverse through the next k nodes which will not be reversed */ while (curr && t--) { prev = curr; curr = curr->next; } /* Tail pointer keeps track of the last node of the k nodes traversed above */ tail = prev; } // newHead is new head of the modified list return newHead;} // Function to insert a node at// the head of the linked listvoid push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Function to print the linked listvoid printList(Node* node){ int count = 0; while (node != NULL) { cout << node->data << \" \"; node = node->next; count++; }} // Driver codeint main(void){ // Start with the empty list Node* head = NULL; int i; // Create a list 1->2->3->4->...->10 for (i = 10; i > 0; i--) push(&head, i); int k = 3; cout << \"Given linked list \\n\"; printList(head); head = kAltReverse(head, k); cout << \"\\n Modified Linked list \\n\"; printList(head); return (0);}",
"e": 30067,
"s": 27594,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Link list nodestatic class Node{ int data; Node next;};static Node head; /* Function to reverse alternate k nodes andreturn the pointer to the new head node */static Node kAltReverse(Node head, int k){ Node prev = null; Node curr = head; Node temp = null; Node tail = null; Node newHead = null; Node join = null; int t = 0; // Traverse till the end of the linked list while (curr != null) { t = k; join = curr; prev = null; /* Reverse alternative group of k nodes // of the given linked list */ while (curr != null && t-- >0) { temp = curr.next; curr.next = prev; prev = curr; curr = temp; } // Sets the new head of the input list if (newHead == null) newHead = prev; /* Tail pointer keeps track of the last node of the k-reversed linked list. The tail pointer is then joined with the first node of the next k-nodes of the linked list */ if (tail != null) tail.next = prev; tail = join; tail.next = curr; t = k; /* Traverse through the next k nodes which will not be reversed */ while (curr != null && t-- >0) { prev = curr; curr = curr.next; } /* Tail pointer keeps track of the last node of the k nodes traversed above */ tail = prev; } // newHead is new head of the modified list return newHead;} // Function to insert a node at// the head of the linked liststatic void push(Node head_ref, int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; head = head_ref;} // Function to print the linked liststatic void printList(Node node){ int count = 0; while (node != null) { System.out.print(node.data + \" \"); node = node.next; count++; }} // Driver codepublic static void main(String[] args){ // Start with the empty list head = null; int i; // Create a list 1->2->3->4->...->10 for (i = 10; i > 0; i--) push(head, i); int k = 3; System.out.print(\"Given linked list \\n\"); printList(head); head = kAltReverse(head, k); System.out.print(\"\\n Modified Linked list \\n\"); printList(head);}} // This code is contributed by Rajput-Ji",
"e": 32665,
"s": 30067,
"text": null
},
{
"code": "# Python implementation of the approach # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None head = None # Function to reverse alternate k nodes and# return the pointer to the new head nodedef kAltReverse(head, k): prev = None curr = head temp = None tail = None newHead = None join = None t = 0 # Traverse till the end of the linked list while (curr != None) : t = k join = curr prev = None # Reverse alternative group of k nodes # of the given linked list while (curr != None and t > 0): t = t - 1 temp = curr.next curr.next = prev prev = curr curr = temp # Sets the new head of the input list if (newHead == None): newHead = prev # Tail pointer keeps track of the last node # of the k-reversed linked list. The tail pointer # is then joined with the first node of the # next k-nodes of the linked list if (tail != None): tail.next = prev tail = join tail.next = curr t = k # Traverse through the next k nodes # which will not be reversed while (curr != None and t > 0): t = t - 1 prev = curr curr = curr.next # Tail pointer keeps track of the last # node of the k nodes traversed above tail = prev # newHead is new head of the modified list return newHead # Function to insert a node at# the head of the linked listdef push(head_ref, new_data): global head # allocate node new_node = Node(0) # put in the data new_node.data = new_data # link the old list off the new node new_node.next = head_ref # move the head to point to the new node head_ref = new_node head = head_ref # Function to print the linked listdef printList(node): count = 0 while (node != None): print(node.data ,end= \" \") node = node.next count = count + 1 # Driver code # Start with the empty listhead = Nonei = 10 # Create a list 1->2->3->4->...->10while ( i > 0 ): push(head, i) i = i - 1 k = 3 print(\"Given linked list \")printList(head)head = kAltReverse(head, k) print(\"\\n Modified Linked list \")printList(head) # This code is contributed by Arnab Kundu",
"e": 35148,
"s": 32665,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Link list nodepublic class Node{ public int data; public Node next;};static Node head; /* Function to reverse alternate k nodes andreturn the pointer to the new head node */static Node kAltReverse(Node head, int k){ Node prev = null; Node curr = head; Node temp = null; Node tail = null; Node newHead = null; Node join = null; int t = 0; // Traverse till the end of the linked list while (curr != null) { t = k; join = curr; prev = null; /* Reverse alternative group of k nodes // of the given linked list */ while (curr != null && t-- >0) { temp = curr.next; curr.next = prev; prev = curr; curr = temp; } // Sets the new head of the input list if (newHead == null) newHead = prev; /* Tail pointer keeps track of the last node of the k-reversed linked list. The tail pointer is then joined with the first node of the next k-nodes of the linked list */ if (tail != null) tail.next = prev; tail = join; tail.next = curr; t = k; /* Traverse through the next k nodes which will not be reversed */ while (curr != null && t-- >0) { prev = curr; curr = curr.next; } /* Tail pointer keeps track of the last node of the k nodes traversed above */ tail = prev; } // newHead is new head of the modified list return newHead;} // Function to insert a node at// the head of the linked liststatic void push(Node head_ref, int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; head = head_ref;} // Function to print the linked liststatic void printList(Node node){ int count = 0; while (node != null) { Console.Write(node.data + \" \"); node = node.next; count++; }} // Driver codepublic static void Main(String[] args){ // Start with the empty list head = null; int i; // Create a list 1->2->3->4->...->10 for (i = 10; i > 0; i--) push(head, i); int k = 3; Console.Write(\"Given linked list \\n\"); printList(head); head = kAltReverse(head, k); Console.Write(\"\\nModified Linked list \\n\"); printList(head);}} // This code is contributed by Rajput-Ji",
"e": 37762,
"s": 35148,
"text": null
},
{
"code": "<script>// javascript implementation of the approach // Link list nodeclass Node { constructor(val) { this.data = val; this.next = null; }} var head; /* * Function to reverse alternate k nodes and return the pointer to the new head * node */ function kAltReverse(head , k) {var prev = null;var curr = head;var temp = null;var tail = null;var newHead = null;var join = null; var t = 0; // Traverse till the end of the linked list while (curr != null) { t = k; join = curr; prev = null; /* * Reverse alternative group of k nodes // of the given linked list */ while (curr != null && t-- > 0) { temp = curr.next; curr.next = prev; prev = curr; curr = temp; } // Sets the new head of the input list if (newHead == null) newHead = prev; /* * Tail pointer keeps track of the last node of the k-reversed linked list. The * tail pointer is then joined with the first node of the next k-nodes of the * linked list */ if (tail != null) tail.next = prev; tail = join; tail.next = curr; t = k; /* * Traverse through the next k nodes which will not be reversed */ while (curr != null && t-- > 0) { prev = curr; curr = curr.next; } /* * Tail pointer keeps track of the last node of the k nodes traversed above */ tail = prev; } // newHead is new head of the modified list return newHead; } // Function to insert a node at // the head of the linked list function push(head_ref , new_data) { /* allocate node */var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; head = head_ref; } // Function to print the linked list function printList(node) { var count = 0; while (node != null) { document.write(node.data + \" \"); node = node.next; count++; } } // Driver code // Start with the empty list head = null; var i; // Create a list 1->2->3->4->...->10 for (i = 10; i > 0; i--) push(head, i); var k = 3; document.write(\"Given linked list <br/>\"); printList(head); head = kAltReverse(head, k); document.write(\"<br/>Modified Linked list <br/>\"); printList(head); // This code contributed by gauravrajput1</script>",
"e": 40685,
"s": 37762,
"text": null
},
{
"code": null,
"e": 40770,
"s": 40685,
"text": "Given linked list \n1 2 3 4 5 6 7 8 9 10 \n Modified Linked list \n3 2 1 4 5 6 9 8 7 10"
},
{
"code": null,
"e": 40818,
"s": 40772,
"text": "Time Complexity: O(n) Space Complexity: O(1) "
},
{
"code": null,
"e": 40828,
"s": 40818,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 40839,
"s": 40828,
"text": "andrew1234"
},
{
"code": null,
"e": 40853,
"s": 40839,
"text": "GauravRajput1"
},
{
"code": null,
"e": 40866,
"s": 40853,
"text": "ankita_saini"
},
{
"code": null,
"e": 40882,
"s": 40866,
"text": "simranarora5sos"
},
{
"code": null,
"e": 40898,
"s": 40882,
"text": "Data Structures"
},
{
"code": null,
"e": 40910,
"s": 40898,
"text": "Linked List"
},
{
"code": null,
"e": 40926,
"s": 40910,
"text": "Data Structures"
},
{
"code": null,
"e": 40938,
"s": 40926,
"text": "Linked List"
},
{
"code": null,
"e": 41036,
"s": 40938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41063,
"s": 41036,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 41099,
"s": 41063,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 41158,
"s": 41099,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 41206,
"s": 41158,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 41229,
"s": 41206,
"text": "Insertion in a B+ tree"
},
{
"code": null,
"e": 41264,
"s": 41229,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 41303,
"s": 41264,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 41325,
"s": 41303,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 41373,
"s": 41325,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
String Interpolation in Angular 8 - GeeksforGeeks | 31 Aug, 2020
String Interpolation in Angular 8 is a one-way data-binding technique that is used to transfer the data from a TypeScript code to an HTML template (view). It uses the template expression in double curly braces to display the data from the component to the view. String interpolation adds the value of a property from the component to the HTML template view.
Syntax:
{{ component_property }}
Approach:
Define a property in the app.component.ts file containing some string value.
In the app.component.html file, bind the value of that property by calling the property name in double curly braces {{ property_name }}.
Example 1:
app.component.htmlHTMLHTML<h1> {{ title }}</h1>
app.component.html
HTML
<h1> {{ title }}</h1>
app.component.tsJavascriptJavascriptimport { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = "GeeksforGeeks";}
app.component.ts
Javascript
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = "GeeksforGeeks";}
Output:
Example 2:
app.component.htmlHTMLHTML<h1 [style.color] = "'green'" [style.text-align] = "'center'" > {{ title }} : {{ about }}</h1>
app.component.html
HTML
<h1 [style.color] = "'green'" [style.text-align] = "'center'" > {{ title }} : {{ about }}</h1>
app.component.tsJavascriptJavascriptimport { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = "GeeksforGeeks"; about = "Computer Science Portal for Geeks";}
app.component.ts
Javascript
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = "GeeksforGeeks"; about = "Computer Science Portal for Geeks";}
Output:
AngularJS-Misc
Picked
AngularJS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Auth Guards in Angular 9/10/11
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
How to bundle an Angular app for production?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
File uploading in React.js | [
{
"code": null,
"e": 25898,
"s": 25870,
"text": "\n31 Aug, 2020"
},
{
"code": null,
"e": 26256,
"s": 25898,
"text": "String Interpolation in Angular 8 is a one-way data-binding technique that is used to transfer the data from a TypeScript code to an HTML template (view). It uses the template expression in double curly braces to display the data from the component to the view. String interpolation adds the value of a property from the component to the HTML template view."
},
{
"code": null,
"e": 26264,
"s": 26256,
"text": "Syntax:"
},
{
"code": null,
"e": 26290,
"s": 26264,
"text": "{{ component_property }}\n"
},
{
"code": null,
"e": 26301,
"s": 26290,
"text": "Approach: "
},
{
"code": null,
"e": 26378,
"s": 26301,
"text": "Define a property in the app.component.ts file containing some string value."
},
{
"code": null,
"e": 26515,
"s": 26378,
"text": "In the app.component.html file, bind the value of that property by calling the property name in double curly braces {{ property_name }}."
},
{
"code": null,
"e": 26527,
"s": 26515,
"text": "Example 1: "
},
{
"code": null,
"e": 26576,
"s": 26527,
"text": "app.component.htmlHTMLHTML<h1> {{ title }}</h1>"
},
{
"code": null,
"e": 26595,
"s": 26576,
"text": "app.component.html"
},
{
"code": null,
"e": 26600,
"s": 26595,
"text": "HTML"
},
{
"code": "<h1> {{ title }}</h1>",
"e": 26623,
"s": 26600,
"text": null
},
{
"code": null,
"e": 26894,
"s": 26623,
"text": "app.component.tsJavascriptJavascriptimport { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = \"GeeksforGeeks\";}"
},
{
"code": null,
"e": 26911,
"s": 26894,
"text": "app.component.ts"
},
{
"code": null,
"e": 26922,
"s": 26911,
"text": "Javascript"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = \"GeeksforGeeks\";}",
"e": 27157,
"s": 26922,
"text": null
},
{
"code": null,
"e": 27165,
"s": 27157,
"text": "Output:"
},
{
"code": null,
"e": 27176,
"s": 27165,
"text": "Example 2:"
},
{
"code": null,
"e": 27304,
"s": 27176,
"text": "app.component.htmlHTMLHTML<h1 [style.color] = \"'green'\" [style.text-align] = \"'center'\" > {{ title }} : {{ about }}</h1>"
},
{
"code": null,
"e": 27323,
"s": 27304,
"text": "app.component.html"
},
{
"code": null,
"e": 27328,
"s": 27323,
"text": "HTML"
},
{
"code": "<h1 [style.color] = \"'green'\" [style.text-align] = \"'center'\" > {{ title }} : {{ about }}</h1>",
"e": 27430,
"s": 27328,
"text": null
},
{
"code": null,
"e": 27747,
"s": 27430,
"text": "app.component.tsJavascriptJavascriptimport { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = \"GeeksforGeeks\"; about = \"Computer Science Portal for Geeks\";}"
},
{
"code": null,
"e": 27764,
"s": 27747,
"text": "app.component.ts"
},
{
"code": null,
"e": 27775,
"s": 27764,
"text": "Javascript"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = \"GeeksforGeeks\"; about = \"Computer Science Portal for Geeks\";}",
"e": 28056,
"s": 27775,
"text": null
},
{
"code": null,
"e": 28064,
"s": 28056,
"text": "Output:"
},
{
"code": null,
"e": 28079,
"s": 28064,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 28086,
"s": 28079,
"text": "Picked"
},
{
"code": null,
"e": 28096,
"s": 28086,
"text": "AngularJS"
},
{
"code": null,
"e": 28107,
"s": 28096,
"text": "JavaScript"
},
{
"code": null,
"e": 28124,
"s": 28107,
"text": "Web Technologies"
},
{
"code": null,
"e": 28222,
"s": 28124,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28257,
"s": 28222,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 28288,
"s": 28257,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 28323,
"s": 28288,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 28358,
"s": 28323,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 28403,
"s": 28358,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 28443,
"s": 28403,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28488,
"s": 28443,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28549,
"s": 28488,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28618,
"s": 28549,
"text": "How to calculate the number of days between two dates in javascript?"
}
] |
Biggest integer which has maximum digit sum in range from 1 to n - GeeksforGeeks | 22 Apr, 2021
Given a number n, find a number in range from 1 to n such that its sum is maximum. If there are several such integers, determine the biggest of them.
Examples :
Input: n = 100
Output: 99
99 is the largest number in range from
1 to 100 with maximum sum of digits.
Input: n = 48
Output: 48
Explanation:
There are two numbers with maximum
digit sum. The numbers are 48 and 39
Since 48 > 39, it is our answer.
A naive approach is to iterate for all numbers from 1 to n and find out which number has maximum sum of digits. Time complexity of this solution is O(n).
An efficient approach is to iterate from n to 1. Do the following for each digit of current number, if the digit is not zero, reduce it by one and change all other digits to nine to the right of it. If the sum of digits in the resulting integer is strictly greater than the sum of the digits of the current answer, then update the answer with the resulting integer. If the sum of the resulting integer is same as the current answer, then if the resulting integer is more then current answer, update the current answer with the resulting integer.
How to reduce a digit and change all other digits on its right to 9? Let x be our current number. We can find next number for current digit using below formula. In below formula, b is a power of 10 to represent position of current digit. After every iteration we reduce x to x/10 and change b to b * 10.We use (x – 1) * b + (b – 1);
This line can further be explained as, if the number is x = 521 and b = 1, then
(521 – 1) * 1 + (1-1) which gives you 520, which is the thing we need to do, reduce the position number by 1 and replace all other numbers to the right by 9.
After x /= 10 gives you x as 52 and b*=10 gives you b as 10, which is again executed as (52-1)*(10) + 9 which gives you 519, which is what we have to do, reduce the current index by 1 and increase all other rights by 9.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the// number with maximum digit// sum.#include <bits/stdc++.h>using namespace std; // function to calculate the // sum of digits of a number.int sumOfDigits(int a){ int sum = 0; while (a) { sum += a % 10; a /= 10; } return sum;} // Returns the maximum number// with maximum sum of digits.int findMax(int x){ // initializing b as 1 and // initial max sum to be of n int b = 1, ans = x; // iterates from right to // left in a digit while (x) { // while iterating this // is the number from // from right to left int cur = (x - 1) * b + (b - 1); // calls the function to // check if sum of cur is // more then of ans if (sumOfDigits(cur) > sumOfDigits(ans) || (sumOfDigits(cur) == sumOfDigits(ans) && cur > ans)) ans = cur; // reduces the number to one unit less x /= 10; b *= 10; } return ans;} // driver programint main(){ int n = 521; cout << findMax(n); return 0;}
// Java program to find the// number with maximum digit// sum.import java.io.*; class GFG { // function to calculate the // sum of digits of a number. static int sumOfDigits(int a) { int sum = 0; while (a!=0) { sum += a % 10; a /= 10; } return sum; } // Returns the maximum number // with maximum sum of digits. static int findMax(int x) { // initializing b as 1 and // initial max sum to be of n int b = 1, ans = x; // iterates from right to // left in a digit while (x!=0) { // while iterating this // is the number from // from right to left int cur = (x - 1) * b + (b - 1); // calls the function to // check if sum of cur is // more then of ans if (sumOfDigits(cur) > sumOfDigits(ans) || (sumOfDigits(cur) == sumOfDigits(ans) && cur > ans)) ans = cur; // reduces the number to one unit less x /= 10; b *= 10; } return ans; } // driver program public static void main (String[] args) { int n = 521; System.out.println(findMax(n)); }} /*This article is contributed by Nikita Tiwari.*/
# Python 3 program to# find the number# with maximum digit# sum. # function to calculate# the sum of digits of# a number.def sumOfDigits(a) : sm = 0 while (a!=0) : sm = sm + a % 10 a = a // 10 return sm # Returns the maximum number# with maximum sum of digits.def findMax(x) : # initializing b as 1 # and initial max sum # to be of n b = 1 ans = x # iterates from right # to left in a digit while (x!=0) : # while iterating this # is the number from # right to left cur = (x - 1) * b + (b - 1) # calls the function to # check if sum of cur is # more then of ans if (sumOfDigits(cur) > sumOfDigits(ans) or (sumOfDigits(cur) == sumOfDigits(ans) and cur > ans)) : ans = cur # reduces the number # to one unit less x =x // 10 b = b * 10 return ans # driver program to test the above functionn = 521print(findMax(n)) # This article is contributed by Nikita Tiwari.
// C# program to find the number// with maximum digit sum.using System; class GFG { // function to calculate the // sum of digits of a number. static int sumOfDigits(int a) { int sum = 0; while (a!=0) { sum += a % 10; a /= 10; } return sum; } // Returns the maximum number // with maximum sum of digits. static int findMax(int x) { // initializing b as 1 and // initial max sum to be of n int b = 1, ans = x; // iterates from right to // left in a digit while (x!=0) { // while iterating this // is the number from // from right to left int cur = (x - 1) * b + (b - 1); // calls the function to // check if sum of cur is // more then of ans if (sumOfDigits(cur) > sumOfDigits(ans) || (sumOfDigits(cur) == sumOfDigits(ans) && cur > ans)) ans = cur; // reduces the number to one unit less x /= 10; b *= 10; } return ans; } // driver program public static void Main() { int n = 521; Console.WriteLine(findMax(n)); }} // This article is contributed by Anant Agarwal.
<?php// PHP program to find the// number with maximum digit// sum. // function to calculate the// sum of digits of a number.function sumOfDigits($a){ $sum = 0; while ($a) { $sum += $a % 10; $a = (int)$a / 10; } return $sum;} // Returns the maximum number// with maximum sum of digits.function findMax( $x){ // initializing b as 1 and // initial max sum to be of n $b = 1; $ans = $x; // iterates from right to // left in a digit while ($x) { // while iterating this // is the number from // from right to left $cur = ($x - 1) * $b + ($b - 1); // calls the function to // check if sum of cur is // more then of ans if (sumOfDigits($cur) > sumOfDigits($ans) || (sumOfDigits($cur) == sumOfDigits($ans) && $cur > $ans)) $ans = $cur; // reduces the number // to one unit less $x = (int)$x / 10; $b *= 10; } return $ans;} // Driver Code$n = 521;echo findMax($n); // This code is contributed by ajit?>
<script> // Javascript program to find the// number with maximum digit// sum. // Function to calculate the// sum of digits of a number.function sumOfDigits(a){ var sum = 0; while (a != 0) { sum += a % 10; a = parseInt(a / 10); } return sum;} // Returns the maximum number// with maximum sum of digits.function findMax(x){ // Initializing b as 1 and // initial max sum to be of n var b = 1, ans = x; // Iterates from right to // left in a digit while (x != 0) { // While iterating this // is the number from // from right to left var cur = (x - 1) * b + (b - 1); // Calls the function to // check if sum of cur is // more then of ans if (sumOfDigits(cur) > sumOfDigits(ans) || (sumOfDigits(cur) == sumOfDigits(ans) && cur > ans)) ans = cur; // Reduces the number to one unit less x = parseInt(x / 10); b *= 10; } return ans;} // Driver Codevar n = 521; document.write(findMax(n)); // This code is contributed by todaysgaurav </script>
Output :
499
Time complexity : O(m) where m is the number of digits in n.
This article is contributed by Striver. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
todaysgaurav
number-digits
Numbers
Mathematical
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Modular multiplicative inverse
Fizz Buzz Implementation
Singular Value Decomposition (SVD)
Check if a number is Palindrome
Segment Tree | Set 1 (Sum of given range)
How to check if a given point lies inside or outside a polygon?
Program to multiply two matrices
Count ways to reach the n'th stair
Merge two sorted arrays with O(1) extra space | [
{
"code": null,
"e": 26073,
"s": 26045,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 26223,
"s": 26073,
"text": "Given a number n, find a number in range from 1 to n such that its sum is maximum. If there are several such integers, determine the biggest of them."
},
{
"code": null,
"e": 26235,
"s": 26223,
"text": "Examples : "
},
{
"code": null,
"e": 26485,
"s": 26235,
"text": "Input: n = 100\nOutput: 99 \n99 is the largest number in range from\n1 to 100 with maximum sum of digits.\n\nInput: n = 48\nOutput: 48\nExplanation: \nThere are two numbers with maximum\ndigit sum. The numbers are 48 and 39\nSince 48 > 39, it is our answer."
},
{
"code": null,
"e": 26639,
"s": 26485,
"text": "A naive approach is to iterate for all numbers from 1 to n and find out which number has maximum sum of digits. Time complexity of this solution is O(n)."
},
{
"code": null,
"e": 27185,
"s": 26639,
"text": "An efficient approach is to iterate from n to 1. Do the following for each digit of current number, if the digit is not zero, reduce it by one and change all other digits to nine to the right of it. If the sum of digits in the resulting integer is strictly greater than the sum of the digits of the current answer, then update the answer with the resulting integer. If the sum of the resulting integer is same as the current answer, then if the resulting integer is more then current answer, update the current answer with the resulting integer."
},
{
"code": null,
"e": 27519,
"s": 27185,
"text": "How to reduce a digit and change all other digits on its right to 9? Let x be our current number. We can find next number for current digit using below formula. In below formula, b is a power of 10 to represent position of current digit. After every iteration we reduce x to x/10 and change b to b * 10.We use (x – 1) * b + (b – 1); "
},
{
"code": null,
"e": 27601,
"s": 27519,
"text": "This line can further be explained as, if the number is x = 521 and b = 1, then "
},
{
"code": null,
"e": 27759,
"s": 27601,
"text": "(521 – 1) * 1 + (1-1) which gives you 520, which is the thing we need to do, reduce the position number by 1 and replace all other numbers to the right by 9."
},
{
"code": null,
"e": 27979,
"s": 27759,
"text": "After x /= 10 gives you x as 52 and b*=10 gives you b as 10, which is again executed as (52-1)*(10) + 9 which gives you 519, which is what we have to do, reduce the current index by 1 and increase all other rights by 9."
},
{
"code": null,
"e": 27983,
"s": 27979,
"text": "C++"
},
{
"code": null,
"e": 27988,
"s": 27983,
"text": "Java"
},
{
"code": null,
"e": 27996,
"s": 27988,
"text": "Python3"
},
{
"code": null,
"e": 27999,
"s": 27996,
"text": "C#"
},
{
"code": null,
"e": 28003,
"s": 27999,
"text": "PHP"
},
{
"code": null,
"e": 28014,
"s": 28003,
"text": "Javascript"
},
{
"code": "// CPP program to find the// number with maximum digit// sum.#include <bits/stdc++.h>using namespace std; // function to calculate the // sum of digits of a number.int sumOfDigits(int a){ int sum = 0; while (a) { sum += a % 10; a /= 10; } return sum;} // Returns the maximum number// with maximum sum of digits.int findMax(int x){ // initializing b as 1 and // initial max sum to be of n int b = 1, ans = x; // iterates from right to // left in a digit while (x) { // while iterating this // is the number from // from right to left int cur = (x - 1) * b + (b - 1); // calls the function to // check if sum of cur is // more then of ans if (sumOfDigits(cur) > sumOfDigits(ans) || (sumOfDigits(cur) == sumOfDigits(ans) && cur > ans)) ans = cur; // reduces the number to one unit less x /= 10; b *= 10; } return ans;} // driver programint main(){ int n = 521; cout << findMax(n); return 0;}",
"e": 29082,
"s": 28014,
"text": null
},
{
"code": "// Java program to find the// number with maximum digit// sum.import java.io.*; class GFG { // function to calculate the // sum of digits of a number. static int sumOfDigits(int a) { int sum = 0; while (a!=0) { sum += a % 10; a /= 10; } return sum; } // Returns the maximum number // with maximum sum of digits. static int findMax(int x) { // initializing b as 1 and // initial max sum to be of n int b = 1, ans = x; // iterates from right to // left in a digit while (x!=0) { // while iterating this // is the number from // from right to left int cur = (x - 1) * b + (b - 1); // calls the function to // check if sum of cur is // more then of ans if (sumOfDigits(cur) > sumOfDigits(ans) || (sumOfDigits(cur) == sumOfDigits(ans) && cur > ans)) ans = cur; // reduces the number to one unit less x /= 10; b *= 10; } return ans; } // driver program public static void main (String[] args) { int n = 521; System.out.println(findMax(n)); }} /*This article is contributed by Nikita Tiwari.*/",
"e": 30450,
"s": 29082,
"text": null
},
{
"code": "# Python 3 program to# find the number# with maximum digit# sum. # function to calculate# the sum of digits of# a number.def sumOfDigits(a) : sm = 0 while (a!=0) : sm = sm + a % 10 a = a // 10 return sm # Returns the maximum number# with maximum sum of digits.def findMax(x) : # initializing b as 1 # and initial max sum # to be of n b = 1 ans = x # iterates from right # to left in a digit while (x!=0) : # while iterating this # is the number from # right to left cur = (x - 1) * b + (b - 1) # calls the function to # check if sum of cur is # more then of ans if (sumOfDigits(cur) > sumOfDigits(ans) or (sumOfDigits(cur) == sumOfDigits(ans) and cur > ans)) : ans = cur # reduces the number # to one unit less x =x // 10 b = b * 10 return ans # driver program to test the above functionn = 521print(findMax(n)) # This article is contributed by Nikita Tiwari.",
"e": 31521,
"s": 30450,
"text": null
},
{
"code": "// C# program to find the number// with maximum digit sum.using System; class GFG { // function to calculate the // sum of digits of a number. static int sumOfDigits(int a) { int sum = 0; while (a!=0) { sum += a % 10; a /= 10; } return sum; } // Returns the maximum number // with maximum sum of digits. static int findMax(int x) { // initializing b as 1 and // initial max sum to be of n int b = 1, ans = x; // iterates from right to // left in a digit while (x!=0) { // while iterating this // is the number from // from right to left int cur = (x - 1) * b + (b - 1); // calls the function to // check if sum of cur is // more then of ans if (sumOfDigits(cur) > sumOfDigits(ans) || (sumOfDigits(cur) == sumOfDigits(ans) && cur > ans)) ans = cur; // reduces the number to one unit less x /= 10; b *= 10; } return ans; } // driver program public static void Main() { int n = 521; Console.WriteLine(findMax(n)); }} // This article is contributed by Anant Agarwal.",
"e": 32905,
"s": 31521,
"text": null
},
{
"code": "<?php// PHP program to find the// number with maximum digit// sum. // function to calculate the// sum of digits of a number.function sumOfDigits($a){ $sum = 0; while ($a) { $sum += $a % 10; $a = (int)$a / 10; } return $sum;} // Returns the maximum number// with maximum sum of digits.function findMax( $x){ // initializing b as 1 and // initial max sum to be of n $b = 1; $ans = $x; // iterates from right to // left in a digit while ($x) { // while iterating this // is the number from // from right to left $cur = ($x - 1) * $b + ($b - 1); // calls the function to // check if sum of cur is // more then of ans if (sumOfDigits($cur) > sumOfDigits($ans) || (sumOfDigits($cur) == sumOfDigits($ans) && $cur > $ans)) $ans = $cur; // reduces the number // to one unit less $x = (int)$x / 10; $b *= 10; } return $ans;} // Driver Code$n = 521;echo findMax($n); // This code is contributed by ajit?>",
"e": 34024,
"s": 32905,
"text": null
},
{
"code": "<script> // Javascript program to find the// number with maximum digit// sum. // Function to calculate the// sum of digits of a number.function sumOfDigits(a){ var sum = 0; while (a != 0) { sum += a % 10; a = parseInt(a / 10); } return sum;} // Returns the maximum number// with maximum sum of digits.function findMax(x){ // Initializing b as 1 and // initial max sum to be of n var b = 1, ans = x; // Iterates from right to // left in a digit while (x != 0) { // While iterating this // is the number from // from right to left var cur = (x - 1) * b + (b - 1); // Calls the function to // check if sum of cur is // more then of ans if (sumOfDigits(cur) > sumOfDigits(ans) || (sumOfDigits(cur) == sumOfDigits(ans) && cur > ans)) ans = cur; // Reduces the number to one unit less x = parseInt(x / 10); b *= 10; } return ans;} // Driver Codevar n = 521; document.write(findMax(n)); // This code is contributed by todaysgaurav </script>",
"e": 35162,
"s": 34024,
"text": null
},
{
"code": null,
"e": 35172,
"s": 35162,
"text": "Output : "
},
{
"code": null,
"e": 35176,
"s": 35172,
"text": "499"
},
{
"code": null,
"e": 35237,
"s": 35176,
"text": "Time complexity : O(m) where m is the number of digits in n."
},
{
"code": null,
"e": 35653,
"s": 35237,
"text": "This article is contributed by Striver. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 35659,
"s": 35653,
"text": "jit_t"
},
{
"code": null,
"e": 35672,
"s": 35659,
"text": "todaysgaurav"
},
{
"code": null,
"e": 35686,
"s": 35672,
"text": "number-digits"
},
{
"code": null,
"e": 35694,
"s": 35686,
"text": "Numbers"
},
{
"code": null,
"e": 35707,
"s": 35694,
"text": "Mathematical"
},
{
"code": null,
"e": 35720,
"s": 35707,
"text": "Mathematical"
},
{
"code": null,
"e": 35728,
"s": 35720,
"text": "Numbers"
},
{
"code": null,
"e": 35826,
"s": 35728,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35870,
"s": 35826,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 35901,
"s": 35870,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 35926,
"s": 35901,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 35961,
"s": 35926,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 35993,
"s": 35961,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 36035,
"s": 35993,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 36099,
"s": 36035,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 36132,
"s": 36099,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 36167,
"s": 36132,
"text": "Count ways to reach the n'th stair"
}
] |
Dual pivot Quicksort - GeeksforGeeks | 17 Mar, 2022
As we know, the single pivot quick sort takes a pivot from one of the ends of the array and partitioning the array, so that all elements are left to the pivot are less than or equal to the pivot, and all elements that are right to the pivot are greater than the pivot.The idea of dual pivot quick sort is to take two pivots, one in the left end of the array and the second, in the right end of the array. The left pivot must be less than or equal to the right pivot, so we swap them if necessary. Then, we begin partitioning the array into three parts: in the first part, all elements will be less than the left pivot, in the second part all elements will be greater or equal to the left pivot and also will be less than or equal to the right pivot, and in the third part all elements will be greater than the right pivot. Then, we shift the two pivots to their appropriate positions as we see in the below bar, and after that we begin quicksorting these three parts recursively, using this method.
Dual pivot quick sort is a little bit faster than the original single pivot quicksort. But still, the worst case will remain O(n^2) when the array is already sorted in an increasing or decreasing order. An example:
C++
C
Java
Python3
// C++ program to implement dual pivot QuickSort#include <iostream>using namespace std; int partition(int* arr, int low, int high, int* lp); void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} void DualPivotQuickSort(int* arr, int low, int high){ if (low < high) { // lp means left pivot, and rp means right pivot. int lp, rp; rp = partition(arr, low, high, &lp); DualPivotQuickSort(arr, low, lp - 1); DualPivotQuickSort(arr, lp + 1, rp - 1); DualPivotQuickSort(arr, rp + 1, high); }} int partition(int* arr, int low, int high, int* lp){ if (arr[low] > arr[high]) swap(&arr[low], &arr[high]); // p is the left pivot, and q is the right pivot. int j = low + 1; int g = high - 1, k = low + 1, p = arr[low], q = arr[high]; while (k <= g) { // if elements are less than the left pivot if (arr[k] < p) { swap(&arr[k], &arr[j]); j++; } // if elements are greater than or equal // to the right pivot else if (arr[k] >= q) { while (arr[g] > q && k < g) g--; swap(&arr[k], &arr[g]); g--; if (arr[k] < p) { swap(&arr[k], &arr[j]); j++; } } k++; } j--; g++; // bring pivots to their appropriate positions. swap(&arr[low], &arr[j]); swap(&arr[high], &arr[g]); // returning the indices of the pivots. *lp = j; // because we cannot return two elements // from a function. return g;} // Driver codeint main(){ int arr[] = { 24, 8, 42, 75, 29, 77, 38, 57 }; DualPivotQuickSort(arr, 0, 7); cout << "Sorted array: "; for (int i = 0; i < 8; i++) cout << arr[i] << " "; cout << endl;} // This code is contributed by SHUBHAMSINGH10
// C program to implement dual pivot QuickSort#include <stdio.h> int partition(int* arr, int low, int high, int* lp); void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} void DualPivotQuickSort(int* arr, int low, int high){ if (low < high) { // lp means left pivot, and rp means right pivot. int lp, rp; rp = partition(arr, low, high, &lp); DualPivotQuickSort(arr, low, lp - 1); DualPivotQuickSort(arr, lp + 1, rp - 1); DualPivotQuickSort(arr, rp + 1, high); }} int partition(int* arr, int low, int high, int* lp){ if (arr[low] > arr[high]) swap(&arr[low], &arr[high]); // p is the left pivot, and q is the right pivot. int j = low + 1; int g = high - 1, k = low + 1, p = arr[low], q = arr[high]; while (k <= g) { // if elements are less than the left pivot if (arr[k] < p) { swap(&arr[k], &arr[j]); j++; } // if elements are greater than or equal // to the right pivot else if (arr[k] >= q) { while (arr[g] > q && k < g) g--; swap(&arr[k], &arr[g]); g--; if (arr[k] < p) { swap(&arr[k], &arr[j]); j++; } } k++; } j--; g++; // bring pivots to their appropriate positions. swap(&arr[low], &arr[j]); swap(&arr[high], &arr[g]); // returning the indices of the pivots. *lp = j; // because we cannot return two elements // from a function. return g;} // Driver codeint main(){ int arr[] = { 24, 8, 42, 75, 29, 77, 38, 57 }; DualPivotQuickSort(arr, 0, 7); printf("Sorted array: "); for (int i = 0; i < 8; i++) printf("%d ", arr[i]); printf("\n"); return 0;}
// Java program to implement// dual pivot QuickSortclass GFG{ static void swap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;} static void dualPivotQuickSort(int[] arr, int low, int high){ if (low < high) { // piv[] stores left pivot and right pivot. // piv[0] means left pivot and // piv[1] means right pivot int[] piv; piv = partition(arr, low, high); dualPivotQuickSort(arr, low, piv[0] - 1); dualPivotQuickSort(arr, piv[0] + 1, piv[1] - 1); dualPivotQuickSort(arr, piv[1] + 1, high); }} static int[] partition(int[] arr, int low, int high){ if (arr[low] > arr[high]) swap(arr, low, high); // p is the left pivot, and q // is the right pivot. int j = low + 1; int g = high - 1, k = low + 1, p = arr[low], q = arr[high]; while (k <= g) { // If elements are less than the left pivot if (arr[k] < p) { swap(arr, k, j); j++; } // If elements are greater than or equal // to the right pivot else if (arr[k] >= q) { while (arr[g] > q && k < g) g--; swap(arr, k, g); g--; if (arr[k] < p) { swap(arr, k, j); j++; } } k++; } j--; g++; // Bring pivots to their appropriate positions. swap(arr, low, j); swap(arr, high, g); // Returning the indices of the pivots // because we cannot return two elements // from a function, we do that using an array. return new int[] { j, g };} // Driver codepublic static void main(String[] args){ int[] arr = { 24, 8, 42, 75, 29, 77, 38, 57 }; dualPivotQuickSort(arr, 0, 7); System.out.print("Sorted array: "); for (int i = 0; i < 8; i++) System.out.print(arr[i] + " "); System.out.println();}} // This code is contributed by Gourish Sadhu
# Python3 program to implement# dual pivot QuickSortdef dualPivotQuickSort(arr, low, high): if low < high: # lp means left pivot and rp # means right pivot lp, rp = partition(arr, low, high) dualPivotQuickSort(arr, low, lp - 1) dualPivotQuickSort(arr, lp + 1, rp - 1) dualPivotQuickSort(arr, rp + 1, high) def partition(arr, low, high): if arr[low] > arr[high]: arr[low], arr[high] = arr[high], arr[low] # p is the left pivot, and q is the right pivot. j = k = low + 1 g, p, q = high - 1, arr[low], arr[high] while k <= g: # If elements are less than the left pivot if arr[k] < p: arr[k], arr[j] = arr[j], arr[k] j += 1 # If elements are greater than or equal # to the right pivot else if arr[k] >= q: while arr[g] > q and k < g: g -= 1 arr[k], arr[g] = arr[g], arr[k] g -= 1 if arr[k] < p: arr[k], arr[j] = arr[j], arr[k] j += 1 k += 1 j -= 1 g += 1 # Bring pivots to their appropriate positions. arr[low], arr[j] = arr[j], arr[low] arr[high], arr[g] = arr[g], arr[high] # Returning the indices of the pivots return j, g # Driver codearr = [ 24, 8, 42, 75, 29, 77, 38, 57 ]dualPivotQuickSort(arr, 0, 7) print('Sorted array: ', end = '')for i in arr: print(i, end = ' ') print() # This code is contributed by Gourish Sadhu
Output:
Sorted array: 8 24 29 38 42 57 75 77
This article is contributed by Shlomi Elhaiani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ManasChhabra2
SHUBHAMSINGH10
sadhu2gourish
simmytarika5
Quick Sort
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C++ Program for QuickSort
Stability in sorting algorithms
Quickselect Algorithm
Quick Sort vs Merge Sort
QuickSort using Random Pivoting
Sorting in Java
Check if two arrays are equal or not
Binary Insertion Sort
Recursive Bubble Sort
Sort a nearly sorted (or K sorted) array | [
{
"code": null,
"e": 24078,
"s": 24050,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 25079,
"s": 24078,
"text": "As we know, the single pivot quick sort takes a pivot from one of the ends of the array and partitioning the array, so that all elements are left to the pivot are less than or equal to the pivot, and all elements that are right to the pivot are greater than the pivot.The idea of dual pivot quick sort is to take two pivots, one in the left end of the array and the second, in the right end of the array. The left pivot must be less than or equal to the right pivot, so we swap them if necessary. Then, we begin partitioning the array into three parts: in the first part, all elements will be less than the left pivot, in the second part all elements will be greater or equal to the left pivot and also will be less than or equal to the right pivot, and in the third part all elements will be greater than the right pivot. Then, we shift the two pivots to their appropriate positions as we see in the below bar, and after that we begin quicksorting these three parts recursively, using this method. "
},
{
"code": null,
"e": 25296,
"s": 25079,
"text": "Dual pivot quick sort is a little bit faster than the original single pivot quicksort. But still, the worst case will remain O(n^2) when the array is already sorted in an increasing or decreasing order. An example: "
},
{
"code": null,
"e": 25300,
"s": 25296,
"text": "C++"
},
{
"code": null,
"e": 25302,
"s": 25300,
"text": "C"
},
{
"code": null,
"e": 25307,
"s": 25302,
"text": "Java"
},
{
"code": null,
"e": 25315,
"s": 25307,
"text": "Python3"
},
{
"code": "// C++ program to implement dual pivot QuickSort#include <iostream>using namespace std; int partition(int* arr, int low, int high, int* lp); void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} void DualPivotQuickSort(int* arr, int low, int high){ if (low < high) { // lp means left pivot, and rp means right pivot. int lp, rp; rp = partition(arr, low, high, &lp); DualPivotQuickSort(arr, low, lp - 1); DualPivotQuickSort(arr, lp + 1, rp - 1); DualPivotQuickSort(arr, rp + 1, high); }} int partition(int* arr, int low, int high, int* lp){ if (arr[low] > arr[high]) swap(&arr[low], &arr[high]); // p is the left pivot, and q is the right pivot. int j = low + 1; int g = high - 1, k = low + 1, p = arr[low], q = arr[high]; while (k <= g) { // if elements are less than the left pivot if (arr[k] < p) { swap(&arr[k], &arr[j]); j++; } // if elements are greater than or equal // to the right pivot else if (arr[k] >= q) { while (arr[g] > q && k < g) g--; swap(&arr[k], &arr[g]); g--; if (arr[k] < p) { swap(&arr[k], &arr[j]); j++; } } k++; } j--; g++; // bring pivots to their appropriate positions. swap(&arr[low], &arr[j]); swap(&arr[high], &arr[g]); // returning the indices of the pivots. *lp = j; // because we cannot return two elements // from a function. return g;} // Driver codeint main(){ int arr[] = { 24, 8, 42, 75, 29, 77, 38, 57 }; DualPivotQuickSort(arr, 0, 7); cout << \"Sorted array: \"; for (int i = 0; i < 8; i++) cout << arr[i] << \" \"; cout << endl;} // This code is contributed by SHUBHAMSINGH10",
"e": 27152,
"s": 25315,
"text": null
},
{
"code": "// C program to implement dual pivot QuickSort#include <stdio.h> int partition(int* arr, int low, int high, int* lp); void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} void DualPivotQuickSort(int* arr, int low, int high){ if (low < high) { // lp means left pivot, and rp means right pivot. int lp, rp; rp = partition(arr, low, high, &lp); DualPivotQuickSort(arr, low, lp - 1); DualPivotQuickSort(arr, lp + 1, rp - 1); DualPivotQuickSort(arr, rp + 1, high); }} int partition(int* arr, int low, int high, int* lp){ if (arr[low] > arr[high]) swap(&arr[low], &arr[high]); // p is the left pivot, and q is the right pivot. int j = low + 1; int g = high - 1, k = low + 1, p = arr[low], q = arr[high]; while (k <= g) { // if elements are less than the left pivot if (arr[k] < p) { swap(&arr[k], &arr[j]); j++; } // if elements are greater than or equal // to the right pivot else if (arr[k] >= q) { while (arr[g] > q && k < g) g--; swap(&arr[k], &arr[g]); g--; if (arr[k] < p) { swap(&arr[k], &arr[j]); j++; } } k++; } j--; g++; // bring pivots to their appropriate positions. swap(&arr[low], &arr[j]); swap(&arr[high], &arr[g]); // returning the indices of the pivots. *lp = j; // because we cannot return two elements // from a function. return g;} // Driver codeint main(){ int arr[] = { 24, 8, 42, 75, 29, 77, 38, 57 }; DualPivotQuickSort(arr, 0, 7); printf(\"Sorted array: \"); for (int i = 0; i < 8; i++) printf(\"%d \", arr[i]); printf(\"\\n\"); return 0;}",
"e": 28932,
"s": 27152,
"text": null
},
{
"code": "// Java program to implement// dual pivot QuickSortclass GFG{ static void swap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;} static void dualPivotQuickSort(int[] arr, int low, int high){ if (low < high) { // piv[] stores left pivot and right pivot. // piv[0] means left pivot and // piv[1] means right pivot int[] piv; piv = partition(arr, low, high); dualPivotQuickSort(arr, low, piv[0] - 1); dualPivotQuickSort(arr, piv[0] + 1, piv[1] - 1); dualPivotQuickSort(arr, piv[1] + 1, high); }} static int[] partition(int[] arr, int low, int high){ if (arr[low] > arr[high]) swap(arr, low, high); // p is the left pivot, and q // is the right pivot. int j = low + 1; int g = high - 1, k = low + 1, p = arr[low], q = arr[high]; while (k <= g) { // If elements are less than the left pivot if (arr[k] < p) { swap(arr, k, j); j++; } // If elements are greater than or equal // to the right pivot else if (arr[k] >= q) { while (arr[g] > q && k < g) g--; swap(arr, k, g); g--; if (arr[k] < p) { swap(arr, k, j); j++; } } k++; } j--; g++; // Bring pivots to their appropriate positions. swap(arr, low, j); swap(arr, high, g); // Returning the indices of the pivots // because we cannot return two elements // from a function, we do that using an array. return new int[] { j, g };} // Driver codepublic static void main(String[] args){ int[] arr = { 24, 8, 42, 75, 29, 77, 38, 57 }; dualPivotQuickSort(arr, 0, 7); System.out.print(\"Sorted array: \"); for (int i = 0; i < 8; i++) System.out.print(arr[i] + \" \"); System.out.println();}} // This code is contributed by Gourish Sadhu",
"e": 31033,
"s": 28932,
"text": null
},
{
"code": "# Python3 program to implement# dual pivot QuickSortdef dualPivotQuickSort(arr, low, high): if low < high: # lp means left pivot and rp # means right pivot lp, rp = partition(arr, low, high) dualPivotQuickSort(arr, low, lp - 1) dualPivotQuickSort(arr, lp + 1, rp - 1) dualPivotQuickSort(arr, rp + 1, high) def partition(arr, low, high): if arr[low] > arr[high]: arr[low], arr[high] = arr[high], arr[low] # p is the left pivot, and q is the right pivot. j = k = low + 1 g, p, q = high - 1, arr[low], arr[high] while k <= g: # If elements are less than the left pivot if arr[k] < p: arr[k], arr[j] = arr[j], arr[k] j += 1 # If elements are greater than or equal # to the right pivot else if arr[k] >= q: while arr[g] > q and k < g: g -= 1 arr[k], arr[g] = arr[g], arr[k] g -= 1 if arr[k] < p: arr[k], arr[j] = arr[j], arr[k] j += 1 k += 1 j -= 1 g += 1 # Bring pivots to their appropriate positions. arr[low], arr[j] = arr[j], arr[low] arr[high], arr[g] = arr[g], arr[high] # Returning the indices of the pivots return j, g # Driver codearr = [ 24, 8, 42, 75, 29, 77, 38, 57 ]dualPivotQuickSort(arr, 0, 7) print('Sorted array: ', end = '')for i in arr: print(i, end = ' ') print() # This code is contributed by Gourish Sadhu",
"e": 32646,
"s": 31033,
"text": null
},
{
"code": null,
"e": 32656,
"s": 32646,
"text": "Output: "
},
{
"code": null,
"e": 32694,
"s": 32656,
"text": "Sorted array: 8 24 29 38 42 57 75 77 "
},
{
"code": null,
"e": 33118,
"s": 32694,
"text": "This article is contributed by Shlomi Elhaiani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33132,
"s": 33118,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 33147,
"s": 33132,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 33161,
"s": 33147,
"text": "sadhu2gourish"
},
{
"code": null,
"e": 33174,
"s": 33161,
"text": "simmytarika5"
},
{
"code": null,
"e": 33185,
"s": 33174,
"text": "Quick Sort"
},
{
"code": null,
"e": 33193,
"s": 33185,
"text": "Sorting"
},
{
"code": null,
"e": 33201,
"s": 33193,
"text": "Sorting"
},
{
"code": null,
"e": 33299,
"s": 33201,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33308,
"s": 33299,
"text": "Comments"
},
{
"code": null,
"e": 33321,
"s": 33308,
"text": "Old Comments"
},
{
"code": null,
"e": 33347,
"s": 33321,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 33379,
"s": 33347,
"text": "Stability in sorting algorithms"
},
{
"code": null,
"e": 33401,
"s": 33379,
"text": "Quickselect Algorithm"
},
{
"code": null,
"e": 33426,
"s": 33401,
"text": "Quick Sort vs Merge Sort"
},
{
"code": null,
"e": 33458,
"s": 33426,
"text": "QuickSort using Random Pivoting"
},
{
"code": null,
"e": 33474,
"s": 33458,
"text": "Sorting in Java"
},
{
"code": null,
"e": 33511,
"s": 33474,
"text": "Check if two arrays are equal or not"
},
{
"code": null,
"e": 33533,
"s": 33511,
"text": "Binary Insertion Sort"
},
{
"code": null,
"e": 33555,
"s": 33533,
"text": "Recursive Bubble Sort"
}
] |
How to remove all rows from a table in JavaScript ? - GeeksforGeeks | 31 Jul, 2019
Given an HTML document which contains an HTML table and the task is to remove all rows from the HTML table. Removing all rows is different from removing the few rows. This can be done by using JavaScript.
Approach
First of all set the ID or unique class to the table.
Select the table element and use remove() or detach() method to delete the all table rows.
Example 1: In this example, All rows are deleted by using remove() method.
<!DOCTYPE HTML><html> <head> <title> How to remove all rows from a table in JavaScript ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> #myCol { background: green; } table { color: white; margin-left: 150px; } #Geek_p { color: green; font-size: 30px; } td { padding: 10px; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <table id="table"> <colgroup> <col id="myCol" span="2"> <col style="background-color:green"> </colgroup> <tr> <th>S.No</th> <th>Title</th> <th>Geek_id</th> </tr> <tr id="row1"> <td>Geek_1</td> <td>GeekForGeeks</td> <th>Geek_id_1</th> </tr> <tr> <td>Geek_2</td> <td>GeeksForGeeks</td> <th>Geek_id_2</th> </tr> <tr> <td>Geek_3</td> <td>GeeksForGeeks</td> <th>Geek_id_3</th> </tr> <tr> <td>Geek_4</td> <td>GeeksForGeeks</td> <th>Geek_id_4</th> </tr> </table> <br> <button onclick="Geeks()"> Click here </button> <p id="GFG_DOWN" style=" color:green; font-size: 20px; font-weight: bold;"> </p> <script> function Geeks() { $("#table").remove(); $("#GFG_DOWN").text ("All rows of the table are deleted."); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: In this example, All rows are deleted by using detach() method.
<!DOCTYPE HTML><html> <head> <title> How to remove all rows from a table in JavaScript ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> #myCol { background: green; } table { color: white; margin-left: 150px; } #Geek_p { color: green; font-size: 30px; } td { padding: 10px; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <table id="table"> <colgroup> <col id="myCol" span="2"> <col style="background-color:green"> </colgroup> <tr id="thead"> <th>S.No</th> <th>Title</th> <th>Geek_id</th> </tr> <tr id="row1"> <td>Geek_1</td> <td>GeekForGeeks</td> <th>Geek_id_1</th> </tr> <tr> <td>Geek_2</td> <td>GeeksForGeeks</td> <th>Geek_id_2</th> </tr> <tr> <td>Geek_3</td> <td>GeeksForGeeks</td> <th>Geek_id_3</th> </tr> <tr> <td>Geek_4</td> <td>GeeksForGeeks</td> <th>Geek_id_4</th> </tr> </table> <br> <button onclick="Geeks()"> Click here </button> <p id="GFG_DOWN" style= "color:green; font-size: 20px; font-weight: bold;"> </p> <script> function Geeks() { $('#table').detach(); $("#GFG_DOWN").text ("All rows of the table are deleted."); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26105,
"s": 26077,
"text": "\n31 Jul, 2019"
},
{
"code": null,
"e": 26310,
"s": 26105,
"text": "Given an HTML document which contains an HTML table and the task is to remove all rows from the HTML table. Removing all rows is different from removing the few rows. This can be done by using JavaScript."
},
{
"code": null,
"e": 26319,
"s": 26310,
"text": "Approach"
},
{
"code": null,
"e": 26373,
"s": 26319,
"text": "First of all set the ID or unique class to the table."
},
{
"code": null,
"e": 26464,
"s": 26373,
"text": "Select the table element and use remove() or detach() method to delete the all table rows."
},
{
"code": null,
"e": 26539,
"s": 26464,
"text": "Example 1: In this example, All rows are deleted by using remove() method."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to remove all rows from a table in JavaScript ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <style> #myCol { background: green; } table { color: white; margin-left: 150px; } #Geek_p { color: green; font-size: 30px; } td { padding: 10px; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <table id=\"table\"> <colgroup> <col id=\"myCol\" span=\"2\"> <col style=\"background-color:green\"> </colgroup> <tr> <th>S.No</th> <th>Title</th> <th>Geek_id</th> </tr> <tr id=\"row1\"> <td>Geek_1</td> <td>GeekForGeeks</td> <th>Geek_id_1</th> </tr> <tr> <td>Geek_2</td> <td>GeeksForGeeks</td> <th>Geek_id_2</th> </tr> <tr> <td>Geek_3</td> <td>GeeksForGeeks</td> <th>Geek_id_3</th> </tr> <tr> <td>Geek_4</td> <td>GeeksForGeeks</td> <th>Geek_id_4</th> </tr> </table> <br> <button onclick=\"Geeks()\"> Click here </button> <p id=\"GFG_DOWN\" style=\" color:green; font-size: 20px; font-weight: bold;\"> </p> <script> function Geeks() { $(\"#table\").remove(); $(\"#GFG_DOWN\").text (\"All rows of the table are deleted.\"); } </script></body> </html>",
"e": 28276,
"s": 26539,
"text": null
},
{
"code": null,
"e": 28284,
"s": 28276,
"text": "Output:"
},
{
"code": null,
"e": 28315,
"s": 28284,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 28345,
"s": 28315,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28420,
"s": 28345,
"text": "Example 2: In this example, All rows are deleted by using detach() method."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to remove all rows from a table in JavaScript ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <style> #myCol { background: green; } table { color: white; margin-left: 150px; } #Geek_p { color: green; font-size: 30px; } td { padding: 10px; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <table id=\"table\"> <colgroup> <col id=\"myCol\" span=\"2\"> <col style=\"background-color:green\"> </colgroup> <tr id=\"thead\"> <th>S.No</th> <th>Title</th> <th>Geek_id</th> </tr> <tr id=\"row1\"> <td>Geek_1</td> <td>GeekForGeeks</td> <th>Geek_id_1</th> </tr> <tr> <td>Geek_2</td> <td>GeeksForGeeks</td> <th>Geek_id_2</th> </tr> <tr> <td>Geek_3</td> <td>GeeksForGeeks</td> <th>Geek_id_3</th> </tr> <tr> <td>Geek_4</td> <td>GeeksForGeeks</td> <th>Geek_id_4</th> </tr> </table> <br> <button onclick=\"Geeks()\"> Click here </button> <p id=\"GFG_DOWN\" style= \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> function Geeks() { $('#table').detach(); $(\"#GFG_DOWN\").text (\"All rows of the table are deleted.\"); } </script></body> </html>",
"e": 30194,
"s": 28420,
"text": null
},
{
"code": null,
"e": 30202,
"s": 30194,
"text": "Output:"
},
{
"code": null,
"e": 30233,
"s": 30202,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 30263,
"s": 30233,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 30279,
"s": 30263,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 30290,
"s": 30279,
"text": "JavaScript"
},
{
"code": null,
"e": 30307,
"s": 30290,
"text": "Web Technologies"
},
{
"code": null,
"e": 30334,
"s": 30307,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30432,
"s": 30334,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30472,
"s": 30432,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30517,
"s": 30472,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30578,
"s": 30517,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30650,
"s": 30578,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30691,
"s": 30650,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30731,
"s": 30691,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30764,
"s": 30731,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30809,
"s": 30764,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30852,
"s": 30809,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to set the Text in TextBox in C#? - GeeksforGeeks | 29 Nov, 2019
In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the text associated with the TextBox by using the Text property of the TextBox. In Windows form, you can set this property in two different ways:
1. Design-Time: It is the simplest way to set the Text property of the TextBox as shown in the following steps:
Step 1: Create a windows form.Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the TextBox control from the ToolBox and Drop it on the windows form. You can place TextBox anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the TextBox control to set the Text property of the TextBox.Output:
Output:
2. Run-Time: It is a little bit tricky than the above method. In this method, you can set the Text property of the TextBox programmatically with the help of given syntax:
public override string Text { get; set; }
Here, the text is represented in the form of String. Following steps are used to set the Text property of the TextBox:
Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox
TextBox Mytextbox = new TextBox();
// Creating textbox
TextBox Mytextbox = new TextBox();
Step 2 : After creating TextBox set the Text property of the TextBox provided by the TextBox class.// Set Text property
Mytextbox.Text = "Enter City Name...";
// Set Text property
Mytextbox.Text = "Enter City Name...";
Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form
this.Controls.Add(Mytextbox);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "City"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = "text_box1"; Mytextbox.Text = "Enter City Name..."; // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output:
// Add this textbox to form
this.Controls.Add(Mytextbox);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "City"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = "text_box1"; Mytextbox.Text = "Enter City Name..."; // Add this textbox to form this.Controls.Add(Mytextbox); }}}
Output:
CSharp-Windows-Forms-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Method Overriding
C# Dictionary with examples
C# | Delegates
Difference between Ref and Out keywords in C#
Destructors in C#
Extension Method in C#
C# | Constructors
Introduction to .NET Framework
C# | String.IndexOf( ) Method | Set - 1
C# | Abstract Classes | [
{
"code": null,
"e": 23988,
"s": 23960,
"text": "\n29 Nov, 2019"
},
{
"code": null,
"e": 24339,
"s": 23988,
"text": "In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the text associated with the TextBox by using the Text property of the TextBox. In Windows form, you can set this property in two different ways:"
},
{
"code": null,
"e": 24451,
"s": 24339,
"text": "1. Design-Time: It is the simplest way to set the Text property of the TextBox as shown in the following steps:"
},
{
"code": null,
"e": 24539,
"s": 24451,
"text": "Step 1: Create a windows form.Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 24697,
"s": 24539,
"text": "Step 2: Drag the TextBox control from the ToolBox and Drop it on the windows form. You can place TextBox anywhere on the windows form according to your need."
},
{
"code": null,
"e": 24826,
"s": 24697,
"text": "Step 3: After drag and drop you will go to the properties of the TextBox control to set the Text property of the TextBox.Output:"
},
{
"code": null,
"e": 24834,
"s": 24826,
"text": "Output:"
},
{
"code": null,
"e": 25005,
"s": 24834,
"text": "2. Run-Time: It is a little bit tricky than the above method. In this method, you can set the Text property of the TextBox programmatically with the help of given syntax:"
},
{
"code": null,
"e": 25047,
"s": 25005,
"text": "public override string Text { get; set; }"
},
{
"code": null,
"e": 25166,
"s": 25047,
"text": "Here, the text is represented in the form of String. Following steps are used to set the Text property of the TextBox:"
},
{
"code": null,
"e": 25310,
"s": 25166,
"text": "Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox\nTextBox Mytextbox = new TextBox();\n"
},
{
"code": null,
"e": 25366,
"s": 25310,
"text": "// Creating textbox\nTextBox Mytextbox = new TextBox();\n"
},
{
"code": null,
"e": 25526,
"s": 25366,
"text": "Step 2 : After creating TextBox set the Text property of the TextBox provided by the TextBox class.// Set Text property\nMytextbox.Text = \"Enter City Name...\";\n"
},
{
"code": null,
"e": 25587,
"s": 25526,
"text": "// Set Text property\nMytextbox.Text = \"Enter City Name...\";\n"
},
{
"code": null,
"e": 26875,
"s": 25587,
"text": "Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form\nthis.Controls.Add(Mytextbox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"City\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = \"text_box1\"; Mytextbox.Text = \"Enter City Name...\"; // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output:"
},
{
"code": null,
"e": 26934,
"s": 26875,
"text": "// Add this textbox to form\nthis.Controls.Add(Mytextbox);\n"
},
{
"code": null,
"e": 26943,
"s": 26934,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"City\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = \"text_box1\"; Mytextbox.Text = \"Enter City Name...\"; // Add this textbox to form this.Controls.Add(Mytextbox); }}}",
"e": 28088,
"s": 26943,
"text": null
},
{
"code": null,
"e": 28096,
"s": 28088,
"text": "Output:"
},
{
"code": null,
"e": 28127,
"s": 28096,
"text": "CSharp-Windows-Forms-Namespace"
},
{
"code": null,
"e": 28130,
"s": 28127,
"text": "C#"
},
{
"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": 28251,
"s": 28228,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28279,
"s": 28251,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 28294,
"s": 28279,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28340,
"s": 28294,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28358,
"s": 28340,
"text": "Destructors in C#"
},
{
"code": null,
"e": 28381,
"s": 28358,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28399,
"s": 28381,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28430,
"s": 28399,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28470,
"s": 28430,
"text": "C# | String.IndexOf( ) Method | Set - 1"
}
] |
Spring Boot - Apache Kafka | Apache Kafka is an open source project used to publish and subscribe the messages based on the fault-tolerant messaging system. It is fast, scalable and distributed by design. If you are a beginner to Kafka, or want to gain a better understanding on it, please refer to this link − www.tutorialspoint.com/apache_kafka/
In this chapter, we are going to see how to implement the Apache Kafka in Spring Boot application.
First, we need to add the Spring Kafka dependency in our build configuration file.
Maven users can add the following dependency in the pom.xml file.
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
Gradle users can add the following dependency in the build.gradle file.
compile group: 'org.springframework.kafka', name: 'spring-kafka', version: '2.1.0.RELEASE'
To produce messages into Apache Kafka, we need to define the Configuration class for Producer configuration as shown −
package com.tutorialspoint.kafkademo;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
@Configuration
public class KafkaProducerConfig {
@Bean
public ProducerFactory<String, String> producerFactory() {
Map<String, Object> configProps = new HashMap<>();
configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
return new DefaultKafkaProducerFactory<>(configProps);
}
@Bean
public KafkaTemplate<String, String> kafkaTemplate() {
return new KafkaTemplate<>(producerFactory());
}
}
To publish a message, auto wire the Kafka Template object and produce the message as shown.
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String msg) {
kafkaTemplate.send(topicName, msg);
}
To consume messages, we need to write a Consumer configuration class file as shown below.
package com.tutorialspoint.kafkademo;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
@EnableKafka
@Configuration
public class KafkaConsumerConfig {
@Bean
public ConsumerFactory<String, String> consumerFactory() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:2181");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "group-id");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
return new DefaultKafkaConsumerFactory<>(props);
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String>
factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
return factory;
}
}
Next, write a Listener to listen to the messages.
@KafkaListener(topics = "tutorialspoint", groupId = "group-id")
public void listen(String message) {
System.out.println("Received Messasge in group - group-id: " + message);
}
Let us call the sendMessage() method from ApplicationRunner class run method from the main Spring Boot application class file and consume the message from the same class file.
Your main Spring Boot application class file code is given below −
package com.tutorialspoint.kafkademo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
@SpringBootApplication
public class KafkaDemoApplication implements ApplicationRunner {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String msg) {
kafkaTemplate.send("tutorialspoint", msg);
}
public static void main(String[] args) {
SpringApplication.run(KafkaDemoApplication.class, args);
}
@KafkaListener(topics = "tutorialspoint", groupId = "group-id")
public void listen(String message) {
System.out.println("Received Messasge in group - group-id: " + message);
}
@Override
public void run(ApplicationArguments args) throws Exception {
sendMessage("Hi Welcome to Spring For Apache Kafka");
}
}
The code for complete build configuration file is given below.
Maven – pom.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>kafka-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>kafka-demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compile group: 'org.springframework.kafka', name: 'spring-kafka', version: '2.1.0.RELEASE'
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Now, create an executable JAR file, and run the Spring Boot application by using the below Maven or Gradle commands as shown −
For Maven, use the command as shown −
mvn clean install
After “BUILD SUCCESS”, you can find the JAR file under the target directory.
For Gradle, use the command as shown −
gradle clean build
After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.
Run the JAR file by using the command given here −
java –jar <JARFILE>
You can see the output in console window.
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3344,
"s": 3025,
"text": "Apache Kafka is an open source project used to publish and subscribe the messages based on the fault-tolerant messaging system. It is fast, scalable and distributed by design. If you are a beginner to Kafka, or want to gain a better understanding on it, please refer to this link − www.tutorialspoint.com/apache_kafka/"
},
{
"code": null,
"e": 3443,
"s": 3344,
"text": "In this chapter, we are going to see how to implement the Apache Kafka in Spring Boot application."
},
{
"code": null,
"e": 3527,
"s": 3443,
"text": "First, we need to add the Spring Kafka dependency in our build configuration file. "
},
{
"code": null,
"e": 3593,
"s": 3527,
"text": "Maven users can add the following dependency in the pom.xml file."
},
{
"code": null,
"e": 3745,
"s": 3593,
"text": "<dependency>\n <groupId>org.springframework.kafka</groupId>\n <artifactId>spring-kafka</artifactId>\n <version>2.1.0.RELEASE</version>\n</dependency>"
},
{
"code": null,
"e": 3817,
"s": 3745,
"text": "Gradle users can add the following dependency in the build.gradle file."
},
{
"code": null,
"e": 3909,
"s": 3817,
"text": "compile group: 'org.springframework.kafka', name: 'spring-kafka', version: '2.1.0.RELEASE'\n"
},
{
"code": null,
"e": 4028,
"s": 3909,
"text": "To produce messages into Apache Kafka, we need to define the Configuration class for Producer configuration as shown −"
},
{
"code": null,
"e": 5162,
"s": 4028,
"text": "package com.tutorialspoint.kafkademo;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.kafka.clients.producer.ProducerConfig;\nimport org.apache.kafka.common.serialization.StringSerializer;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.kafka.core.DefaultKafkaProducerFactory;\nimport org.springframework.kafka.core.KafkaTemplate;\nimport org.springframework.kafka.core.ProducerFactory;\n\n@Configuration\npublic class KafkaProducerConfig {\n @Bean\n public ProducerFactory<String, String> producerFactory() {\n Map<String, Object> configProps = new HashMap<>();\n configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, \"localhost:9092\");\n configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);\n configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);\n return new DefaultKafkaProducerFactory<>(configProps);\n }\n @Bean\n public KafkaTemplate<String, String> kafkaTemplate() {\n return new KafkaTemplate<>(producerFactory());\n }\n}"
},
{
"code": null,
"e": 5254,
"s": 5162,
"text": "To publish a message, auto wire the Kafka Template object and produce the message as shown."
},
{
"code": null,
"e": 5402,
"s": 5254,
"text": "@Autowired\nprivate KafkaTemplate<String, String> kafkaTemplate;\n \npublic void sendMessage(String msg) {\n kafkaTemplate.send(topicName, msg);\n} "
},
{
"code": null,
"e": 5492,
"s": 5402,
"text": "To consume messages, we need to write a Consumer configuration class file as shown below."
},
{
"code": null,
"e": 6963,
"s": 5492,
"text": "package com.tutorialspoint.kafkademo;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.kafka.clients.consumer.ConsumerConfig;\nimport org.apache.kafka.common.serialization.StringDeserializer;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.kafka.annotation.EnableKafka;\nimport org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;\nimport org.springframework.kafka.core.ConsumerFactory;\nimport org.springframework.kafka.core.DefaultKafkaConsumerFactory;\n\n@EnableKafka\n@Configuration\npublic class KafkaConsumerConfig {\n @Bean\n public ConsumerFactory<String, String> consumerFactory() {\n Map<String, Object> props = new HashMap<>();\n props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, \"localhost:2181\");\n props.put(ConsumerConfig.GROUP_ID_CONFIG, \"group-id\");\n props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);\n props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);\n return new DefaultKafkaConsumerFactory<>(props);\n }\n @Bean\n public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {\n ConcurrentKafkaListenerContainerFactory<String, String> \n factory = new ConcurrentKafkaListenerContainerFactory<>();\n factory.setConsumerFactory(consumerFactory());\n return factory;\n }\n} "
},
{
"code": null,
"e": 7013,
"s": 6963,
"text": "Next, write a Listener to listen to the messages."
},
{
"code": null,
"e": 7192,
"s": 7013,
"text": "@KafkaListener(topics = \"tutorialspoint\", groupId = \"group-id\")\npublic void listen(String message) {\n System.out.println(\"Received Messasge in group - group-id: \" + message);\n}"
},
{
"code": null,
"e": 7368,
"s": 7192,
"text": "Let us call the sendMessage() method from ApplicationRunner class run method from the main Spring Boot application class file and consume the message from the same class file."
},
{
"code": null,
"e": 7435,
"s": 7368,
"text": "Your main Spring Boot application class file code is given below −"
},
{
"code": null,
"e": 8577,
"s": 7435,
"text": "package com.tutorialspoint.kafkademo;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.ApplicationArguments;\nimport org.springframework.boot.ApplicationRunner;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.kafka.annotation.KafkaListener;\nimport org.springframework.kafka.core.KafkaTemplate;\n\n@SpringBootApplication\npublic class KafkaDemoApplication implements ApplicationRunner {\n @Autowired\n private KafkaTemplate<String, String> kafkaTemplate;\n\n public void sendMessage(String msg) {\n kafkaTemplate.send(\"tutorialspoint\", msg);\n }\n public static void main(String[] args) {\n SpringApplication.run(KafkaDemoApplication.class, args);\n }\n @KafkaListener(topics = \"tutorialspoint\", groupId = \"group-id\")\n public void listen(String message) {\n System.out.println(\"Received Messasge in group - group-id: \" + message);\n }\n @Override\n public void run(ApplicationArguments args) throws Exception {\n sendMessage(\"Hi Welcome to Spring For Apache Kafka\");\n }\n}"
},
{
"code": null,
"e": 8640,
"s": 8577,
"text": "The code for complete build configuration file is given below."
},
{
"code": null,
"e": 8656,
"s": 8640,
"text": "Maven – pom.xml"
},
{
"code": null,
"e": 10431,
"s": 8656,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint</groupId>\n <artifactId>kafka-demo</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>kafka-demo</name>\n <description>Demo project for Spring Boot</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.9.RELEASE</version>\n <relativePath /> <!-- lookup parent from repository -->\n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.kafka</groupId>\n <artifactId>spring-kafka</artifactId>\n <version>2.1.0.RELEASE</version>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n </dependencies>\n\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n \n</project>"
},
{
"code": null,
"e": 10453,
"s": 10431,
"text": "Gradle – build.gradle"
},
{
"code": null,
"e": 11130,
"s": 10453,
"text": "buildscript {\n ext {\n springBootVersion = '1.5.9.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\n\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\n\ngroup = 'com.tutorialspoint'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n}\ndependencies {\n compile('org.springframework.boot:spring-boot-starter')\n compile group: 'org.springframework.kafka', name: 'spring-kafka', version: '2.1.0.RELEASE'\n testCompile('org.springframework.boot:spring-boot-starter-test')\n} "
},
{
"code": null,
"e": 11257,
"s": 11130,
"text": "Now, create an executable JAR file, and run the Spring Boot application by using the below Maven or Gradle commands as shown −"
},
{
"code": null,
"e": 11295,
"s": 11257,
"text": "For Maven, use the command as shown −"
},
{
"code": null,
"e": 11314,
"s": 11295,
"text": "mvn clean install\n"
},
{
"code": null,
"e": 11391,
"s": 11314,
"text": "After “BUILD SUCCESS”, you can find the JAR file under the target directory."
},
{
"code": null,
"e": 11430,
"s": 11391,
"text": "For Gradle, use the command as shown −"
},
{
"code": null,
"e": 11450,
"s": 11430,
"text": "gradle clean build\n"
},
{
"code": null,
"e": 11534,
"s": 11450,
"text": "After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory."
},
{
"code": null,
"e": 11585,
"s": 11534,
"text": "Run the JAR file by using the command given here −"
},
{
"code": null,
"e": 11607,
"s": 11585,
"text": "java –jar <JARFILE> \n"
},
{
"code": null,
"e": 11649,
"s": 11607,
"text": "You can see the output in console window."
},
{
"code": null,
"e": 11683,
"s": 11649,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 11697,
"s": 11683,
"text": " Karthikeya T"
},
{
"code": null,
"e": 11730,
"s": 11697,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 11745,
"s": 11730,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 11780,
"s": 11745,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 11792,
"s": 11780,
"text": " Senol Atac"
},
{
"code": null,
"e": 11827,
"s": 11792,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11839,
"s": 11827,
"text": " Senol Atac"
},
{
"code": null,
"e": 11874,
"s": 11839,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11886,
"s": 11874,
"text": " Senol Atac"
},
{
"code": null,
"e": 11919,
"s": 11886,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 11931,
"s": 11919,
"text": " Senol Atac"
},
{
"code": null,
"e": 11938,
"s": 11931,
"text": " Print"
},
{
"code": null,
"e": 11949,
"s": 11938,
"text": " Add Notes"
}
] |
Python PostgreSQL - Introduction | PostgreSQL is a powerful, open source object-relational database system. It has more than 15 years of active development phase and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness.
To communicate with PostgreSQL using Python you need to install psycopg, an adapter provided for python programming, the current version of this is psycog2.
psycopg2 was written with the aim of being very small and fast, and stable as a rock. It is available under PIP (package manager of python)
First of all, make sure python and PIP is installed in your system properly and, PIP is up-to-date.
To upgrade PIP, open command prompt and execute the following command −
C:\Users\Tutorialspoint>python -m pip install --upgrade pip
Collecting pip
Using cached https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl
Installing collected packages: pip
Found existing installation: pip 19.0.3
Uninstalling pip-19.0.3:
Successfully uninstalled pip-19.0.3
Successfully installed pip-19.2.2
Then, open command prompt in admin mode and execute the pip install psycopg2-binary command as shown below −
C:\WINDOWS\system32>pip install psycopg2-binary
Collecting psycopg2-binary
Using cached https://files.pythonhosted.org/packages/80/79/d0d13ce4c2f1addf4786f4a2ded802c2df66ddf3c1b1a982ed8d4cb9fc6d/psycopg2_binary-2.8.3-cp37-cp37m-win32.whl
Installing collected packages: psycopg2-binary
Successfully installed psycopg2-binary-2.8.3
To verify the installation, create a sample python script with the following line in it.
import mysql.connector
If the installation is successful, when you execute it, you should not get any errors −
D:\Python_PostgreSQL>import psycopg2
D:\Python_PostgreSQL>
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": 3447,
"s": 3205,
"text": "PostgreSQL is a powerful, open source object-relational database system. It has more than 15 years of active development phase and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness."
},
{
"code": null,
"e": 3604,
"s": 3447,
"text": "To communicate with PostgreSQL using Python you need to install psycopg, an adapter provided for python programming, the current version of this is psycog2."
},
{
"code": null,
"e": 3744,
"s": 3604,
"text": "psycopg2 was written with the aim of being very small and fast, and stable as a rock. It is available under PIP (package manager of python)"
},
{
"code": null,
"e": 3844,
"s": 3744,
"text": "First of all, make sure python and PIP is installed in your system properly and, PIP is up-to-date."
},
{
"code": null,
"e": 3916,
"s": 3844,
"text": "To upgrade PIP, open command prompt and execute the following command −"
},
{
"code": null,
"e": 4314,
"s": 3916,
"text": "C:\\Users\\Tutorialspoint>python -m pip install --upgrade pip\nCollecting pip\nUsing cached https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl\nInstalling collected packages: pip\nFound existing installation: pip 19.0.3\nUninstalling pip-19.0.3:\nSuccessfully uninstalled pip-19.0.3\nSuccessfully installed pip-19.2.2\n"
},
{
"code": null,
"e": 4423,
"s": 4314,
"text": "Then, open command prompt in admin mode and execute the pip install psycopg2-binary command as shown below −"
},
{
"code": null,
"e": 4754,
"s": 4423,
"text": "C:\\WINDOWS\\system32>pip install psycopg2-binary\nCollecting psycopg2-binary\nUsing cached https://files.pythonhosted.org/packages/80/79/d0d13ce4c2f1addf4786f4a2ded802c2df66ddf3c1b1a982ed8d4cb9fc6d/psycopg2_binary-2.8.3-cp37-cp37m-win32.whl\nInstalling collected packages: psycopg2-binary\nSuccessfully installed psycopg2-binary-2.8.3\n"
},
{
"code": null,
"e": 4843,
"s": 4754,
"text": "To verify the installation, create a sample python script with the following line in it."
},
{
"code": null,
"e": 4867,
"s": 4843,
"text": "import mysql.connector\n"
},
{
"code": null,
"e": 4955,
"s": 4867,
"text": "If the installation is successful, when you execute it, you should not get any errors −"
},
{
"code": null,
"e": 5015,
"s": 4955,
"text": "D:\\Python_PostgreSQL>import psycopg2\nD:\\Python_PostgreSQL>\n"
},
{
"code": null,
"e": 5052,
"s": 5015,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5068,
"s": 5052,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5101,
"s": 5068,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5120,
"s": 5101,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5155,
"s": 5120,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 5177,
"s": 5155,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 5211,
"s": 5177,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5239,
"s": 5211,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5274,
"s": 5239,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5288,
"s": 5274,
"text": " Lets Kode It"
},
{
"code": null,
"e": 5321,
"s": 5288,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5338,
"s": 5321,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5345,
"s": 5338,
"text": " Print"
},
{
"code": null,
"e": 5356,
"s": 5345,
"text": " Add Notes"
}
] |
Kubernetes - Network Policy | Network Policy defines how the pods in the same namespace will communicate with each other and the network endpoint. It requires extensions/v1beta1/networkpolicies to be enabled in the runtime configuration in the API server. Its resources use labels to select the pods and define rules to allow traffic to a specific pod in addition to which is defined in the namespace.
First, we need to configure Namespace Isolation Policy. Basically, this kind of networking policies are required on the load balancers.
kind: Namespace
apiVersion: v1
metadata:
annotations:
net.beta.kubernetes.io/network-policy: |
{
"ingress":
{
"isolation": "DefaultDeny"
}
}
$ kubectl annotate ns <namespace> "net.beta.kubernetes.io/network-policy =
{\"ingress\": {\"isolation\": \"DefaultDeny\"}}"
Once the namespace is created, we need to create the Network Policy.
kind: NetworkPolicy
apiVersion: extensions/v1beta1
metadata:
name: allow-frontend
namespace: myns
spec:
podSelector:
matchLabels:
role: backend
ingress:
- from:
- podSelector:
matchLabels:
role: frontend
ports:
- protocol: TCP
port: 6379
41 Lectures
5 hours
AR Shankar
15 Lectures
2 hours
Harshit Srivastava, Pranjal Srivastava
18 Lectures
1.5 hours
Nigel Poulton
25 Lectures
1.5 hours
Pranjal Srivastava
18 Lectures
1 hours
Pranjal Srivastava
26 Lectures
1.5 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2567,
"s": 2195,
"text": "Network Policy defines how the pods in the same namespace will communicate with each other and the network endpoint. It requires extensions/v1beta1/networkpolicies to be enabled in the runtime configuration in the API server. Its resources use labels to select the pods and define rules to allow traffic to a specific pod in addition to which is defined in the namespace."
},
{
"code": null,
"e": 2703,
"s": 2567,
"text": "First, we need to configure Namespace Isolation Policy. Basically, this kind of networking policies are required on the load balancers."
},
{
"code": null,
"e": 2906,
"s": 2703,
"text": "kind: Namespace\napiVersion: v1\nmetadata:\n annotations:\n net.beta.kubernetes.io/network-policy: |\n {\n \"ingress\": \n {\n \"isolation\": \"DefaultDeny\"\n }\n }\n"
},
{
"code": null,
"e": 3032,
"s": 2906,
"text": "$ kubectl annotate ns <namespace> \"net.beta.kubernetes.io/network-policy = \n{\\\"ingress\\\": {\\\"isolation\\\": \\\"DefaultDeny\\\"}}\"\n"
},
{
"code": null,
"e": 3101,
"s": 3032,
"text": "Once the namespace is created, we need to create the Network Policy."
},
{
"code": null,
"e": 3415,
"s": 3101,
"text": "kind: NetworkPolicy\napiVersion: extensions/v1beta1\nmetadata:\n name: allow-frontend\n namespace: myns\nspec:\n podSelector:\n matchLabels:\n role: backend\n ingress:\n - from:\n - podSelector:\n matchLabels:\n role: frontend\n ports:\n - protocol: TCP\n port: 6379\n"
},
{
"code": null,
"e": 3448,
"s": 3415,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3460,
"s": 3448,
"text": " AR Shankar"
},
{
"code": null,
"e": 3493,
"s": 3460,
"text": "\n 15 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3533,
"s": 3493,
"text": " Harshit Srivastava, Pranjal Srivastava"
},
{
"code": null,
"e": 3568,
"s": 3533,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3583,
"s": 3568,
"text": " Nigel Poulton"
},
{
"code": null,
"e": 3618,
"s": 3583,
"text": "\n 25 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3638,
"s": 3618,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3671,
"s": 3638,
"text": "\n 18 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3691,
"s": 3671,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3726,
"s": 3691,
"text": "\n 26 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3746,
"s": 3726,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3753,
"s": 3746,
"text": " Print"
},
{
"code": null,
"e": 3764,
"s": 3753,
"text": " Add Notes"
}
] |
LeetCode Longest Substring Without Repetition Solution in Python | Towards Data Science | LeetCode is a platform that gives access to numerous coding problems that are usually asked in technical interviews of tech giants such as Google, Meta and Amazon for Engineering and Machine Learning positions.
In today’s article, we are going to explore a couple of approaches for the third problem on LeetCode problem which is of medium difficulty level and is called “Longest substring without repetition”.
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"Output: 3Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"Output: 1Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"Output: 3Explanation: The answer is "wke", with the length of 3.Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Example 4:
Input: s = ""Output: 0
Constraints:
0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.
Source: LeetCode
The most intuitive approach to the problem would be to perform a brute force search by using two nested loops.
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: longest_str = "" for i, c in enumerate(s): canditate_str = str(c) for j in range(i + 1, len(s)): if s[j] not in canditate_str: canditate_str += str(s[j]) else: break if len(canditate_str) > len(longest_str): longest_str = canditate_str if len(s) - i <= len(longest_str): break return len(longest_str)
Even though the above algorithm would solve the problem in question, the time complexity — which in this case is O(n2) — is an issue as we can definitely do better than this.
Now in order to improve the previous answer, we need to somehow make a single pass over the string containing the characters. One approach that could help us do so is the so called sliding window.
To make clear what I mean with sliding window, let’s consider the following string below (at the top we show the index of each individual character):
# 0 1 2 3 4 5 6 7 # a b c a b c b b
A sliding window has a starting and ending indices:
# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |
Depending on the algorithm, the starting and ending indices will move accordingly. In our case, we would want the sliding window to be created and move forward as illustrated below.
# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |
An algorithm that can reflect the logic described in the diagram/code below is shown below. We use a Hash Map (i.e. a Python dictionary) where keys correspond to characters seen so far, and values to the index this particular character was last seen.
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: chars = {} start = 0 max_length = 0 for end, c in enumerate(s): if c in chars: start = max(start, chars[c] + 1) max_length = max(max_length, end - start + 1) chars[c] = end return max_length
Now in terms of complexity, we made a significant improvement compared to the brute force approach since now we iterate over the string only once and thus the time complexity of our solution is O(n).
In today’s article we walked through a couple of potential solutions to the third problem on LeetCode platform called “Longest substring without repetition”.
We initially created a less optimal solution that involves brute force by creating two nested loops in order to identify which substring in the input string is the longest one.
Finally, we optimised the algorithm by using sliding windows and hash maps (i.e. Python dictionaries) so that we will need to made just a single pass over the string and solve the problem in O(n) time.
Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.
gmyrianthous.medium.com
You may also like | [
{
"code": null,
"e": 258,
"s": 47,
"text": "LeetCode is a platform that gives access to numerous coding problems that are usually asked in technical interviews of tech giants such as Google, Meta and Amazon for Engineering and Machine Learning positions."
},
{
"code": null,
"e": 457,
"s": 258,
"text": "In today’s article, we are going to explore a couple of approaches for the third problem on LeetCode problem which is of medium difficulty level and is called “Longest substring without repetition”."
},
{
"code": null,
"e": 546,
"s": 457,
"text": "Given a string s, find the length of the longest substring without repeating characters."
},
{
"code": null,
"e": 557,
"s": 546,
"text": "Example 1:"
},
{
"code": null,
"e": 643,
"s": 557,
"text": "Input: s = \"abcabcbb\"Output: 3Explanation: The answer is \"abc\", with the length of 3."
},
{
"code": null,
"e": 654,
"s": 643,
"text": "Example 2:"
},
{
"code": null,
"e": 735,
"s": 654,
"text": "Input: s = \"bbbbb\"Output: 1Explanation: The answer is \"b\", with the length of 1."
},
{
"code": null,
"e": 746,
"s": 735,
"text": "Example 3:"
},
{
"code": null,
"e": 918,
"s": 746,
"text": "Input: s = \"pwwkew\"Output: 3Explanation: The answer is \"wke\", with the length of 3.Notice that the answer must be a substring, \"pwke\" is a subsequence and not a substring."
},
{
"code": null,
"e": 929,
"s": 918,
"text": "Example 4:"
},
{
"code": null,
"e": 952,
"s": 929,
"text": "Input: s = \"\"Output: 0"
},
{
"code": null,
"e": 965,
"s": 952,
"text": "Constraints:"
},
{
"code": null,
"e": 990,
"s": 965,
"text": "0 <= s.length <= 5 * 104"
},
{
"code": null,
"e": 1049,
"s": 990,
"text": "s consists of English letters, digits, symbols and spaces."
},
{
"code": null,
"e": 1066,
"s": 1049,
"text": "Source: LeetCode"
},
{
"code": null,
"e": 1177,
"s": 1066,
"text": "The most intuitive approach to the problem would be to perform a brute force search by using two nested loops."
},
{
"code": null,
"e": 1722,
"s": 1177,
"text": "class Solution: def lengthOfLongestSubstring(self, s: str) -> int: longest_str = \"\" for i, c in enumerate(s): canditate_str = str(c) for j in range(i + 1, len(s)): if s[j] not in canditate_str: canditate_str += str(s[j]) else: break if len(canditate_str) > len(longest_str): longest_str = canditate_str if len(s) - i <= len(longest_str): break return len(longest_str)"
},
{
"code": null,
"e": 1897,
"s": 1722,
"text": "Even though the above algorithm would solve the problem in question, the time complexity — which in this case is O(n2) — is an issue as we can definitely do better than this."
},
{
"code": null,
"e": 2094,
"s": 1897,
"text": "Now in order to improve the previous answer, we need to somehow make a single pass over the string containing the characters. One approach that could help us do so is the so called sliding window."
},
{
"code": null,
"e": 2244,
"s": 2094,
"text": "To make clear what I mean with sliding window, let’s consider the following string below (at the top we show the index of each individual character):"
},
{
"code": null,
"e": 2310,
"s": 2244,
"text": "# 0 1 2 3 4 5 6 7 # a b c a b c b b"
},
{
"code": null,
"e": 2362,
"s": 2310,
"text": "A sliding window has a starting and ending indices:"
},
{
"code": null,
"e": 2462,
"s": 2362,
"text": "# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |"
},
{
"code": null,
"e": 2644,
"s": 2462,
"text": "Depending on the algorithm, the starting and ending indices will move accordingly. In our case, we would want the sliding window to be created and move forward as illustrated below."
},
{
"code": null,
"e": 3997,
"s": 2644,
"text": "# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |# 0 1 2 3 4 5 6 7 # a b c a b c b b# start |# end |"
},
{
"code": null,
"e": 4248,
"s": 3997,
"text": "An algorithm that can reflect the logic described in the diagram/code below is shown below. We use a Hash Map (i.e. a Python dictionary) where keys correspond to characters seen so far, and values to the index this particular character was last seen."
},
{
"code": null,
"e": 4616,
"s": 4248,
"text": "class Solution: def lengthOfLongestSubstring(self, s: str) -> int: chars = {} start = 0 max_length = 0 for end, c in enumerate(s): if c in chars: start = max(start, chars[c] + 1) max_length = max(max_length, end - start + 1) chars[c] = end return max_length"
},
{
"code": null,
"e": 4816,
"s": 4616,
"text": "Now in terms of complexity, we made a significant improvement compared to the brute force approach since now we iterate over the string only once and thus the time complexity of our solution is O(n)."
},
{
"code": null,
"e": 4974,
"s": 4816,
"text": "In today’s article we walked through a couple of potential solutions to the third problem on LeetCode platform called “Longest substring without repetition”."
},
{
"code": null,
"e": 5151,
"s": 4974,
"text": "We initially created a less optimal solution that involves brute force by creating two nested loops in order to identify which substring in the input string is the longest one."
},
{
"code": null,
"e": 5353,
"s": 5151,
"text": "Finally, we optimised the algorithm by using sliding windows and hash maps (i.e. Python dictionaries) so that we will need to made just a single pass over the string and solve the problem in O(n) time."
},
{
"code": null,
"e": 5524,
"s": 5353,
"text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium."
},
{
"code": null,
"e": 5548,
"s": 5524,
"text": "gmyrianthous.medium.com"
}
] |
Node.js - Packaging | JXcore, which is an open source project, introduces a unique feature for packaging and encryption of source files and other assets into JX packages.
Consider you have a large project consisting of many files. JXcore can pack them all into a single file to simplify the distribution. This chapter provides a quick overview of the whole process starting from installing JXcore.
Installing JXcore is quite simple. Here we have provided step-by-step instructions on how to install JXcore on your system. Follow the steps given below −
Download the JXcore package from https://github.com/jxcore/jxcore, as per your operating system and machine architecture. We downloaded a package for Cenots running on 64-bit machine.
$ wget https://s3.amazonaws.com/nodejx/jx_rh64.zip
Unpack the downloaded file jx_rh64.zipand copy the jx binary into /usr/bin or may be in any other directory based on your system setup.
$ unzip jx_rh64.zip
$ cp jx_rh64/jx /usr/bin
Set your PATH variable appropriately to run jx from anywhere you like.
$ export PATH=$PATH:/usr/bin
You can verify your installation by issuing a simple command as shown below. You should find it working and printing its version number as follows −
$ jx --version
v0.10.32
Consider you have a project with the following directories where you kept all your files including Node.js, main file, index.js, and all the modules installed locally.
drwxr-xr-x 2 root root 4096 Nov 13 12:42 images
-rwxr-xr-x 1 root root 30457 Mar 6 12:19 index.htm
-rwxr-xr-x 1 root root 30452 Mar 1 12:54 index.js
drwxr-xr-x 23 root root 4096 Jan 15 03:48 node_modules
drwxr-xr-x 2 root root 4096 Mar 21 06:10 scripts
drwxr-xr-x 2 root root 4096 Feb 15 11:56 style
To package the above project, you simply need to go inside this directory and issue the following jx command. Assuming index.js is the entry file for your Node.js project −
$ jx package index.js index
Here you could have used any other package name instead of index. We have used index because we wanted to keep our main file name as index.jx. However, the above command will pack everything and will create the following two files −
index.jxp This is an intermediate file which contains the complete project detail needed to compile the project.
index.jxp This is an intermediate file which contains the complete project detail needed to compile the project.
index.jx This is the binary file having the complete package that is ready to be shipped to your client or to your production environment.
index.jx This is the binary file having the complete package that is ready to be shipped to your client or to your production environment.
Consider your original Node.js project was running as follows −
$ node index.js command_line_arguments
After compiling your package using JXcore, it can be started as follows −
$ jx index.jx command_line_arguments
To know more on JXcore, you can check its official website.
44 Lectures
7.5 hours
Eduonix Learning Solutions
88 Lectures
17 hours
Eduonix Learning Solutions
32 Lectures
1.5 hours
Richard Wells
8 Lectures
33 mins
Anant Rungta
9 Lectures
2.5 hours
SHIVPRASAD KOIRALA
97 Lectures
6 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2167,
"s": 2018,
"text": "JXcore, which is an open source project, introduces a unique feature for packaging and encryption of source files and other assets into JX packages."
},
{
"code": null,
"e": 2394,
"s": 2167,
"text": "Consider you have a large project consisting of many files. JXcore can pack them all into a single file to simplify the distribution. This chapter provides a quick overview of the whole process starting from installing JXcore."
},
{
"code": null,
"e": 2549,
"s": 2394,
"text": "Installing JXcore is quite simple. Here we have provided step-by-step instructions on how to install JXcore on your system. Follow the steps given below −"
},
{
"code": null,
"e": 2733,
"s": 2549,
"text": "Download the JXcore package from https://github.com/jxcore/jxcore, as per your operating system and machine architecture. We downloaded a package for Cenots running on 64-bit machine."
},
{
"code": null,
"e": 2785,
"s": 2733,
"text": "$ wget https://s3.amazonaws.com/nodejx/jx_rh64.zip\n"
},
{
"code": null,
"e": 2921,
"s": 2785,
"text": "Unpack the downloaded file jx_rh64.zipand copy the jx binary into /usr/bin or may be in any other directory based on your system setup."
},
{
"code": null,
"e": 2967,
"s": 2921,
"text": "$ unzip jx_rh64.zip\n$ cp jx_rh64/jx /usr/bin\n"
},
{
"code": null,
"e": 3038,
"s": 2967,
"text": "Set your PATH variable appropriately to run jx from anywhere you like."
},
{
"code": null,
"e": 3068,
"s": 3038,
"text": "$ export PATH=$PATH:/usr/bin\n"
},
{
"code": null,
"e": 3217,
"s": 3068,
"text": "You can verify your installation by issuing a simple command as shown below. You should find it working and printing its version number as follows −"
},
{
"code": null,
"e": 3242,
"s": 3217,
"text": "$ jx --version\nv0.10.32\n"
},
{
"code": null,
"e": 3410,
"s": 3242,
"text": "Consider you have a project with the following directories where you kept all your files including Node.js, main file, index.js, and all the modules installed locally."
},
{
"code": null,
"e": 3722,
"s": 3410,
"text": "drwxr-xr-x 2 root root 4096 Nov 13 12:42 images\n-rwxr-xr-x 1 root root 30457 Mar 6 12:19 index.htm\n-rwxr-xr-x 1 root root 30452 Mar 1 12:54 index.js\ndrwxr-xr-x 23 root root 4096 Jan 15 03:48 node_modules\ndrwxr-xr-x 2 root root 4096 Mar 21 06:10 scripts\ndrwxr-xr-x 2 root root 4096 Feb 15 11:56 style\n"
},
{
"code": null,
"e": 3895,
"s": 3722,
"text": "To package the above project, you simply need to go inside this directory and issue the following jx command. Assuming index.js is the entry file for your Node.js project −"
},
{
"code": null,
"e": 3924,
"s": 3895,
"text": "$ jx package index.js index\n"
},
{
"code": null,
"e": 4157,
"s": 3924,
"text": "Here you could have used any other package name instead of index. We have used index because we wanted to keep our main file name as index.jx. However, the above command will pack everything and will create the following two files −"
},
{
"code": null,
"e": 4270,
"s": 4157,
"text": "index.jxp This is an intermediate file which contains the complete project detail needed to compile the project."
},
{
"code": null,
"e": 4383,
"s": 4270,
"text": "index.jxp This is an intermediate file which contains the complete project detail needed to compile the project."
},
{
"code": null,
"e": 4522,
"s": 4383,
"text": "index.jx This is the binary file having the complete package that is ready to be shipped to your client or to your production environment."
},
{
"code": null,
"e": 4661,
"s": 4522,
"text": "index.jx This is the binary file having the complete package that is ready to be shipped to your client or to your production environment."
},
{
"code": null,
"e": 4725,
"s": 4661,
"text": "Consider your original Node.js project was running as follows −"
},
{
"code": null,
"e": 4765,
"s": 4725,
"text": "$ node index.js command_line_arguments\n"
},
{
"code": null,
"e": 4839,
"s": 4765,
"text": "After compiling your package using JXcore, it can be started as follows −"
},
{
"code": null,
"e": 4877,
"s": 4839,
"text": "$ jx index.jx command_line_arguments\n"
},
{
"code": null,
"e": 4937,
"s": 4877,
"text": "To know more on JXcore, you can check its official website."
},
{
"code": null,
"e": 4972,
"s": 4937,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5000,
"s": 4972,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5034,
"s": 5000,
"text": "\n 88 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 5062,
"s": 5034,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5097,
"s": 5062,
"text": "\n 32 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5112,
"s": 5097,
"text": " Richard Wells"
},
{
"code": null,
"e": 5143,
"s": 5112,
"text": "\n 8 Lectures \n 33 mins\n"
},
{
"code": null,
"e": 5157,
"s": 5143,
"text": " Anant Rungta"
},
{
"code": null,
"e": 5191,
"s": 5157,
"text": "\n 9 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5211,
"s": 5191,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 5244,
"s": 5211,
"text": "\n 97 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5264,
"s": 5244,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5271,
"s": 5264,
"text": " Print"
},
{
"code": null,
"e": 5282,
"s": 5271,
"text": " Add Notes"
}
] |
C Program for KMP Algorithm for Pattern Searching | In this problem, we are given two strings a text and a pattern. Our task is to create a program for KMP algorithm for pattern search, it will find all the occurrences of pattern in text string.
Here, we have to find all the occurrences of patterns in the text.
Let’s take an example to understand the problem,
text = “xyztrwqxyzfg” pattern = “xyz”
Found at index 0
Found at index 7
Here, we will discuss the solution to the problem using KMP (Knuth Morris Pratt) pattern searching algorithm, it will use a preprocessing string of the pattern which will be used for matching in the text. And help’s in processing or finding pattern matches in the case where matching characters are followed by the character of the string that does not match the pattern.
We will preprocess the pattern wand to create an array that contains the proper prefix and suffix from the pattern that will help in finding the mismatch patterns.
// C Program for KMP Algorithm for Pattern Searching
Live Demo
#include<iostream>
#include<string.h>
using namespace std;
void prefixSuffixArray(char* pat, int M, int* pps) {
int length = 0;
pps[0] = 0;
int i = 1;
while (i < M) {
if (pat[i] == pat[length]) {
length++;
pps[i] = length;
i++;
} else {
if (length != 0)
length = pps[length - 1];
else {
pps[i] = 0;
i++;
}
}
}
}
void KMPAlgorithm(char* text, char* pattern) {
int M = strlen(pattern);
int N = strlen(text);
int pps[M];
prefixSuffixArray(pattern, M, pps);
int i = 0;
int j = 0;
while (i < N) {
if (pattern[j] == text[i]) {
j++;
i++;
}
if (j == M) {
printf("Found pattern at index %d\n", i - j);
j = pps[j - 1];
}
else if (i < N && pattern[j] != text[i]) {
if (j != 0)
j = pps[j - 1];
else
i = i + 1;
}
}
}
int main() {
char text[] = "xyztrwqxyzfg";
char pattern[] = "xyz";
printf("The pattern is found in the text at the following index : \n");
KMPAlgorithm(text, pattern);
return 0;
}
The pattern is found in the text at the following index −
Found pattern at index 0
Found pattern at index 7 | [
{
"code": null,
"e": 1256,
"s": 1062,
"text": "In this problem, we are given two strings a text and a pattern. Our task is to create a program for KMP algorithm for pattern search, it will find all the occurrences of pattern in text string."
},
{
"code": null,
"e": 1323,
"s": 1256,
"text": "Here, we have to find all the occurrences of patterns in the text."
},
{
"code": null,
"e": 1372,
"s": 1323,
"text": "Let’s take an example to understand the problem,"
},
{
"code": null,
"e": 1410,
"s": 1372,
"text": "text = “xyztrwqxyzfg” pattern = “xyz”"
},
{
"code": null,
"e": 1444,
"s": 1410,
"text": "Found at index 0\nFound at index 7"
},
{
"code": null,
"e": 1816,
"s": 1444,
"text": "Here, we will discuss the solution to the problem using KMP (Knuth Morris Pratt) pattern searching algorithm, it will use a preprocessing string of the pattern which will be used for matching in the text. And help’s in processing or finding pattern matches in the case where matching characters are followed by the character of the string that does not match the pattern."
},
{
"code": null,
"e": 1980,
"s": 1816,
"text": "We will preprocess the pattern wand to create an array that contains the proper prefix and suffix from the pattern that will help in finding the mismatch patterns."
},
{
"code": null,
"e": 2033,
"s": 1980,
"text": "// C Program for KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 2044,
"s": 2033,
"text": " Live Demo"
},
{
"code": null,
"e": 3195,
"s": 2044,
"text": "#include<iostream>\n#include<string.h>\nusing namespace std;\nvoid prefixSuffixArray(char* pat, int M, int* pps) {\n int length = 0;\n pps[0] = 0;\n int i = 1;\n while (i < M) {\n if (pat[i] == pat[length]) {\n length++;\n pps[i] = length;\n i++;\n } else {\n if (length != 0)\n length = pps[length - 1];\n else {\n pps[i] = 0;\n i++;\n }\n }\n }\n}\nvoid KMPAlgorithm(char* text, char* pattern) {\n int M = strlen(pattern);\n int N = strlen(text);\n int pps[M];\n prefixSuffixArray(pattern, M, pps);\n int i = 0;\n int j = 0;\n while (i < N) {\n if (pattern[j] == text[i]) {\n j++;\n i++;\n }\n if (j == M) {\n printf(\"Found pattern at index %d\\n\", i - j);\n j = pps[j - 1];\n }\n else if (i < N && pattern[j] != text[i]) {\n if (j != 0)\n j = pps[j - 1];\n else\n i = i + 1;\n }\n }\n}\nint main() {\n char text[] = \"xyztrwqxyzfg\";\n char pattern[] = \"xyz\";\n printf(\"The pattern is found in the text at the following index : \\n\");\n KMPAlgorithm(text, pattern);\n return 0;\n}"
},
{
"code": null,
"e": 3253,
"s": 3195,
"text": "The pattern is found in the text at the following index −"
},
{
"code": null,
"e": 3303,
"s": 3253,
"text": "Found pattern at index 0\nFound pattern at index 7"
}
] |
Variational Auto Encoders. What happens when we encounter data... | by Viv | Towards Data Science | What happens when we encounter data with no labels? Most deep learning techniques require cleanly labelled data, but how realistic is this? At its core, this technique essentially says that if you have a set of inputs and their respective target labels, you can try and learn the probability of a particular label for a particular target. Sure, so glorified image mapping? In this post, I am exploring the variational autoencoder to probe a little deeper into the world of unlabelled data. This model will generate unique images after training on a collection of images with no labels.
Auto encoders sequentially de-construct input data into hidden representations and use these representations to sequentially reconstruct outputs that resemble their originals. It is essentially data compression that is data specific, meaning it can only compress that is similar to the data it has been trained on. Autoencoders are also known to be lossy, so the decompressed output will be a little degraded compared to the original inputs. Well so if they cause a loss in quality, why are they useful? The good question turns out, they are quite useful for data de-noising, where we train an autoencoder to reconstruct the input from a corrupted version of itself so that it can de-nise similar corrupted data.
In this post, I use my main man, Siraj’s support via his youtube channel and dive into the Variational Auto Encoder (VAE).
Let's start by talking about the Bayesian inference. Everyone reading this is probably aware of deep learning and its usefulness when it comes to approximating complex functions, however, the Bayesian inference offers a unique framework to reason uncertainty. In it, all uncertainty is expressed in terms of probability. This makes sense if you think about it, at any given time there exists evidence either in favour of or against something we already know, which can then be used to create a new probability. Extending this a little further, when we learn something new, we have to take into account what we already know and add this new evidence into consideration to create a new probability. The Bayesian theory basically describes this idea mathematically.
The VAE is a child of these ideas. Looking at it from a Bayesian standpoint, we can treat the inputs, hidden representations and reconstructed outputs of the VAE as probabilistic, random variables within a directed graphical model. Assuming it contains a specific probability model of some data, x, and a latent/hidden variable, z. We can write out the joint probability of the model like so:
Given just a character produced by the model, we wouldn’t know what setting of the latent variable has generated that character, our model is inherently stochastic!
Now, let's pull out the deep learning lens, a VAE consists of 3 main things:
An Encoder
A Decoder
A Loss Function
Given some input x, let's say we have a 28 by 28 handwritten digit image, which works out to 784 dimensions, where each pixel is one dimension. Now, this will encode into a latent/hidden representation space, which will be a lot less than 784. We can now sample a Gaussian probability density to get the noisy values of the representations.
Cool. Let's write this in code! (I have linked the code in its entirety at the end of this post)
First, we import the libraries and find our hyperparameters.
import numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import normfrom keras.layers import Input, Dense, Lambdafrom keras.models import Modelfrom keras import backend as Kfrom keras import objectivesfrom keras.datasets import mnist# Hyperparametersbatch_size = 100original_dim = 784latent_dim = 2intermediate_dim = 256nb_epoch = 10epsilon_std = 1.0
Next, we initialize our encoder network. This network’s job is to map inputs to our hidden distribution parameters. We take the input and send it through a dense fully connected layer with ReLU (classic non-linearity to squash dimensionality). Next, we convert the input data into two parameters in the hidden space. We predefine the size using dense, fully connected layers — z mean and z log sigma.
#encoderx = Input(batch_shape = (batch_size, original_dim))h = Dense(intermediate_dim, activation = ‘relu’)(x)z_mean = Dense(latent_dim)(h)z_log_var = Dense(latent_dim)(h)print(z_mean)print(z_log_var)
The decoder will take ‘z’ as its input and output the parameters to the probability distribution of the data. So let's assume that each pixel is either a 1 or 0 (black or white), now we can use Bernoulli distribution as it will define success as a binary value to represent a single pixel. So the decoder will get the latent/hidden representation of a digit as its input, and it outputs 784 Bernoulli parameters, one for each pixel, so essentially 784 values between 0 and 1.
We will be using the z_mean and z_log_var to randomly sample new, similar points from the hidden/latent normal distribution by defining a sampling function. The epsilon in the code block below is a random normal tensor.
def sampling(args): z_mean, z_log_var = args epsilon = K.random_normal(shape=(batch_size, latent_dim), mean=0.) return z_mean + K.exp(z_log_var / 2) * epsilon # note that “output_shape” isn’t necessary with the TensorFlow backendz = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])#latent hidden stateprint(z)
Once, we get z, we can feed it to our decoder and the decoder will map these latent space points back to the original input data. So, to build a decoder we first initialize it with two fully connected layers and their own respective activation functions. Because the data is extracted from a small dimensionality to a larger one, some of it will be lost in the reconstruction process.
#decoder# we instantiate these layers separately so as to reuse them laterdecoder_h = Dense(intermediate_dim, activation=’relu’)decoder_mean = Dense(original_dim, activation=’sigmoid’)h_decoded = decoder_h(z)x_decoded_mean = decoder_mean(h_decoded)print(x_decoded_mean)
Cool, but how much are some? So we’ll be building our loss function to measure exactly this. The first term below measures the reconstruction loss. If the decoder output is bad at reconstructing data, the cost in terms of loss will be considered at this point. The next term is a regularizer, meaning it keeps the representation of each digit as diverse as possible. So for instance, if two different people were to write out the digit three, the representations might end up looking very different because, of course, different people write differently. This can be bad, and the regularizer comes to the rescue! We penalize bad behaviour (like the example here) and ensure similar representations are close together. Our total loss function is defined as the sum of our reconstruction term and the KL divergence regularization term.
#lossdef vae_loss(x, x_decoded_mean): xent_loss = original_dim * objectives.binary_crossentropy(x, x_decoded_mean) kl_loss = — 0.5 * K.sum(1 + z_log_var — K.square(z_mean) — K.exp(z_log_var), axis=-1) return xent_loss + kl_lossvae = Model(x, x_decoded_mean)vae.compile(optimizer=’rmsprop’, loss=vae_loss)
Now comes the training part, we would usually train this model by using gradient descent to optimize our loss with respect to the parameters of the encoder and decoder. But how are we going to take derivatives with respect to the parameters of a randomly determined variable?
Turns out, we’ve built randomness into our model itself. Now, gradient descent usually expects that a given input always returns the same output for a fixed set of parameters. The only source of randomness in our case would be the inputs. So how do we tackle this? We parametrize! We will parametrize the samples so that the randomness can be independent of the parameters.
We will define a function that depends on the parameters deterministically, and so we can inject randomness into the model by introducing a random variable. The encoder will generate a vector of means and a vector of standard deviations, instead of generating a vector of real values. We take derivatives of the functions involving z with respect to the parameters of its distribution. We have defined our model’s optimizer as rmsprop and the loss function as vae_loss.
We start the training below by importing the MNIST dataset and feeding them to our model for a given number of epochs and batch size.
# train the VAE on MNIST digits(x_train, y_train), (x_test, y_test) = mnist.load_data()x_train = x_train.astype(‘float32’) / 255.x_test = x_test.astype(‘float32’) / 255.x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))vae.fit(x_train, x_train, shuffle=True, nb_epoch=nb_epoch, batch_size=batch_size, validation_data=(x_test, x_test),verbose=1)
Below we plot out the neighbourhoods on a 2D plane. Each coloured cluster represents a digit representation, and close clusters are essentially digits that are structurally similar.
# build a model to project inputs on the latent spaceencoder = Model(x, z_mean)# display a 2D plot of the digit classes in the latent spacex_test_encoded = encoder.predict(x_test, batch_size=batch_size)plt.figure(figsize=(6, 6))plt.scatter(x_test_encoded[:, 0], x_test_encoded[:, 1], c=y_test)plt.colorbar()plt.show()
Another way to represent this is to generate digits by scanning the latent plan, sampling latent points at regular intervals and generating the corresponding digit for each of these points like so:
# build a digit generator that can sample from the learned distributiondecoder_input = Input(shape=(latent_dim,))_h_decoded = decoder_h(decoder_input)_x_decoded_mean = decoder_mean(_h_decoded)generator = Model(decoder_input, _x_decoded_mean)# display a 2D manifold of the digitsn = 15 # figure with 15x15 digitsdigit_size = 28figure = np.zeros((digit_size * n, digit_size * n))# linearly spaced coordinates on the unit square were transformed through the inverse CDF (ppf) of the Gaussian# to produce values of the latent variables z, since the prior of the latent space is Gaussiangrid_x = norm.ppf(np.linspace(0.05, 0.95, n))grid_y = norm.ppf(np.linspace(0.05, 0.95, n))for i, yi in enumerate(grid_x): for j, xi in enumerate(grid_y): z_sample = np.array([[xi, yi]]) x_decoded = generator.predict(z_sample) digit = x_decoded[0].reshape(digit_size, digit_size) figure[i * digit_size: (i + 1) * digit_size, j * digit_size: (j + 1) * digit_size] = digitplt.figure(figsize=(10, 10))plt.imshow(figure, cmap=’Greys_r’)plt.show()
This has got to blow your mind at some level!
So at the essence of this exercise, there are three key takeaways:
Variational Encoders allow us to generate data by performing unsupervised learning
VAEs = Bayesian Inference + Deep Learning
Reparameterization allows us to backpropagate through the network, by making randomness independent of the parameters that allow us to derive our gradients.
This is a really fascinating world in the universe of machine learning and I hope I was able to bring some value to you through this post! | [
{
"code": null,
"e": 758,
"s": 172,
"text": "What happens when we encounter data with no labels? Most deep learning techniques require cleanly labelled data, but how realistic is this? At its core, this technique essentially says that if you have a set of inputs and their respective target labels, you can try and learn the probability of a particular label for a particular target. Sure, so glorified image mapping? In this post, I am exploring the variational autoencoder to probe a little deeper into the world of unlabelled data. This model will generate unique images after training on a collection of images with no labels."
},
{
"code": null,
"e": 1471,
"s": 758,
"text": "Auto encoders sequentially de-construct input data into hidden representations and use these representations to sequentially reconstruct outputs that resemble their originals. It is essentially data compression that is data specific, meaning it can only compress that is similar to the data it has been trained on. Autoencoders are also known to be lossy, so the decompressed output will be a little degraded compared to the original inputs. Well so if they cause a loss in quality, why are they useful? The good question turns out, they are quite useful for data de-noising, where we train an autoencoder to reconstruct the input from a corrupted version of itself so that it can de-nise similar corrupted data."
},
{
"code": null,
"e": 1594,
"s": 1471,
"text": "In this post, I use my main man, Siraj’s support via his youtube channel and dive into the Variational Auto Encoder (VAE)."
},
{
"code": null,
"e": 2357,
"s": 1594,
"text": "Let's start by talking about the Bayesian inference. Everyone reading this is probably aware of deep learning and its usefulness when it comes to approximating complex functions, however, the Bayesian inference offers a unique framework to reason uncertainty. In it, all uncertainty is expressed in terms of probability. This makes sense if you think about it, at any given time there exists evidence either in favour of or against something we already know, which can then be used to create a new probability. Extending this a little further, when we learn something new, we have to take into account what we already know and add this new evidence into consideration to create a new probability. The Bayesian theory basically describes this idea mathematically."
},
{
"code": null,
"e": 2750,
"s": 2357,
"text": "The VAE is a child of these ideas. Looking at it from a Bayesian standpoint, we can treat the inputs, hidden representations and reconstructed outputs of the VAE as probabilistic, random variables within a directed graphical model. Assuming it contains a specific probability model of some data, x, and a latent/hidden variable, z. We can write out the joint probability of the model like so:"
},
{
"code": null,
"e": 2915,
"s": 2750,
"text": "Given just a character produced by the model, we wouldn’t know what setting of the latent variable has generated that character, our model is inherently stochastic!"
},
{
"code": null,
"e": 2992,
"s": 2915,
"text": "Now, let's pull out the deep learning lens, a VAE consists of 3 main things:"
},
{
"code": null,
"e": 3003,
"s": 2992,
"text": "An Encoder"
},
{
"code": null,
"e": 3013,
"s": 3003,
"text": "A Decoder"
},
{
"code": null,
"e": 3029,
"s": 3013,
"text": "A Loss Function"
},
{
"code": null,
"e": 3370,
"s": 3029,
"text": "Given some input x, let's say we have a 28 by 28 handwritten digit image, which works out to 784 dimensions, where each pixel is one dimension. Now, this will encode into a latent/hidden representation space, which will be a lot less than 784. We can now sample a Gaussian probability density to get the noisy values of the representations."
},
{
"code": null,
"e": 3467,
"s": 3370,
"text": "Cool. Let's write this in code! (I have linked the code in its entirety at the end of this post)"
},
{
"code": null,
"e": 3528,
"s": 3467,
"text": "First, we import the libraries and find our hyperparameters."
},
{
"code": null,
"e": 3888,
"s": 3528,
"text": "import numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import normfrom keras.layers import Input, Dense, Lambdafrom keras.models import Modelfrom keras import backend as Kfrom keras import objectivesfrom keras.datasets import mnist# Hyperparametersbatch_size = 100original_dim = 784latent_dim = 2intermediate_dim = 256nb_epoch = 10epsilon_std = 1.0"
},
{
"code": null,
"e": 4289,
"s": 3888,
"text": "Next, we initialize our encoder network. This network’s job is to map inputs to our hidden distribution parameters. We take the input and send it through a dense fully connected layer with ReLU (classic non-linearity to squash dimensionality). Next, we convert the input data into two parameters in the hidden space. We predefine the size using dense, fully connected layers — z mean and z log sigma."
},
{
"code": null,
"e": 4490,
"s": 4289,
"text": "#encoderx = Input(batch_shape = (batch_size, original_dim))h = Dense(intermediate_dim, activation = ‘relu’)(x)z_mean = Dense(latent_dim)(h)z_log_var = Dense(latent_dim)(h)print(z_mean)print(z_log_var)"
},
{
"code": null,
"e": 4966,
"s": 4490,
"text": "The decoder will take ‘z’ as its input and output the parameters to the probability distribution of the data. So let's assume that each pixel is either a 1 or 0 (black or white), now we can use Bernoulli distribution as it will define success as a binary value to represent a single pixel. So the decoder will get the latent/hidden representation of a digit as its input, and it outputs 784 Bernoulli parameters, one for each pixel, so essentially 784 values between 0 and 1."
},
{
"code": null,
"e": 5186,
"s": 4966,
"text": "We will be using the z_mean and z_log_var to randomly sample new, similar points from the hidden/latent normal distribution by defining a sampling function. The epsilon in the code block below is a random normal tensor."
},
{
"code": null,
"e": 5513,
"s": 5186,
"text": "def sampling(args): z_mean, z_log_var = args epsilon = K.random_normal(shape=(batch_size, latent_dim), mean=0.) return z_mean + K.exp(z_log_var / 2) * epsilon # note that “output_shape” isn’t necessary with the TensorFlow backendz = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])#latent hidden stateprint(z)"
},
{
"code": null,
"e": 5898,
"s": 5513,
"text": "Once, we get z, we can feed it to our decoder and the decoder will map these latent space points back to the original input data. So, to build a decoder we first initialize it with two fully connected layers and their own respective activation functions. Because the data is extracted from a small dimensionality to a larger one, some of it will be lost in the reconstruction process."
},
{
"code": null,
"e": 6168,
"s": 5898,
"text": "#decoder# we instantiate these layers separately so as to reuse them laterdecoder_h = Dense(intermediate_dim, activation=’relu’)decoder_mean = Dense(original_dim, activation=’sigmoid’)h_decoded = decoder_h(z)x_decoded_mean = decoder_mean(h_decoded)print(x_decoded_mean)"
},
{
"code": null,
"e": 7002,
"s": 6168,
"text": "Cool, but how much are some? So we’ll be building our loss function to measure exactly this. The first term below measures the reconstruction loss. If the decoder output is bad at reconstructing data, the cost in terms of loss will be considered at this point. The next term is a regularizer, meaning it keeps the representation of each digit as diverse as possible. So for instance, if two different people were to write out the digit three, the representations might end up looking very different because, of course, different people write differently. This can be bad, and the regularizer comes to the rescue! We penalize bad behaviour (like the example here) and ensure similar representations are close together. Our total loss function is defined as the sum of our reconstruction term and the KL divergence regularization term."
},
{
"code": null,
"e": 7307,
"s": 7002,
"text": "#lossdef vae_loss(x, x_decoded_mean): xent_loss = original_dim * objectives.binary_crossentropy(x, x_decoded_mean) kl_loss = — 0.5 * K.sum(1 + z_log_var — K.square(z_mean) — K.exp(z_log_var), axis=-1) return xent_loss + kl_lossvae = Model(x, x_decoded_mean)vae.compile(optimizer=’rmsprop’, loss=vae_loss)"
},
{
"code": null,
"e": 7583,
"s": 7307,
"text": "Now comes the training part, we would usually train this model by using gradient descent to optimize our loss with respect to the parameters of the encoder and decoder. But how are we going to take derivatives with respect to the parameters of a randomly determined variable?"
},
{
"code": null,
"e": 7957,
"s": 7583,
"text": "Turns out, we’ve built randomness into our model itself. Now, gradient descent usually expects that a given input always returns the same output for a fixed set of parameters. The only source of randomness in our case would be the inputs. So how do we tackle this? We parametrize! We will parametrize the samples so that the randomness can be independent of the parameters."
},
{
"code": null,
"e": 8427,
"s": 7957,
"text": "We will define a function that depends on the parameters deterministically, and so we can inject randomness into the model by introducing a random variable. The encoder will generate a vector of means and a vector of standard deviations, instead of generating a vector of real values. We take derivatives of the functions involving z with respect to the parameters of its distribution. We have defined our model’s optimizer as rmsprop and the loss function as vae_loss."
},
{
"code": null,
"e": 8561,
"s": 8427,
"text": "We start the training below by importing the MNIST dataset and feeding them to our model for a given number of epochs and batch size."
},
{
"code": null,
"e": 8990,
"s": 8561,
"text": "# train the VAE on MNIST digits(x_train, y_train), (x_test, y_test) = mnist.load_data()x_train = x_train.astype(‘float32’) / 255.x_test = x_test.astype(‘float32’) / 255.x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))vae.fit(x_train, x_train, shuffle=True, nb_epoch=nb_epoch, batch_size=batch_size, validation_data=(x_test, x_test),verbose=1)"
},
{
"code": null,
"e": 9172,
"s": 8990,
"text": "Below we plot out the neighbourhoods on a 2D plane. Each coloured cluster represents a digit representation, and close clusters are essentially digits that are structurally similar."
},
{
"code": null,
"e": 9490,
"s": 9172,
"text": "# build a model to project inputs on the latent spaceencoder = Model(x, z_mean)# display a 2D plot of the digit classes in the latent spacex_test_encoded = encoder.predict(x_test, batch_size=batch_size)plt.figure(figsize=(6, 6))plt.scatter(x_test_encoded[:, 0], x_test_encoded[:, 1], c=y_test)plt.colorbar()plt.show()"
},
{
"code": null,
"e": 9688,
"s": 9490,
"text": "Another way to represent this is to generate digits by scanning the latent plan, sampling latent points at regular intervals and generating the corresponding digit for each of these points like so:"
},
{
"code": null,
"e": 10712,
"s": 9688,
"text": "# build a digit generator that can sample from the learned distributiondecoder_input = Input(shape=(latent_dim,))_h_decoded = decoder_h(decoder_input)_x_decoded_mean = decoder_mean(_h_decoded)generator = Model(decoder_input, _x_decoded_mean)# display a 2D manifold of the digitsn = 15 # figure with 15x15 digitsdigit_size = 28figure = np.zeros((digit_size * n, digit_size * n))# linearly spaced coordinates on the unit square were transformed through the inverse CDF (ppf) of the Gaussian# to produce values of the latent variables z, since the prior of the latent space is Gaussiangrid_x = norm.ppf(np.linspace(0.05, 0.95, n))grid_y = norm.ppf(np.linspace(0.05, 0.95, n))for i, yi in enumerate(grid_x): for j, xi in enumerate(grid_y): z_sample = np.array([[xi, yi]]) x_decoded = generator.predict(z_sample) digit = x_decoded[0].reshape(digit_size, digit_size) figure[i * digit_size: (i + 1) * digit_size, j * digit_size: (j + 1) * digit_size] = digitplt.figure(figsize=(10, 10))plt.imshow(figure, cmap=’Greys_r’)plt.show()"
},
{
"code": null,
"e": 10758,
"s": 10712,
"text": "This has got to blow your mind at some level!"
},
{
"code": null,
"e": 10825,
"s": 10758,
"text": "So at the essence of this exercise, there are three key takeaways:"
},
{
"code": null,
"e": 10908,
"s": 10825,
"text": "Variational Encoders allow us to generate data by performing unsupervised learning"
},
{
"code": null,
"e": 10950,
"s": 10908,
"text": "VAEs = Bayesian Inference + Deep Learning"
},
{
"code": null,
"e": 11107,
"s": 10950,
"text": "Reparameterization allows us to backpropagate through the network, by making randomness independent of the parameters that allow us to derive our gradients."
}
] |
Singleton Class in Kotlin - GeeksforGeeks | 14 Sep, 2020
Singleton Class in Kotlin is also called as the Singleton Object in Kotlin. Singleton class is a class that is defined in such a way that only one instance of the class can be created and used everywhere. Many times we create the two different objects of the same class, but we have to remember that creating two different objects also requires the allocation of two different memories for the objects. So it is better to make a single object and use it again and again.
Kotlin
// Kotlin programfun main(args: Array<String>) { val obj1 = GFG() val obj2 = GFG() println(obj1.toString()) println(obj2.toString())} class GFG{ }
Output:
In the above example, we can see that both the objects have a different address, thus it is a wastage of memory. In the below program, we have done the same thing, but we have used the singleton class.
Kotlin
// Kotlin programfun main(args: Array<String>){ println(GFG.toString()) println(GFG.toString())} // GFG is the singleton class hereobject GFG{ }
Output:
So when we use an object instead of a class, Kotlin actually uses the Singelton and allocates the single memory. In Java, a singleton class is made making a class named Singleton. But in Kotlin, we need to use the object keyword. The object class can have functions, properties, and the init method. The constructor method is not allowed in an object so we can use the init method if some initialization is required and the object can be defined inside a class. We call the method and member variables present in the singleton class using the class name, as we did in the companion objects.
Kotlin
// Kotlin programfun main(args: Array<String>) { println(GFG.name) println("The answer of addition is ${GFG.add(3,2)}") println("The answer of addition is ${GFG.add(10,15)}")} object GFG{ init { println("Singleton class invoked.") } var name = "GFG Is Best" fun add(num1:Int,num2:Int):Int { return num1.plus(num2) }}
Output:
The following are the properties of a typical singleton class:
Only one instance: The singleton class has only one instance and this is done by providing an instance of the class, within the class.
Globally accessible: The instance of the singleton class should be globally accessible so that each class can use it.
Constructor not allowed: We can use the init method to initialize our member variables.
Below are some points which explain the importance of singleton objects in android along with some examples, where it must be used, and reasons for why android developers should learn about singleton objects.
As we know that when we want a single instance of a particular object for the entire application, then we use Singleton. Common use-cases when you use the singleton is when you use Retrofit for every single request that you make throughout the app, in that case, you only need the single instance of the retrofit, as that instance of the retrofit contains some properties attached to it, like Gson Converter(which is used for conversion of JSON response to Java Objects) and Moshy Converter, so you want to reuse that instance and creating a new instance again and again would be a waste of space and time, so in this case, we have to use singleton objects.
Consider the case when you are working with the repository in MVVM architecture, so in that case, you should only create only 1 instance of the repository, as repositories are not going to change, and creating different instances would result in space increment and time wastage.
Suppose you have an app, and users can Login to it after undergoing user authentication, so if at the same time two user with same name and password tries to Login to the account, the app should not permit as due to concern of security issues. So singleton objects help us here to create only one instance of the object, i.e user here so that multiple logins can’t be possible. Hope these examples are sufficient to satisfy the reader to explore more about singleton objects in Kotlin so that they can use singleton object in their android projects.
Sample Android Program showing Use of Singleton Object:
Kotlin
// sample android application program in kotlin// showing use of singleton objectpackage com.example.retrofitexampleimport retrofit2.Callimport retrofit2.Retrofitimport retrofit2.converter.gson.GsonConverterFactoryimport retrofit2.http.GETimport retrofit2.http.Query const val BASE_URL = "https://newsapi.org/"const val API_KEY = "ff30357667f94aca9793cc35b9e447c1" interface NewsInterface{ @GET("v2/top-headlines?apiKey=$API_KEY") fun getheadlines(@Query("country")country:String,@Query("page")page:Int):Call<News> // function used to get the headlines of the country according to the query // written by developer} // NewsService is the instance of retrofit made by using Singleton objectobject NewsService{ val newsInstance:NewsInterface init { val retrofit=Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() newsInstance=retrofit.create(NewsInterface::class.java) }}
android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
GridView in Android with Example
Android Listview in Java with Example
How to Read Data from SQLite Database in Android?
Kotlin Array
Android UI Layouts
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters | [
{
"code": null,
"e": 25116,
"s": 25088,
"text": "\n14 Sep, 2020"
},
{
"code": null,
"e": 25588,
"s": 25116,
"text": "Singleton Class in Kotlin is also called as the Singleton Object in Kotlin. Singleton class is a class that is defined in such a way that only one instance of the class can be created and used everywhere. Many times we create the two different objects of the same class, but we have to remember that creating two different objects also requires the allocation of two different memories for the objects. So it is better to make a single object and use it again and again. "
},
{
"code": null,
"e": 25595,
"s": 25588,
"text": "Kotlin"
},
{
"code": "// Kotlin programfun main(args: Array<String>) { val obj1 = GFG() val obj2 = GFG() println(obj1.toString()) println(obj2.toString())} class GFG{ }",
"e": 25750,
"s": 25595,
"text": null
},
{
"code": null,
"e": 25758,
"s": 25750,
"text": "Output:"
},
{
"code": null,
"e": 25960,
"s": 25758,
"text": "In the above example, we can see that both the objects have a different address, thus it is a wastage of memory. In the below program, we have done the same thing, but we have used the singleton class."
},
{
"code": null,
"e": 25967,
"s": 25960,
"text": "Kotlin"
},
{
"code": "// Kotlin programfun main(args: Array<String>){ println(GFG.toString()) println(GFG.toString())} // GFG is the singleton class hereobject GFG{ }",
"e": 26119,
"s": 25967,
"text": null
},
{
"code": null,
"e": 26127,
"s": 26119,
"text": "Output:"
},
{
"code": null,
"e": 26718,
"s": 26127,
"text": "So when we use an object instead of a class, Kotlin actually uses the Singelton and allocates the single memory. In Java, a singleton class is made making a class named Singleton. But in Kotlin, we need to use the object keyword. The object class can have functions, properties, and the init method. The constructor method is not allowed in an object so we can use the init method if some initialization is required and the object can be defined inside a class. We call the method and member variables present in the singleton class using the class name, as we did in the companion objects."
},
{
"code": null,
"e": 26725,
"s": 26718,
"text": "Kotlin"
},
{
"code": "// Kotlin programfun main(args: Array<String>) { println(GFG.name) println(\"The answer of addition is ${GFG.add(3,2)}\") println(\"The answer of addition is ${GFG.add(10,15)}\")} object GFG{ init { println(\"Singleton class invoked.\") } var name = \"GFG Is Best\" fun add(num1:Int,num2:Int):Int { return num1.plus(num2) }}",
"e": 27068,
"s": 26725,
"text": null
},
{
"code": null,
"e": 27078,
"s": 27068,
"text": "Output: "
},
{
"code": null,
"e": 27141,
"s": 27078,
"text": "The following are the properties of a typical singleton class:"
},
{
"code": null,
"e": 27276,
"s": 27141,
"text": "Only one instance: The singleton class has only one instance and this is done by providing an instance of the class, within the class."
},
{
"code": null,
"e": 27394,
"s": 27276,
"text": "Globally accessible: The instance of the singleton class should be globally accessible so that each class can use it."
},
{
"code": null,
"e": 27482,
"s": 27394,
"text": "Constructor not allowed: We can use the init method to initialize our member variables."
},
{
"code": null,
"e": 27691,
"s": 27482,
"text": "Below are some points which explain the importance of singleton objects in android along with some examples, where it must be used, and reasons for why android developers should learn about singleton objects."
},
{
"code": null,
"e": 28349,
"s": 27691,
"text": "As we know that when we want a single instance of a particular object for the entire application, then we use Singleton. Common use-cases when you use the singleton is when you use Retrofit for every single request that you make throughout the app, in that case, you only need the single instance of the retrofit, as that instance of the retrofit contains some properties attached to it, like Gson Converter(which is used for conversion of JSON response to Java Objects) and Moshy Converter, so you want to reuse that instance and creating a new instance again and again would be a waste of space and time, so in this case, we have to use singleton objects."
},
{
"code": null,
"e": 28629,
"s": 28349,
"text": "Consider the case when you are working with the repository in MVVM architecture, so in that case, you should only create only 1 instance of the repository, as repositories are not going to change, and creating different instances would result in space increment and time wastage."
},
{
"code": null,
"e": 29179,
"s": 28629,
"text": "Suppose you have an app, and users can Login to it after undergoing user authentication, so if at the same time two user with same name and password tries to Login to the account, the app should not permit as due to concern of security issues. So singleton objects help us here to create only one instance of the object, i.e user here so that multiple logins can’t be possible. Hope these examples are sufficient to satisfy the reader to explore more about singleton objects in Kotlin so that they can use singleton object in their android projects."
},
{
"code": null,
"e": 29235,
"s": 29179,
"text": "Sample Android Program showing Use of Singleton Object:"
},
{
"code": null,
"e": 29242,
"s": 29235,
"text": "Kotlin"
},
{
"code": "// sample android application program in kotlin// showing use of singleton objectpackage com.example.retrofitexampleimport retrofit2.Callimport retrofit2.Retrofitimport retrofit2.converter.gson.GsonConverterFactoryimport retrofit2.http.GETimport retrofit2.http.Query const val BASE_URL = \"https://newsapi.org/\"const val API_KEY = \"ff30357667f94aca9793cc35b9e447c1\" interface NewsInterface{ @GET(\"v2/top-headlines?apiKey=$API_KEY\") fun getheadlines(@Query(\"country\")country:String,@Query(\"page\")page:Int):Call<News> // function used to get the headlines of the country according to the query // written by developer} // NewsService is the instance of retrofit made by using Singleton objectobject NewsService{ val newsInstance:NewsInterface init { val retrofit=Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() newsInstance=retrofit.create(NewsInterface::class.java) }}",
"e": 30234,
"s": 29242,
"text": null
},
{
"code": null,
"e": 30242,
"s": 30234,
"text": "android"
},
{
"code": null,
"e": 30250,
"s": 30242,
"text": "Android"
},
{
"code": null,
"e": 30257,
"s": 30250,
"text": "Kotlin"
},
{
"code": null,
"e": 30265,
"s": 30257,
"text": "Android"
},
{
"code": null,
"e": 30363,
"s": 30265,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30372,
"s": 30363,
"text": "Comments"
},
{
"code": null,
"e": 30385,
"s": 30372,
"text": "Old Comments"
},
{
"code": null,
"e": 30424,
"s": 30385,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 30466,
"s": 30424,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 30499,
"s": 30466,
"text": "GridView in Android with Example"
},
{
"code": null,
"e": 30537,
"s": 30499,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 30587,
"s": 30537,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 30600,
"s": 30587,
"text": "Kotlin Array"
},
{
"code": null,
"e": 30619,
"s": 30600,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 30661,
"s": 30619,
"text": "Retrofit with Kotlin Coroutine in Android"
}
] |
How to handle a link click event using jQuery? | To handle a click event using jQuery, use the click() method. You can try to run the following code to handle a link click event using jQuery −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("a").click(function(){
alert("You've clicked the link.");
});
});
</script>
</head>
<body>
<p>Click below link.</p>
<a href="#">Click</a>
</body>
</html> | [
{
"code": null,
"e": 1206,
"s": 1062,
"text": "To handle a click event using jQuery, use the click() method. You can try to run the following code to handle a link click event using jQuery −"
},
{
"code": null,
"e": 1216,
"s": 1206,
"text": "Live Demo"
},
{
"code": null,
"e": 1550,
"s": 1216,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n $(document).ready(function(){\n $(\"a\").click(function(){\n alert(\"You've clicked the link.\");\n });\n });\n</script>\n</head>\n<body>\n\n<p>Click below link.</p>\n<a href=\"#\">Click</a>\n\n</body>\n</html>"
}
] |
How to scroll to element with Selenium WebDriver using C#? | We can scroll to an element with Selenium webdriver in C#. This is done with the help of JavaScript Executor. Selenium can run JavaScript commands with the help of ExecuteScript method.
The method scrollIntoView in JavaScript is used to perform the scrolling action and the value true is passed as a parameter to the method. This is then passed to the ExecuteScript method.
var e = driver.FindElement(By.XPath("//*[text()='Careers']"));
((IJavaScriptExecutor)driver)
.ExecuteScript("arguments[0].scrollIntoView(true);", e);
For implementation we shall be using the NUnit framework.
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
namespace NUnitTestProject1{
public class Tests{
String u = "https://www.tutorialspoint.com/index.htm";
IWebDriver d;
[SetUp]
public void Setup(){
//creating object of FirefoxDriver
d = new FirefoxDriver();
}
[Test]
public void Test1(){
//launching URL
d.Navigate().GoToUrl(u);
//identify element
var e = d.FindElement(By.XPath("//*[text()='Careers']"));
// JavaScript Executor to scroll to element
((IJavaScriptExecutor)d)
.ExecuteScript("arguments[0].scrollIntoView(true);", e);
Console.WriteLine(e.Text);
}
[TearDown]
public void close_Browser(){
d.Quit();
}
}
}
Click on Run All Tests button −
Click on Open additional output for this result link −
We should get the Test Outcome and Standard Output. | [
{
"code": null,
"e": 1248,
"s": 1062,
"text": "We can scroll to an element with Selenium webdriver in C#. This is done with the help of JavaScript Executor. Selenium can run JavaScript commands with the help of ExecuteScript method."
},
{
"code": null,
"e": 1436,
"s": 1248,
"text": "The method scrollIntoView in JavaScript is used to perform the scrolling action and the value true is passed as a parameter to the method. This is then passed to the ExecuteScript method."
},
{
"code": null,
"e": 1586,
"s": 1436,
"text": "var e = driver.FindElement(By.XPath(\"//*[text()='Careers']\"));\n((IJavaScriptExecutor)driver)\n.ExecuteScript(\"arguments[0].scrollIntoView(true);\", e);"
},
{
"code": null,
"e": 1644,
"s": 1586,
"text": "For implementation we shall be using the NUnit framework."
},
{
"code": null,
"e": 2472,
"s": 1644,
"text": "using NUnit.Framework;\nusing OpenQA.Selenium;\nusing OpenQA.Selenium.Firefox;\nusing System;\nnamespace NUnitTestProject1{\n public class Tests{\n String u = \"https://www.tutorialspoint.com/index.htm\";\n IWebDriver d;\n [SetUp]\n public void Setup(){\n //creating object of FirefoxDriver\n d = new FirefoxDriver();\n }\n [Test]\n public void Test1(){\n //launching URL\n d.Navigate().GoToUrl(u);\n //identify element\n var e = d.FindElement(By.XPath(\"//*[text()='Careers']\"));\n // JavaScript Executor to scroll to element\n ((IJavaScriptExecutor)d)\n .ExecuteScript(\"arguments[0].scrollIntoView(true);\", e);\n Console.WriteLine(e.Text);\n }\n [TearDown]\n public void close_Browser(){\n d.Quit();\n }\n }\n}"
},
{
"code": null,
"e": 2504,
"s": 2472,
"text": "Click on Run All Tests button −"
},
{
"code": null,
"e": 2559,
"s": 2504,
"text": "Click on Open additional output for this result link −"
},
{
"code": null,
"e": 2611,
"s": 2559,
"text": "We should get the Test Outcome and Standard Output."
}
] |
How to check if String is Palindrome using C#? | Let’s say we need to find that the following string is Palindrome or not −
str = "Level";
For that, convert the string into character array to chec each character −
char[] ch = str.ToCharArray();
Now find the reverse −
Array.Reverse(ch);
Use the Equals method to find whether the reverse is equal to original array or not −
bool res = str.Equals(rev, StringComparison.OrdinalIgnoreCase);
The following is the complete code −
Live Demo
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
string str, rev;
str = "Level";
char[] ch = str.ToCharArray();
Array.Reverse(ch);
rev = new string(ch);
bool res = str.Equals(rev, StringComparison.OrdinalIgnoreCase);
if (res == true) {
Console.WriteLine("String " + str + " is a Palindrome!");
} else {
Console.WriteLine("String " + str + " is not a Palindrome!");
}
Console.Read();
}
}
}
String Level is a Palindrome! | [
{
"code": null,
"e": 1137,
"s": 1062,
"text": "Let’s say we need to find that the following string is Palindrome or not −"
},
{
"code": null,
"e": 1152,
"s": 1137,
"text": "str = \"Level\";"
},
{
"code": null,
"e": 1227,
"s": 1152,
"text": "For that, convert the string into character array to chec each character −"
},
{
"code": null,
"e": 1258,
"s": 1227,
"text": "char[] ch = str.ToCharArray();"
},
{
"code": null,
"e": 1281,
"s": 1258,
"text": "Now find the reverse −"
},
{
"code": null,
"e": 1300,
"s": 1281,
"text": "Array.Reverse(ch);"
},
{
"code": null,
"e": 1386,
"s": 1300,
"text": "Use the Equals method to find whether the reverse is equal to original array or not −"
},
{
"code": null,
"e": 1450,
"s": 1386,
"text": "bool res = str.Equals(rev, StringComparison.OrdinalIgnoreCase);"
},
{
"code": null,
"e": 1487,
"s": 1450,
"text": "The following is the complete code −"
},
{
"code": null,
"e": 1498,
"s": 1487,
"text": " Live Demo"
},
{
"code": null,
"e": 2058,
"s": 1498,
"text": "using System;\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n\n string str, rev;\n str = \"Level\";\n char[] ch = str.ToCharArray();\n Array.Reverse(ch);\n rev = new string(ch);\n bool res = str.Equals(rev, StringComparison.OrdinalIgnoreCase);\n \n if (res == true) {\n Console.WriteLine(\"String \" + str + \" is a Palindrome!\");\n } else {\n Console.WriteLine(\"String \" + str + \" is not a Palindrome!\");\n }\n Console.Read();\n }\n }\n}"
},
{
"code": null,
"e": 2088,
"s": 2058,
"text": "String Level is a Palindrome!"
}
] |
How to read a .txt file with RandomAccessFile in Java? | In general, while reading or writing data to a file, you can only read or, write data from the start of the file. you cannot read/write from random position.
The java.io.RandomAccessFile class in Java enables you to read/write data to a random access file.
This acts similar to a large array of bytes with an index or, cursor known as file pointer you can get the position of this pointer using the getFilePointer() method and set it using the seek() method.
This class provides various methods to read and write data to a file. The readLine() method of this class reads the next line from the file and returns it in the form as String.
To read data from a file using the readLine() method of this class −
Instantiate the File class by passing the path of the required file in String format.
Instantiate the File class by passing the path of the required file in String format.
Instantiate the StringBuffer class.
Instantiate the StringBuffer class.
Instantiate the RandomAccessFile class by passing the above created File object and a String representing mode of access (r:read, rw:read/write etc..)
Instantiate the RandomAccessFile class by passing the above created File object and a String representing mode of access (r:read, rw:read/write etc..)
iterate through the file while its position is less than its length (length() method).
iterate through the file while its position is less than its length (length() method).
Append each line to the StringBuffer object created above.
Append each line to the StringBuffer object created above.
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
public static void main(String args[]) throws IOException {
String filePath = "D://input.txt";
//Instantiating the File class
File file = new File(filePath);
//Instantiating the StringBuffer
StringBuffer buffer = new StringBuffer();
//instantiating the RandomAccessFile
RandomAccessFile raFile = new RandomAccessFile(file, "rw");
//Reading each line using the readLine() method
while(raFile.getFilePointer() < raFile.length()) {
buffer.append(raFile.readLine()+System.lineSeparator());
}
String contents = buffer.toString();
System.out.println("Contents of the file: \n"+contents);
}
}
Contents of the file:
Tutorials Point originated from the idea that there exists a class of readers who respond better
to online content and prefer to learn new skills.
Our content and resources are freely available and we prefer to keep it that way to encourage
our readers acquire as many skills as they would like to.
We don’t force our readers to sign up with us or submit their details either.
Enjoy the free content | [
{
"code": null,
"e": 1220,
"s": 1062,
"text": "In general, while reading or writing data to a file, you can only read or, write data from the start of the file. you cannot read/write from random position."
},
{
"code": null,
"e": 1319,
"s": 1220,
"text": "The java.io.RandomAccessFile class in Java enables you to read/write data to a random access file."
},
{
"code": null,
"e": 1521,
"s": 1319,
"text": "This acts similar to a large array of bytes with an index or, cursor known as file pointer you can get the position of this pointer using the getFilePointer() method and set it using the seek() method."
},
{
"code": null,
"e": 1699,
"s": 1521,
"text": "This class provides various methods to read and write data to a file. The readLine() method of this class reads the next line from the file and returns it in the form as String."
},
{
"code": null,
"e": 1768,
"s": 1699,
"text": "To read data from a file using the readLine() method of this class −"
},
{
"code": null,
"e": 1854,
"s": 1768,
"text": "Instantiate the File class by passing the path of the required file in String format."
},
{
"code": null,
"e": 1940,
"s": 1854,
"text": "Instantiate the File class by passing the path of the required file in String format."
},
{
"code": null,
"e": 1976,
"s": 1940,
"text": "Instantiate the StringBuffer class."
},
{
"code": null,
"e": 2012,
"s": 1976,
"text": "Instantiate the StringBuffer class."
},
{
"code": null,
"e": 2163,
"s": 2012,
"text": "Instantiate the RandomAccessFile class by passing the above created File object and a String representing mode of access (r:read, rw:read/write etc..)"
},
{
"code": null,
"e": 2314,
"s": 2163,
"text": "Instantiate the RandomAccessFile class by passing the above created File object and a String representing mode of access (r:read, rw:read/write etc..)"
},
{
"code": null,
"e": 2401,
"s": 2314,
"text": "iterate through the file while its position is less than its length (length() method)."
},
{
"code": null,
"e": 2488,
"s": 2401,
"text": "iterate through the file while its position is less than its length (length() method)."
},
{
"code": null,
"e": 2547,
"s": 2488,
"text": "Append each line to the StringBuffer object created above."
},
{
"code": null,
"e": 2606,
"s": 2547,
"text": "Append each line to the StringBuffer object created above."
},
{
"code": null,
"e": 3400,
"s": 2606,
"text": "import java.io.File;\nimport java.io.IOException;\nimport java.io.RandomAccessFile;\npublic class RandomAccessFileExample {\n public static void main(String args[]) throws IOException {\n String filePath = \"D://input.txt\";\n //Instantiating the File class\n File file = new File(filePath);\n //Instantiating the StringBuffer\n StringBuffer buffer = new StringBuffer();\n //instantiating the RandomAccessFile\n RandomAccessFile raFile = new RandomAccessFile(file, \"rw\");\n //Reading each line using the readLine() method\n while(raFile.getFilePointer() < raFile.length()) {\n buffer.append(raFile.readLine()+System.lineSeparator());\n }\n String contents = buffer.toString();\n System.out.println(\"Contents of the file: \\n\"+contents);\n }\n}"
},
{
"code": null,
"e": 3824,
"s": 3400,
"text": "Contents of the file:\nTutorials Point originated from the idea that there exists a class of readers who respond better \nto online content and prefer to learn new skills.\nOur content and resources are freely available and we prefer to keep it that way to encourage \nour readers acquire as many skills as they would like to.\nWe don’t force our readers to sign up with us or submit their details either.\nEnjoy the free content"
}
] |
Python program to print all the numbers divisible by 3 and 5 for a given number | This is a python program to print all the numbers which are divisible by 3 and 5 from a given interger N. There are numerous ways we can write this program except that we need to check if the number is fully divisble by both 3 and 5.
Below is my code to write a python program to print all the numbers divisible by 3 and 5 −
lower = int(input("Enter lower range limit:"))
upper = int(input("Enter upper range limit:"))
for i in range(lower, upper+1):
if((i%3==0) & (i%5==0)):
print(i)
Enter lower range limit:0
Enter upper range limit:99
0
15
30
45
60
75
90
Above we try to print all the numbers between 0 and 99 which are divisble by 3 and 5. Same program can be used to print all the number between 0 and 1000 which are divisible by 3 and 5, we just need to alter our range and our output will be something like,
Enter lower range limit:0
Enter upper range limit:1000
0
15
30
45
60
75
90
105
120
135
150
165
180
195
....
....
915
930
945
960
975
990
In case we want to write a program which will print all the numbers in a range divisible by a given number not the fixed number like above, i just need to update by
program like,
#Incase we want to print all number between a range divided by any given number
n = int(input("Enter the number to be divided by:"))
for i in range(lower, upper+1):
if(i%n==0):
print(i)
Below the steps to write above code −
Take the lower and upper limit .i.e. the range from the user.
Take the lower and upper limit .i.e. the range from the user.
Take the number to be divided by from the user. In case of our main problem, because we know that numbers(3 and 5), i write the 3 and 5 in the if statement only.
Take the number to be divided by from the user. In case of our main problem, because we know that numbers(3 and 5), i write the 3 and 5 in the if statement only.
Using a loop with &(and) operator statement(so that it print only those numbers which are divisble by both 3 & 5), prints all the factors which is divisible by the number.
Using a loop with &(and) operator statement(so that it print only those numbers which are divisble by both 3 & 5), prints all the factors which is divisible by the number.
Exit.
Exit. | [
{
"code": null,
"e": 1296,
"s": 1062,
"text": "This is a python program to print all the numbers which are divisible by 3 and 5 from a given interger N. There are numerous ways we can write this program except that we need to check if the number is fully divisble by both 3 and 5."
},
{
"code": null,
"e": 1387,
"s": 1296,
"text": "Below is my code to write a python program to print all the numbers divisible by 3 and 5 −"
},
{
"code": null,
"e": 1556,
"s": 1387,
"text": "lower = int(input(\"Enter lower range limit:\"))\nupper = int(input(\"Enter upper range limit:\"))\nfor i in range(lower, upper+1):\n if((i%3==0) & (i%5==0)):\n print(i)"
},
{
"code": null,
"e": 1629,
"s": 1556,
"text": "Enter lower range limit:0\nEnter upper range limit:99\n0\n15\n30\n45\n60\n75\n90"
},
{
"code": null,
"e": 1886,
"s": 1629,
"text": "Above we try to print all the numbers between 0 and 99 which are divisble by 3 and 5. Same program can be used to print all the number between 0 and 1000 which are divisible by 3 and 5, we just need to alter our range and our output will be something like,"
},
{
"code": null,
"e": 2023,
"s": 1886,
"text": "Enter lower range limit:0\nEnter upper range limit:1000\n0\n15\n30\n45\n60\n75\n90\n105\n120\n135\n150\n165\n180\n195\n....\n....\n915\n930\n945\n960\n975\n990"
},
{
"code": null,
"e": 2202,
"s": 2023,
"text": "In case we want to write a program which will print all the numbers in a range divisible by a given number not the fixed number like above, i just need to update by\nprogram like,"
},
{
"code": null,
"e": 2397,
"s": 2202,
"text": "#Incase we want to print all number between a range divided by any given number\nn = int(input(\"Enter the number to be divided by:\"))\nfor i in range(lower, upper+1):\n if(i%n==0):\n print(i)"
},
{
"code": null,
"e": 2435,
"s": 2397,
"text": "Below the steps to write above code −"
},
{
"code": null,
"e": 2497,
"s": 2435,
"text": "Take the lower and upper limit .i.e. the range from the user."
},
{
"code": null,
"e": 2559,
"s": 2497,
"text": "Take the lower and upper limit .i.e. the range from the user."
},
{
"code": null,
"e": 2721,
"s": 2559,
"text": "Take the number to be divided by from the user. In case of our main problem, because we know that numbers(3 and 5), i write the 3 and 5 in the if statement only."
},
{
"code": null,
"e": 2883,
"s": 2721,
"text": "Take the number to be divided by from the user. In case of our main problem, because we know that numbers(3 and 5), i write the 3 and 5 in the if statement only."
},
{
"code": null,
"e": 3055,
"s": 2883,
"text": "Using a loop with &(and) operator statement(so that it print only those numbers which are divisble by both 3 & 5), prints all the factors which is divisible by the number."
},
{
"code": null,
"e": 3227,
"s": 3055,
"text": "Using a loop with &(and) operator statement(so that it print only those numbers which are divisble by both 3 & 5), prints all the factors which is divisible by the number."
},
{
"code": null,
"e": 3233,
"s": 3227,
"text": "Exit."
},
{
"code": null,
"e": 3239,
"s": 3233,
"text": "Exit."
}
] |
How to disable landscape mode in Android? | Android supports two orientations as portrait and landscape. we can disable orientation in android application. This example demonstrate
about how to disable landscape mode in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:background = "#dde4dd">
<EditText
android:id = "@+id/editText"
android:layout_width = "match_parent"
android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, it contains linear layout and editext. it going to support both landscape and portrait as shown below -
The above output indicates about landscape mode
The above output indicates about portrait mode.
To disable landscape mode need to add screenOrientation tag in manifest.xml as shown below -
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication">
<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"
android:screenOrientation = "portrait">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
In the above code we have given screenOrientation as portrait means MainActivity going to support only portrait mode only . If you want to develop an application in portrait mode, add screenOrientation inside application tag.
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result it is showing only portrait mode. now turn your device it not going to change the view according to orientation. | [
{
"code": null,
"e": 1247,
"s": 1062,
"text": "Android supports two orientations as portrait and landscape. we can disable orientation in android application. This example demonstrate\nabout how to disable landscape mode in Android."
},
{
"code": null,
"e": 1376,
"s": 1247,
"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": 1441,
"s": 1376,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1920,
"s": 1441,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:background = \"#dde4dd\">\n <EditText\n android:id = \"@+id/editText\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2043,
"s": 1920,
"text": "In the above code, it contains linear layout and editext. it going to support both landscape and portrait as shown below -"
},
{
"code": null,
"e": 2091,
"s": 2043,
"text": "The above output indicates about landscape mode"
},
{
"code": null,
"e": 2139,
"s": 2091,
"text": "The above output indicates about portrait mode."
},
{
"code": null,
"e": 2232,
"s": 2139,
"text": "To disable landscape mode need to add screenOrientation tag in manifest.xml as shown below -"
},
{
"code": null,
"e": 2992,
"s": 2232,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\" package = \"com.example.andy.myapplication\">\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 android:screenOrientation = \"portrait\">\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": 3218,
"s": 2992,
"text": "In the above code we have given screenOrientation as portrait means MainActivity going to support only portrait mode only . If you want to develop an application in portrait mode, add screenOrientation inside application tag."
},
{
"code": null,
"e": 3565,
"s": 3218,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 3698,
"s": 3565,
"text": "In the above result it is showing only portrait mode. now turn your device it not going to change the view according to orientation."
}
] |
How to create wave ball effect using CSS? - GeeksforGeeks | 11 Sep, 2020
Wave ball effect is a new entry in the world of animation effects that are used in the designing of modern web apps. In this effect, we have some balls which are animated like a wave. Now you can add different elements to it make it unique like a different color for balls and animation-delay or by changing the axis of animation.
Approach: The approach is to first create some small size balls and then use keyframes to animate them and also change the color of the balls on each frame division. Then we will be adding some animation-delay to each of the balls. Although, the animation delay part is optional.
HTML Code: In this section, we have created a number of span tags that will be used to make the balls. All of them are wrapped inside a div tag.
<!DOCTYPE html><html><head><title>Wave Ball Effect</title></head><body> <div class="loader"> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div></body></html>
CSS Code: For CSS, follow the below given steps.
Step 1: First, apply a dark background to the body tag.
Step 2: Now align all the span tag to center of the page.
Step 3: Now use animation property with identifier name animate.
Step 4: Now use keyframes to to apply border and color for each frame division. Use transform on Y-axis.
Step 5: Now use n-th child property to give some animation delay to each span tag.
body { background: rgb(65, 63, 63); } .loader { height: 40px; position: absolute; top: 50%; left: 50%; } .loader span { height: 15px; width: 15px; display: inline-block; border-radius: 50%; transition: all 0.5s; animation: animate 2s infinite; } @keyframes animate { 0% { border: 1px solid #fff; background: transparent; transform: translateY(0); } 50% { border: 1px solid #fff; background: green; transform: translateY(-25px); } 100% { border: 1px solid #fff; background: yellow; transform: translateY(0); } } .loader span:nth-child(1) { animation-delay: 0; } .loader span:nth-child(2) { animation-delay: 0.1s; } .loader span:nth-child(3) { animation-delay: 0.2s; } .loader span:nth-child(4) { animation-delay: 0.3s; } .loader span:nth-child(5) { animation-delay: 0.4s; } .loader span:nth-child(6) { animation-delay: 0.5s; }
Tip: Make sure the to keep the size of balls small and you can change the axis of animation to X-axis for a different effect.
Complete Code: It is the combination of the above two sections of code.
<!DOCTYPE html><html><head><title>Wave Ball Effect</title> <style> body { background: rgb(65, 63, 63); } .loader { height: 40px; position: absolute; top: 50%; left: 50%; } .loader span { height: 15px; width: 15px; display: inline-block; border-radius: 50%; transition: all 0.5s; animation: animate 2s infinite; } @keyframes animate { 0% { border: 1px solid #fff; background: transparent; transform: translateY(0); } 50% { border: 1px solid #fff; background: green; transform: translateY(-25px); } 100% { border: 1px solid #fff; background: yellow; transform: translateY(0); } } .loader span:nth-child(1) { animation-delay: 0; } .loader span:nth-child(2) { animation-delay: 0.1s; } .loader span:nth-child(3) { animation-delay: 0.2s; } .loader span:nth-child(4) { animation-delay: 0.3s; } .loader span:nth-child(5) { animation-delay: 0.4s; } .loader span:nth-child(6) { animation-delay: 0.5s; } </style></head><body> <div class="loader"> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div></body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Advanced
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 28046,
"s": 28018,
"text": "\n11 Sep, 2020"
},
{
"code": null,
"e": 28377,
"s": 28046,
"text": "Wave ball effect is a new entry in the world of animation effects that are used in the designing of modern web apps. In this effect, we have some balls which are animated like a wave. Now you can add different elements to it make it unique like a different color for balls and animation-delay or by changing the axis of animation."
},
{
"code": null,
"e": 28657,
"s": 28377,
"text": "Approach: The approach is to first create some small size balls and then use keyframes to animate them and also change the color of the balls on each frame division. Then we will be adding some animation-delay to each of the balls. Although, the animation delay part is optional."
},
{
"code": null,
"e": 28802,
"s": 28657,
"text": "HTML Code: In this section, we have created a number of span tags that will be used to make the balls. All of them are wrapped inside a div tag."
},
{
"code": "<!DOCTYPE html><html><head><title>Wave Ball Effect</title></head><body> <div class=\"loader\"> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div></body></html>",
"e": 29037,
"s": 28802,
"text": null
},
{
"code": null,
"e": 29086,
"s": 29037,
"text": "CSS Code: For CSS, follow the below given steps."
},
{
"code": null,
"e": 29142,
"s": 29086,
"text": "Step 1: First, apply a dark background to the body tag."
},
{
"code": null,
"e": 29200,
"s": 29142,
"text": "Step 2: Now align all the span tag to center of the page."
},
{
"code": null,
"e": 29265,
"s": 29200,
"text": "Step 3: Now use animation property with identifier name animate."
},
{
"code": null,
"e": 29370,
"s": 29265,
"text": "Step 4: Now use keyframes to to apply border and color for each frame division. Use transform on Y-axis."
},
{
"code": null,
"e": 29453,
"s": 29370,
"text": "Step 5: Now use n-th child property to give some animation delay to each span tag."
},
{
"code": "body { background: rgb(65, 63, 63); } .loader { height: 40px; position: absolute; top: 50%; left: 50%; } .loader span { height: 15px; width: 15px; display: inline-block; border-radius: 50%; transition: all 0.5s; animation: animate 2s infinite; } @keyframes animate { 0% { border: 1px solid #fff; background: transparent; transform: translateY(0); } 50% { border: 1px solid #fff; background: green; transform: translateY(-25px); } 100% { border: 1px solid #fff; background: yellow; transform: translateY(0); } } .loader span:nth-child(1) { animation-delay: 0; } .loader span:nth-child(2) { animation-delay: 0.1s; } .loader span:nth-child(3) { animation-delay: 0.2s; } .loader span:nth-child(4) { animation-delay: 0.3s; } .loader span:nth-child(5) { animation-delay: 0.4s; } .loader span:nth-child(6) { animation-delay: 0.5s; }",
"e": 30634,
"s": 29453,
"text": null
},
{
"code": null,
"e": 30760,
"s": 30634,
"text": "Tip: Make sure the to keep the size of balls small and you can change the axis of animation to X-axis for a different effect."
},
{
"code": null,
"e": 30832,
"s": 30760,
"text": "Complete Code: It is the combination of the above two sections of code."
},
{
"code": "<!DOCTYPE html><html><head><title>Wave Ball Effect</title> <style> body { background: rgb(65, 63, 63); } .loader { height: 40px; position: absolute; top: 50%; left: 50%; } .loader span { height: 15px; width: 15px; display: inline-block; border-radius: 50%; transition: all 0.5s; animation: animate 2s infinite; } @keyframes animate { 0% { border: 1px solid #fff; background: transparent; transform: translateY(0); } 50% { border: 1px solid #fff; background: green; transform: translateY(-25px); } 100% { border: 1px solid #fff; background: yellow; transform: translateY(0); } } .loader span:nth-child(1) { animation-delay: 0; } .loader span:nth-child(2) { animation-delay: 0.1s; } .loader span:nth-child(3) { animation-delay: 0.2s; } .loader span:nth-child(4) { animation-delay: 0.3s; } .loader span:nth-child(5) { animation-delay: 0.4s; } .loader span:nth-child(6) { animation-delay: 0.5s; } </style></head><body> <div class=\"loader\"> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div></body></html>",
"e": 32275,
"s": 30832,
"text": null
},
{
"code": null,
"e": 32283,
"s": 32275,
"text": "Output:"
},
{
"code": null,
"e": 32420,
"s": 32283,
"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": 32433,
"s": 32420,
"text": "CSS-Advanced"
},
{
"code": null,
"e": 32437,
"s": 32433,
"text": "CSS"
},
{
"code": null,
"e": 32442,
"s": 32437,
"text": "HTML"
},
{
"code": null,
"e": 32459,
"s": 32442,
"text": "Web Technologies"
},
{
"code": null,
"e": 32464,
"s": 32459,
"text": "HTML"
},
{
"code": null,
"e": 32562,
"s": 32464,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32612,
"s": 32562,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 32674,
"s": 32612,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 32732,
"s": 32674,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 32780,
"s": 32732,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 32830,
"s": 32780,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 32880,
"s": 32830,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 32942,
"s": 32880,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 33002,
"s": 32942,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 33050,
"s": 33002,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Program to find largest element in an array using Dynamic Memory Allocation - GeeksforGeeks | 17 Sep, 2020
Given an array arr[] consisting of N integers, the task is to find the largest element in the given array using Dynamic Memory Allocation.
Examples:
Input: arr[] = {4, 5, 6, 7} Output: 7Explanation:The largest element present in the given array is 7.
Input: arr[] = {8, 9, 10, 12} Output: 12Explanation:The largest element present in the given array is 12.
Approach: The idea here is to use Dynamic Memory for searching the largest element in the given array. Follow the steps below to solve the problem:
Take N elements and a pointer to store the address of N elementsAllocate memory dynamically for N elements.Store the elements in the allocated memory.Traverse the array arr[] to find the largest element among all the numbers by comparing the values using pointers.
Take N elements and a pointer to store the address of N elements
Allocate memory dynamically for N elements.
Store the elements in the allocated memory.
Traverse the array arr[] to find the largest element among all the numbers by comparing the values using pointers.
Below is the implementation of the above approach:
C
C++
Java
Python3
C#
// C program for the above approach#include <stdio.h>#include <stdlib.h> // Function to find the largest element// using dynamic memory allocationvoid findLargest(int* arr, int N){ int i; // Traverse the array arr[] for (i = 1; i < N; i++) { // Update the largest element if (*arr < *(arr + i)) { *arr = *(arr + i); } } // Print the largest number printf("%d ", *arr);} // Driver Codeint main(){ int i, N = 4; int* arr; // Memory allocation to arr arr = (int*)calloc(N, sizeof(int)); // Condition for no memory // allocation if (arr == NULL) { printf("No memory allocated"); exit(0); } // Store the elements *(arr + 0) = 14; *(arr + 1) = 12; *(arr + 2) = 19; *(arr + 3) = 20; // Function Call findLargest(arr, N); return 0;}
// C++ program for the above approach#include <iostream>using namespace std; // Function to find the largest element// using dynamic memory allocationvoid findLargest(int* arr, int N){ // Traverse the array arr[] for (int i = 1; i < N; i++) { // Update the largest element if (*arr < *(arr + i)) { *arr = *(arr + i); } } // Print the largest number cout << *arr;} // Driver Codeint main(){ int N = 4; int* arr; // Memory allocation to arr arr = new int[N]; // Condition for no memory // allocation if (arr == NULL) { cout << "No memory allocated"; } // Store the elements *(arr + 0) = 14; *(arr + 1) = 12; *(arr + 2) = 19; *(arr + 3) = 20; // Function Call findLargest(arr, N); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to find the largest element// using dynamic memory allocationstatic void findLargest(int []arr, int N){ // Traverse the array arr[] for (int i = 1; i < N; i++) { // Update the largest element if (arr[0] < (arr[i])) { arr[0] = (arr[i]); } } // Print the largest number System.out.print(arr[0]);} // Driver Codepublic static void main(String[] args){ int N = 4; int []arr; // Memory allocation to arr arr = new int[N]; // Condition for no memory // allocation if (arr.length < N) { System.out.print("No memory allocated"); } // Store the elements arr[0] = 14; arr[1] = 12; arr[2] = 19; arr[3] = 20; // Function Call findLargest(arr, N);}} // This code is contributed by shikhasingrajput
# Python3 program for# the above approach # Function to find the largest element# using dynamic memory allocationdef findLargest(arr, N): # Traverse the array arr for i in range(1, N): # Update the largest element if (arr[0] < (arr[i])): arr[0] = (arr[i]); # Print largest number print(arr[0]); # Driver Codeif __name__ == '__main__': N = 4; # Memory allocation to arr arr = [0] * N; # Condition for no memory # allocation if (len(arr) < N): print("No memory allocated"); # Store the elements arr[0] = 14; arr[1] = 12; arr[2] = 19; arr[3] = 20; # Function Call findLargest(arr, N); # This code is contributed by shikhasingrajput
// C# program for the above approachusing System;class GFG{ // Function to find the largest// element using dynamic memory allocationstatic void findLargest(int []arr, int N){ // Traverse the array []arr for (int i = 1; i < N; i++) { // Update the largest element if (arr[0] < (arr[i])) { arr[0] = (arr[i]); } } // Print the largest number Console.Write(arr[0]);} // Driver Codepublic static void Main(String[] args){ int N = 4; int []arr; // Memory allocation to arr arr = new int[N]; // Condition for no memory // allocation if (arr.Length < N) { Console.Write("No memory allocated"); } // Store the elements arr[0] = 14; arr[1] = 12; arr[2] = 19; arr[3] = 20; // Function Call findLargest(arr, N);}} // This code is contributed by Rajput-Ji
20
Time Complexity: O(N)Auxiliary Space: O(1)
shikhasingrajput
Rajput-Ji
C-Pointers
Dynamic Memory Allocation
Arrays
C Programs
C++ Programs
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Reversal algorithm for array rotation
Window Sliding Technique
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Strings in C
Arrow operator -> in C/C++ with Examples
Header files in C/C++ and its uses
C Program to read contents of Whole File
Basics of File Handling in C | [
{
"code": null,
"e": 26151,
"s": 26123,
"text": "\n17 Sep, 2020"
},
{
"code": null,
"e": 26290,
"s": 26151,
"text": "Given an array arr[] consisting of N integers, the task is to find the largest element in the given array using Dynamic Memory Allocation."
},
{
"code": null,
"e": 26300,
"s": 26290,
"text": "Examples:"
},
{
"code": null,
"e": 26402,
"s": 26300,
"text": "Input: arr[] = {4, 5, 6, 7} Output: 7Explanation:The largest element present in the given array is 7."
},
{
"code": null,
"e": 26508,
"s": 26402,
"text": "Input: arr[] = {8, 9, 10, 12} Output: 12Explanation:The largest element present in the given array is 12."
},
{
"code": null,
"e": 26656,
"s": 26508,
"text": "Approach: The idea here is to use Dynamic Memory for searching the largest element in the given array. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26921,
"s": 26656,
"text": "Take N elements and a pointer to store the address of N elementsAllocate memory dynamically for N elements.Store the elements in the allocated memory.Traverse the array arr[] to find the largest element among all the numbers by comparing the values using pointers."
},
{
"code": null,
"e": 26986,
"s": 26921,
"text": "Take N elements and a pointer to store the address of N elements"
},
{
"code": null,
"e": 27030,
"s": 26986,
"text": "Allocate memory dynamically for N elements."
},
{
"code": null,
"e": 27074,
"s": 27030,
"text": "Store the elements in the allocated memory."
},
{
"code": null,
"e": 27189,
"s": 27074,
"text": "Traverse the array arr[] to find the largest element among all the numbers by comparing the values using pointers."
},
{
"code": null,
"e": 27240,
"s": 27189,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27242,
"s": 27240,
"text": "C"
},
{
"code": null,
"e": 27246,
"s": 27242,
"text": "C++"
},
{
"code": null,
"e": 27251,
"s": 27246,
"text": "Java"
},
{
"code": null,
"e": 27259,
"s": 27251,
"text": "Python3"
},
{
"code": null,
"e": 27262,
"s": 27259,
"text": "C#"
},
{
"code": "// C program for the above approach#include <stdio.h>#include <stdlib.h> // Function to find the largest element// using dynamic memory allocationvoid findLargest(int* arr, int N){ int i; // Traverse the array arr[] for (i = 1; i < N; i++) { // Update the largest element if (*arr < *(arr + i)) { *arr = *(arr + i); } } // Print the largest number printf(\"%d \", *arr);} // Driver Codeint main(){ int i, N = 4; int* arr; // Memory allocation to arr arr = (int*)calloc(N, sizeof(int)); // Condition for no memory // allocation if (arr == NULL) { printf(\"No memory allocated\"); exit(0); } // Store the elements *(arr + 0) = 14; *(arr + 1) = 12; *(arr + 2) = 19; *(arr + 3) = 20; // Function Call findLargest(arr, N); return 0;}",
"e": 28107,
"s": 27262,
"text": null
},
{
"code": "// C++ program for the above approach#include <iostream>using namespace std; // Function to find the largest element// using dynamic memory allocationvoid findLargest(int* arr, int N){ // Traverse the array arr[] for (int i = 1; i < N; i++) { // Update the largest element if (*arr < *(arr + i)) { *arr = *(arr + i); } } // Print the largest number cout << *arr;} // Driver Codeint main(){ int N = 4; int* arr; // Memory allocation to arr arr = new int[N]; // Condition for no memory // allocation if (arr == NULL) { cout << \"No memory allocated\"; } // Store the elements *(arr + 0) = 14; *(arr + 1) = 12; *(arr + 2) = 19; *(arr + 3) = 20; // Function Call findLargest(arr, N); return 0;}",
"e": 28905,
"s": 28107,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the largest element// using dynamic memory allocationstatic void findLargest(int []arr, int N){ // Traverse the array arr[] for (int i = 1; i < N; i++) { // Update the largest element if (arr[0] < (arr[i])) { arr[0] = (arr[i]); } } // Print the largest number System.out.print(arr[0]);} // Driver Codepublic static void main(String[] args){ int N = 4; int []arr; // Memory allocation to arr arr = new int[N]; // Condition for no memory // allocation if (arr.length < N) { System.out.print(\"No memory allocated\"); } // Store the elements arr[0] = 14; arr[1] = 12; arr[2] = 19; arr[3] = 20; // Function Call findLargest(arr, N);}} // This code is contributed by shikhasingrajput",
"e": 29791,
"s": 28905,
"text": null
},
{
"code": "# Python3 program for# the above approach # Function to find the largest element# using dynamic memory allocationdef findLargest(arr, N): # Traverse the array arr for i in range(1, N): # Update the largest element if (arr[0] < (arr[i])): arr[0] = (arr[i]); # Print largest number print(arr[0]); # Driver Codeif __name__ == '__main__': N = 4; # Memory allocation to arr arr = [0] * N; # Condition for no memory # allocation if (len(arr) < N): print(\"No memory allocated\"); # Store the elements arr[0] = 14; arr[1] = 12; arr[2] = 19; arr[3] = 20; # Function Call findLargest(arr, N); # This code is contributed by shikhasingrajput",
"e": 30522,
"s": 29791,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to find the largest// element using dynamic memory allocationstatic void findLargest(int []arr, int N){ // Traverse the array []arr for (int i = 1; i < N; i++) { // Update the largest element if (arr[0] < (arr[i])) { arr[0] = (arr[i]); } } // Print the largest number Console.Write(arr[0]);} // Driver Codepublic static void Main(String[] args){ int N = 4; int []arr; // Memory allocation to arr arr = new int[N]; // Condition for no memory // allocation if (arr.Length < N) { Console.Write(\"No memory allocated\"); } // Store the elements arr[0] = 14; arr[1] = 12; arr[2] = 19; arr[3] = 20; // Function Call findLargest(arr, N);}} // This code is contributed by Rajput-Ji",
"e": 31336,
"s": 30522,
"text": null
},
{
"code": null,
"e": 31347,
"s": 31336,
"text": "20\n\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 31392,
"s": 31349,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31409,
"s": 31392,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 31419,
"s": 31409,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31430,
"s": 31419,
"text": "C-Pointers"
},
{
"code": null,
"e": 31456,
"s": 31430,
"text": "Dynamic Memory Allocation"
},
{
"code": null,
"e": 31463,
"s": 31456,
"text": "Arrays"
},
{
"code": null,
"e": 31474,
"s": 31463,
"text": "C Programs"
},
{
"code": null,
"e": 31487,
"s": 31474,
"text": "C++ Programs"
},
{
"code": null,
"e": 31494,
"s": 31487,
"text": "Arrays"
},
{
"code": null,
"e": 31592,
"s": 31494,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31623,
"s": 31592,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 31661,
"s": 31623,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 31686,
"s": 31661,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 31707,
"s": 31686,
"text": "Next Greater Element"
},
{
"code": null,
"e": 31765,
"s": 31707,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 31778,
"s": 31765,
"text": "Strings in C"
},
{
"code": null,
"e": 31819,
"s": 31778,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 31854,
"s": 31819,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 31895,
"s": 31854,
"text": "C Program to read contents of Whole File"
}
] |
C# | Params - GeeksforGeeks | 19 Jan, 2019
Params is an important keyword in C#. It is used as a parameter which can take the variable number of arguments.
Important Point About Params Keyword :
It is useful when programmer don’t have any prior knowledge about the number of parameters to be used.
Only one Params keyword is allowed and no additional Params will be allowed in function declaration after a params keyword.
The length of params will be zero if no arguments will be passed.
Examples: To illustrate the use of params keyword
Simple program to show the params keyword usage// C# program to illustrate the // use of params keywordusing System;namespace Examples { class Geeks { // function containing params parameters public static int Add(params int[] ListNumbers) { int total = 0; // foreach loop foreach(int i in ListNumbers) { total += i; } return total; } // Driver Code static void Main(string[] args){ // Calling function by passing 5 // arguments as follows int y = Add(12,13,10,15,56); // Displaying result Console.WriteLine(y);}}}Output :106
Explanation : There is no need to define the size of the array because using params keyword in above program, the Integer data will be in the form:ListNumbers[0] 12[1] 13[2] 10[3] 15[4] 56
// C# program to illustrate the // use of params keywordusing System;namespace Examples { class Geeks { // function containing params parameters public static int Add(params int[] ListNumbers) { int total = 0; // foreach loop foreach(int i in ListNumbers) { total += i; } return total; } // Driver Code static void Main(string[] args){ // Calling function by passing 5 // arguments as follows int y = Add(12,13,10,15,56); // Displaying result Console.WriteLine(y);}}}
Output :
106
Explanation : There is no need to define the size of the array because using params keyword in above program, the Integer data will be in the form:ListNumbers[0] 12[1] 13[2] 10[3] 15[4] 56
Object type Params will allow any type of arguments and any number of arguments as follows :// C# program to illustrate the // use of object type paramsusing System; namespace Example2 {class Geeks { // function using object type params public void result(params object[] array) { for (int i = 0; i < array.Length; i++) { // Display result Console.WriteLine(array[i]); } } // Driver Code static void Main(string[] args) { Geeks gfg = new Geeks(); // Variable length arguments gfg.result("Geeks", "GFG", "ProGeek Cup 2.0", "G4G", "100"); } } } Output :Geeks
GFG
ProGeek Cup 2.0
G4G
100
Explanation : In above program the object type params parameter can accept any type of data and any number of arguments.
// C# program to illustrate the // use of object type paramsusing System; namespace Example2 {class Geeks { // function using object type params public void result(params object[] array) { for (int i = 0; i < array.Length; i++) { // Display result Console.WriteLine(array[i]); } } // Driver Code static void Main(string[] args) { Geeks gfg = new Geeks(); // Variable length arguments gfg.result("Geeks", "GFG", "ProGeek Cup 2.0", "G4G", "100"); } } }
Output :
Geeks
GFG
ProGeek Cup 2.0
G4G
100
Explanation : In above program the object type params parameter can accept any type of data and any number of arguments.
CSharp-Basics
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Extension Method in C#
Difference between Ref and Out keywords in C#
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Arrays | [
{
"code": null,
"e": 25179,
"s": 25151,
"text": "\n19 Jan, 2019"
},
{
"code": null,
"e": 25292,
"s": 25179,
"text": "Params is an important keyword in C#. It is used as a parameter which can take the variable number of arguments."
},
{
"code": null,
"e": 25331,
"s": 25292,
"text": "Important Point About Params Keyword :"
},
{
"code": null,
"e": 25434,
"s": 25331,
"text": "It is useful when programmer don’t have any prior knowledge about the number of parameters to be used."
},
{
"code": null,
"e": 25558,
"s": 25434,
"text": "Only one Params keyword is allowed and no additional Params will be allowed in function declaration after a params keyword."
},
{
"code": null,
"e": 25624,
"s": 25558,
"text": "The length of params will be zero if no arguments will be passed."
},
{
"code": null,
"e": 25674,
"s": 25624,
"text": "Examples: To illustrate the use of params keyword"
},
{
"code": null,
"e": 26515,
"s": 25674,
"text": "Simple program to show the params keyword usage// C# program to illustrate the // use of params keywordusing System;namespace Examples { class Geeks { // function containing params parameters public static int Add(params int[] ListNumbers) { int total = 0; // foreach loop foreach(int i in ListNumbers) { total += i; } return total; } // Driver Code static void Main(string[] args){ // Calling function by passing 5 // arguments as follows int y = Add(12,13,10,15,56); // Displaying result Console.WriteLine(y);}}}Output :106\nExplanation : There is no need to define the size of the array because using params keyword in above program, the Integer data will be in the form:ListNumbers[0] 12[1] 13[2] 10[3] 15[4] 56"
},
{
"code": "// C# program to illustrate the // use of params keywordusing System;namespace Examples { class Geeks { // function containing params parameters public static int Add(params int[] ListNumbers) { int total = 0; // foreach loop foreach(int i in ListNumbers) { total += i; } return total; } // Driver Code static void Main(string[] args){ // Calling function by passing 5 // arguments as follows int y = Add(12,13,10,15,56); // Displaying result Console.WriteLine(y);}}}",
"e": 27109,
"s": 26515,
"text": null
},
{
"code": null,
"e": 27118,
"s": 27109,
"text": "Output :"
},
{
"code": null,
"e": 27123,
"s": 27118,
"text": "106\n"
},
{
"code": null,
"e": 27312,
"s": 27123,
"text": "Explanation : There is no need to define the size of the array because using params keyword in above program, the Integer data will be in the form:ListNumbers[0] 12[1] 13[2] 10[3] 15[4] 56"
},
{
"code": null,
"e": 28239,
"s": 27312,
"text": "Object type Params will allow any type of arguments and any number of arguments as follows :// C# program to illustrate the // use of object type paramsusing System; namespace Example2 {class Geeks { // function using object type params public void result(params object[] array) { for (int i = 0; i < array.Length; i++) { // Display result Console.WriteLine(array[i]); } } // Driver Code static void Main(string[] args) { Geeks gfg = new Geeks(); // Variable length arguments gfg.result(\"Geeks\", \"GFG\", \"ProGeek Cup 2.0\", \"G4G\", \"100\"); } } } Output :Geeks\nGFG\nProGeek Cup 2.0\nG4G\n100\nExplanation : In above program the object type params parameter can accept any type of data and any number of arguments."
},
{
"code": "// C# program to illustrate the // use of object type paramsusing System; namespace Example2 {class Geeks { // function using object type params public void result(params object[] array) { for (int i = 0; i < array.Length; i++) { // Display result Console.WriteLine(array[i]); } } // Driver Code static void Main(string[] args) { Geeks gfg = new Geeks(); // Variable length arguments gfg.result(\"Geeks\", \"GFG\", \"ProGeek Cup 2.0\", \"G4G\", \"100\"); } } } ",
"e": 28912,
"s": 28239,
"text": null
},
{
"code": null,
"e": 28921,
"s": 28912,
"text": "Output :"
},
{
"code": null,
"e": 28956,
"s": 28921,
"text": "Geeks\nGFG\nProGeek Cup 2.0\nG4G\n100\n"
},
{
"code": null,
"e": 29077,
"s": 28956,
"text": "Explanation : In above program the object type params parameter can accept any type of data and any number of arguments."
},
{
"code": null,
"e": 29091,
"s": 29077,
"text": "CSharp-Basics"
},
{
"code": null,
"e": 29094,
"s": 29091,
"text": "C#"
},
{
"code": null,
"e": 29192,
"s": 29094,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29220,
"s": 29192,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 29235,
"s": 29220,
"text": "C# | Delegates"
},
{
"code": null,
"e": 29258,
"s": 29235,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 29280,
"s": 29258,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 29303,
"s": 29280,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29349,
"s": 29303,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 29371,
"s": 29349,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 29411,
"s": 29371,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 29442,
"s": 29411,
"text": "Introduction to .NET Framework"
}
] |
How to create a tar file using Python? | Use the tarfile module to create a zip archive of a directory. Walk the directory tree using os.walk and add all the files in it recursively.
import os
import tarfile
def tardir(path, tar_name):
with tarfile.open(tar_name, "w:gz") as tar_handle:
for root, dirs, files in os.walk(path):
for file in files:
tar_handle.add(os.path.join(root, file))
tardir('./my_folder', 'sample.tar.gz')
tar.close()
The above code will compress the contents of my_folder in a file 'sample.tar.gz'. and store it in the current directory. | [
{
"code": null,
"e": 1204,
"s": 1062,
"text": "Use the tarfile module to create a zip archive of a directory. Walk the directory tree using os.walk and add all the files in it recursively."
},
{
"code": null,
"e": 1499,
"s": 1204,
"text": "import os\nimport tarfile\ndef tardir(path, tar_name):\n with tarfile.open(tar_name, \"w:gz\") as tar_handle:\n for root, dirs, files in os.walk(path):\n for file in files:\n tar_handle.add(os.path.join(root, file))\ntardir('./my_folder', 'sample.tar.gz')\ntar.close()"
},
{
"code": null,
"e": 1620,
"s": 1499,
"text": "The above code will compress the contents of my_folder in a file 'sample.tar.gz'. and store it in the current directory."
}
] |
Tryit Editor v3.7 | Tryit: Using the clip property | [] |
Find Simple Closed Path for a given set of points in C++ | Consider we have a set of points. We have to find a simple closed path covering all points. Suppose the points are like below, and the next image is making a closed path on those points.
To get the path, we have to follow these steps −
Find the bottom left point as P
Find the bottom left point as P
Sort other n – 1 point based on the polar angle counterclockwise around P, if polar angle of two points are same, then put them as the distance is shortest
Sort other n – 1 point based on the polar angle counterclockwise around P, if polar angle of two points are same, then put them as the distance is shortest
Traverse the sorted list of points, then make the path
Traverse the sorted list of points, then make the path
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Point {
public:
int x, y;
};
Point p0;
int euclid_dist(Point p1, Point p2) {
return (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y);
}
int orientation(Point p1, Point p2, Point p3) {
int val = (p2.y - p1.y) * (p3.x - p2.x) - (p2.x - p1.x) * (p3.y - p2.y);
if (val == 0) return 0; // colinear
return (val > 0)? 1: 2; // clockwise or counterclock wise
}
int compare(const void *vp1, const void *vp2) {
Point *p1 = (Point *)vp1;
Point *p2 = (Point *)vp2;
int o = orientation(p0, *p1, *p2);
if (o == 0)
return (euclid_dist(p0, *p2) >= euclid_dist(p0, *p1))? -1 : 1;
return (o == 2)? -1: 1;
}
void findClosedPath(Point points[], int n) {
int y_min = points[0].y, min = 0;
for (int i = 1; i < n; i++) {
int y = points[i].y;
if ((y < y_min) || (y_min == y && points[i].x < points[min].x))
y_min = points[i].y, min = i;
}
swap(points[0], points[min]);
p0 = points[0];
qsort(&points[1], n-1, sizeof(Point), compare); //sort on polar angle
for (int i=0; i<n; i++)
cout << "(" << points[i].x << ", "<< points[i].y <<"), ";
}
int main() {
Point points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4},{0, 0}, {1, 2}, {3, 1}, {3, 3}};
int n = sizeof(points)/sizeof(points[0]);
findClosedPath(points, n);
}
(0, 0), (3, 1), (1, 1), (2, 2), (3, 3), (4, 4), (1, 2), (0, 3), | [
{
"code": null,
"e": 1249,
"s": 1062,
"text": "Consider we have a set of points. We have to find a simple closed path covering all points. Suppose the points are like below, and the next image is making a closed path on those points."
},
{
"code": null,
"e": 1298,
"s": 1249,
"text": "To get the path, we have to follow these steps −"
},
{
"code": null,
"e": 1330,
"s": 1298,
"text": "Find the bottom left point as P"
},
{
"code": null,
"e": 1362,
"s": 1330,
"text": "Find the bottom left point as P"
},
{
"code": null,
"e": 1518,
"s": 1362,
"text": "Sort other n – 1 point based on the polar angle counterclockwise around P, if polar angle of two points are same, then put them as the distance is shortest"
},
{
"code": null,
"e": 1674,
"s": 1518,
"text": "Sort other n – 1 point based on the polar angle counterclockwise around P, if polar angle of two points are same, then put them as the distance is shortest"
},
{
"code": null,
"e": 1729,
"s": 1674,
"text": "Traverse the sorted list of points, then make the path"
},
{
"code": null,
"e": 1784,
"s": 1729,
"text": "Traverse the sorted list of points, then make the path"
},
{
"code": null,
"e": 1795,
"s": 1784,
"text": " Live Demo"
},
{
"code": null,
"e": 3124,
"s": 1795,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Point {\n public:\n int x, y;\n};\nPoint p0;\nint euclid_dist(Point p1, Point p2) {\n return (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y);\n}\nint orientation(Point p1, Point p2, Point p3) {\n int val = (p2.y - p1.y) * (p3.x - p2.x) - (p2.x - p1.x) * (p3.y - p2.y);\n if (val == 0) return 0; // colinear\n return (val > 0)? 1: 2; // clockwise or counterclock wise\n}\nint compare(const void *vp1, const void *vp2) {\n Point *p1 = (Point *)vp1;\n Point *p2 = (Point *)vp2;\n int o = orientation(p0, *p1, *p2);\n if (o == 0)\n return (euclid_dist(p0, *p2) >= euclid_dist(p0, *p1))? -1 : 1;\n return (o == 2)? -1: 1;\n}\nvoid findClosedPath(Point points[], int n) {\n int y_min = points[0].y, min = 0;\n for (int i = 1; i < n; i++) {\n int y = points[i].y;\n if ((y < y_min) || (y_min == y && points[i].x < points[min].x))\n y_min = points[i].y, min = i;\n }\n swap(points[0], points[min]);\n p0 = points[0];\n qsort(&points[1], n-1, sizeof(Point), compare); //sort on polar angle\n for (int i=0; i<n; i++)\n cout << \"(\" << points[i].x << \", \"<< points[i].y <<\"), \";\n}\nint main() {\n Point points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4},{0, 0}, {1, 2}, {3, 1}, {3, 3}};\n int n = sizeof(points)/sizeof(points[0]);\n findClosedPath(points, n);\n}"
},
{
"code": null,
"e": 3188,
"s": 3124,
"text": "(0, 0), (3, 1), (1, 1), (2, 2), (3, 3), (4, 4), (1, 2), (0, 3),"
}
] |
Text alignment in a Matplotlib legend | To make text alignment in a matplotlib legend, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create x data points using numpy.
Create x data points using numpy.
Plot x, sin(x) and cos(x) using plot() method.
Plot x, sin(x) and cos(x) using plot() method.
Place legend using legend() method and initialize a method.
Place legend using legend() method and initialize a method.
Iterate the legend.get_texts() method to set the horizontal alignment.
Iterate the legend.get_texts() method to set the horizontal alignment.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-5, 5, 100)
plt.plot(x, np.sin(x), label="$y=sin(x)$")
plt.plot(x, np.cos(x), label="$y=cos(x)$")
legend = plt.legend(loc='upper right')
for t in legend.get_texts():
t.set_ha('left')
plt.show() | [
{
"code": null,
"e": 1143,
"s": 1062,
"text": "To make text alignment in a matplotlib legend, we can take the following steps −"
},
{
"code": null,
"e": 1219,
"s": 1143,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1295,
"s": 1219,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1329,
"s": 1295,
"text": "Create x data points using numpy."
},
{
"code": null,
"e": 1363,
"s": 1329,
"text": "Create x data points using numpy."
},
{
"code": null,
"e": 1410,
"s": 1363,
"text": "Plot x, sin(x) and cos(x) using plot() method."
},
{
"code": null,
"e": 1457,
"s": 1410,
"text": "Plot x, sin(x) and cos(x) using plot() method."
},
{
"code": null,
"e": 1517,
"s": 1457,
"text": "Place legend using legend() method and initialize a method."
},
{
"code": null,
"e": 1577,
"s": 1517,
"text": "Place legend using legend() method and initialize a method."
},
{
"code": null,
"e": 1648,
"s": 1577,
"text": "Iterate the legend.get_texts() method to set the horizontal alignment."
},
{
"code": null,
"e": 1719,
"s": 1648,
"text": "Iterate the legend.get_texts() method to set the horizontal alignment."
},
{
"code": null,
"e": 1761,
"s": 1719,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1803,
"s": 1761,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2165,
"s": 1803,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = np.linspace(-5, 5, 100)\n\nplt.plot(x, np.sin(x), label=\"$y=sin(x)$\")\nplt.plot(x, np.cos(x), label=\"$y=cos(x)$\")\n\nlegend = plt.legend(loc='upper right')\n\nfor t in legend.get_texts():\n t.set_ha('left')\n\nplt.show()"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.