title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to make a Pagination using HTML and CSS ?
13 Jun, 2022 Creating pagination is quite simple, you can easily do that by using Bootstrap, and JavaScript. However, in this article, we will use HTML and CSS to create pagination. Pagination is helpful when the website contains lots of content on a single page, and a single page will not look good with all those topics together. Few websites use the scroll to avoid pagination and vice versa. But the best looks come with the combination of scroll and pagination. As a developer, you can put a few contents on a page to make that page a little scrollable until it’s annoying. After that, you can use pagination that will leave those previous content and proceed to the new content page but the topic will be the same. Creating Structure: In this section, we will just create the basic website structure of the pagination. Here, also we will attach the title attribute so the user can know what will be the content type on the next page of the pagination. HTML code to make the structure: HTML <!DOCTYPE html><html> <head> <title> How to make a Pagination using HTML and CSS ? </title></head> <body> <center> <!-- Header and Slogan --> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> <!-- content in this Section --> <div class="content"> <h3>Interview Experiences:</h3> <article> Share Your Questions/Experience or share your "Interview Experience", please mail your interview experience to [email protected]. Also, to share interview questions, please add questions at Contribute a Question! You can also find company specific Interview Questions at our PRACTICE portal ! </article> </div> <!-- pagination elements --> <div class="pagination_section"> <a href="#"><< Previous</a> <a href="#" title="Algorithm">1</a> <a href="#" title="DataStructure">2</a> <a href="#" title="Languages">3</a> <a href="#" title="Interview" class="active">4</a> <a href="#" title="practice">5</a> <a href="#">Next >></a> </div> </center></body> </html> Designing Structure: In the previous section, we have created the structure of the basic website where we are going to use CSS. CSS code to look good the structure: CSS <style> /* header styling */ h1 { color: green; } /* pagination position styling */ .pagination_section { position: relative; } /* pagination styling */ .pagination_section a { color: black; padding: 10px 18px; text-decoration: none; } /* pagination hover effect on non-active */ .pagination_section a:hover:not(.active) { background-color: #031F3B; color: white; } /* pagination hover effect on active*/ a:nth-child(5) { background-color: green; color: white; } a:nth-child(1) { font-weight: bold; } a:nth-child(7) { font-weight: bold; } .content { margin: 50px; padding: 15px; width: 700px; height: 200px; border: 2px solid black; } </style> Combining the HTML and CSS Code: This is the final code that is the combination of the above two sections. HTML <!DOCTYPE html><html> <head> <title> How to make a Pagination using HTML and CSS ? </title> <style> /* header styling */ h1 { color: green; } /* pagination position styling */ .pagination_section { position: relative; } /* pagination styling */ .pagination_section a { color: black; padding: 10px 18px; text-decoration: none; } /* pagination hover effect on non-active */ .pagination_section a:hover:not(.active) { background-color: #031F3B; color: white; } /* pagination hover effect on active*/ a:nth-child(5) { background-color: green; color: white; } a:nth-child(1) { font-weight: bold; } a:nth-child(7) { font-weight: bold; } .content { margin: 50px; padding: 15px; width: 700px; height: 200px; border: 2px solid black; } </style></head> <body> <center> <!-- Header and Slogan --> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> <!-- content in this Section --> <div class="content"> <h3>Interview Experiences:</h3> <article> Share Your Questions/Experience or share your "Interview Experience", please mail your interview experience to [email protected]. Also, to share interview questions, please add questions at Contribute a Question! You can also find company specific Interview Questions at our PRACTICE portal ! </article> </div> <!-- pagination elements --> <div class="pagination_section"> <a href="#"><< Previous</a> <a href="#" title="Algorithm">1</a> <a href="#" title="DataStructure">2</a> <a href="#" title="Languages">3</a> <a href="#" title="Interview" class="active">4</a> <a href="#" title="practice">5</a> <a href="#">Next >></a> </div> </center></body> </html> Output: HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. CSS is the foundation of web pages and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. arorakashish0911 sanjyotpanure CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Jun, 2022" }, { "code": null, "e": 223, "s": 53, "text": "Creating pagination is quite simple, you can easily do that by using Bootstrap, and JavaScript. However, in this article, we will use HTML and CSS to create pagination. " }, { "code": null, "e": 763, "s": 223, "text": "Pagination is helpful when the website contains lots of content on a single page, and a single page will not look good with all those topics together. Few websites use the scroll to avoid pagination and vice versa. But the best looks come with the combination of scroll and pagination. As a developer, you can put a few contents on a page to make that page a little scrollable until it’s annoying. After that, you can use pagination that will leave those previous content and proceed to the new content page but the topic will be the same." }, { "code": null, "e": 1002, "s": 765, "text": "Creating Structure: In this section, we will just create the basic website structure of the pagination. Here, also we will attach the title attribute so the user can know what will be the content type on the next page of the pagination." }, { "code": null, "e": 1036, "s": 1002, "text": "HTML code to make the structure: " }, { "code": null, "e": 1041, "s": 1036, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to make a Pagination using HTML and CSS ? </title></head> <body> <center> <!-- Header and Slogan --> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> <!-- content in this Section --> <div class=\"content\"> <h3>Interview Experiences:</h3> <article> Share Your Questions/Experience or share your \"Interview Experience\", please mail your interview experience to [email protected]. Also, to share interview questions, please add questions at Contribute a Question! You can also find company specific Interview Questions at our PRACTICE portal ! </article> </div> <!-- pagination elements --> <div class=\"pagination_section\"> <a href=\"#\"><< Previous</a> <a href=\"#\" title=\"Algorithm\">1</a> <a href=\"#\" title=\"DataStructure\">2</a> <a href=\"#\" title=\"Languages\">3</a> <a href=\"#\" title=\"Interview\" class=\"active\">4</a> <a href=\"#\" title=\"practice\">5</a> <a href=\"#\">Next >></a> </div> </center></body> </html>", "e": 2348, "s": 1041, "text": null }, { "code": null, "e": 2476, "s": 2348, "text": "Designing Structure: In the previous section, we have created the structure of the basic website where we are going to use CSS." }, { "code": null, "e": 2513, "s": 2476, "text": "CSS code to look good the structure:" }, { "code": null, "e": 2517, "s": 2513, "text": "CSS" }, { "code": "<style> /* header styling */ h1 { color: green; } /* pagination position styling */ .pagination_section { position: relative; } /* pagination styling */ .pagination_section a { color: black; padding: 10px 18px; text-decoration: none; } /* pagination hover effect on non-active */ .pagination_section a:hover:not(.active) { background-color: #031F3B; color: white; } /* pagination hover effect on active*/ a:nth-child(5) { background-color: green; color: white; } a:nth-child(1) { font-weight: bold; } a:nth-child(7) { font-weight: bold; } .content { margin: 50px; padding: 15px; width: 700px; height: 200px; border: 2px solid black; } </style>", "e": 3239, "s": 2517, "text": null }, { "code": null, "e": 3347, "s": 3239, "text": "Combining the HTML and CSS Code: This is the final code that is the combination of the above two sections. " }, { "code": null, "e": 3352, "s": 3347, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to make a Pagination using HTML and CSS ? </title> <style> /* header styling */ h1 { color: green; } /* pagination position styling */ .pagination_section { position: relative; } /* pagination styling */ .pagination_section a { color: black; padding: 10px 18px; text-decoration: none; } /* pagination hover effect on non-active */ .pagination_section a:hover:not(.active) { background-color: #031F3B; color: white; } /* pagination hover effect on active*/ a:nth-child(5) { background-color: green; color: white; } a:nth-child(1) { font-weight: bold; } a:nth-child(7) { font-weight: bold; } .content { margin: 50px; padding: 15px; width: 700px; height: 200px; border: 2px solid black; } </style></head> <body> <center> <!-- Header and Slogan --> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> <!-- content in this Section --> <div class=\"content\"> <h3>Interview Experiences:</h3> <article> Share Your Questions/Experience or share your \"Interview Experience\", please mail your interview experience to [email protected]. Also, to share interview questions, please add questions at Contribute a Question! You can also find company specific Interview Questions at our PRACTICE portal ! </article> </div> <!-- pagination elements --> <div class=\"pagination_section\"> <a href=\"#\"><< Previous</a> <a href=\"#\" title=\"Algorithm\">1</a> <a href=\"#\" title=\"DataStructure\">2</a> <a href=\"#\" title=\"Languages\">3</a> <a href=\"#\" title=\"Interview\" class=\"active\">4</a> <a href=\"#\" title=\"practice\">5</a> <a href=\"#\">Next >></a> </div> </center></body> </html>", "e": 5642, "s": 3352, "text": null }, { "code": null, "e": 5651, "s": 5642, "text": "Output: " }, { "code": null, "e": 5852, "s": 5653, "text": "HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 6043, "s": 5852, "text": "CSS is the foundation of web pages and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 6060, "s": 6043, "text": "arorakashish0911" }, { "code": null, "e": 6074, "s": 6060, "text": "sanjyotpanure" }, { "code": null, "e": 6083, "s": 6074, "text": "CSS-Misc" }, { "code": null, "e": 6093, "s": 6083, "text": "HTML-Misc" }, { "code": null, "e": 6097, "s": 6093, "text": "CSS" }, { "code": null, "e": 6102, "s": 6097, "text": "HTML" }, { "code": null, "e": 6119, "s": 6102, "text": "Web Technologies" }, { "code": null, "e": 6146, "s": 6119, "text": "Web technologies Questions" }, { "code": null, "e": 6151, "s": 6146, "text": "HTML" }, { "code": null, "e": 6249, "s": 6151, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6297, "s": 6249, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 6359, "s": 6297, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6409, "s": 6359, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 6467, "s": 6409, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 6517, "s": 6467, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 6565, "s": 6517, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 6627, "s": 6565, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6677, "s": 6627, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 6701, "s": 6677, "text": "REST API (Introduction)" } ]
Learning Vector Quantization
16 May, 2022 Learning Vector Quantization ( or LVQ ) is a type of Artificial Neural Network which also inspired by biological models of neural systems. It is based on prototype supervised learning classification algorithm and trained its network through a competitive learning algorithm similar to Self Organizing Map. It can also deal with the multiclass classification problem. LVQ has two layers, one is the Input layer and the other one is the Output layer. The architecture of the Learning Vector Quantization with the number of classes in an input data and n number of input features for any sample is given below: Let’s say that an input data of size ( m, n ) where m is the number of training examples and n is the number of features in each example and a label vector of size ( m, 1 ). First, it initializes the weights of size ( n, c ) from the first c number of training samples with different labels and should be discarded from all training samples. Here, c is the number of classes. Then iterate over the remaining input data, for each training example, it updates the winning vector ( weight vector with the shortest distance ( e.g Euclidean distance ) from the training example ). The weight updation rule is given by: if correctly_classified: wij(new) = wij(old) + alpha(t) * (xik - wij(old)) else: wij(new) = wij(old) - alpha(t) * (xik - wij(old)) where alpha is a learning rate at time t, j denotes the winning vector, i denotes the ith feature of training example and k denotes the kth training example from the input data. After training the LVQ network, trained weights are used for classifying new examples. A new example is labelled with the class of the winning vector. Steps involved are : Weight initialization For 1 to N number of epochs Select a training example Compute the winning vector Update the winning vector Repeat steps 3, 4, 5 for all training example. Classify test sample Below is the implementation. Python3 import math class LVQ : # Function here computes the winning vector # by Euclidean distance def winner( self, weights, sample ) : D0 = 0 D1 = 0 for i in range( len( sample ) ) : D0 = D0 + math.pow( ( sample[i] - weights[0][i] ), 2 ) D1 = D1 + math.pow( ( sample[i] - weights[1][i] ), 2 ) if D0 > D1 : return 0 else : return 1 # Function here updates the winning vector def update( self, weights, sample, J, alpha, actual ) : if actual -- j: for i in range(len(weights)) : weights[J][i] = weights[J][i] + alpha * ( sample[i] - weights[J][i] ) else: for i in range(len(weights)) : weights[J][i] = weights[J][i] - alpha * ( sample[i] - weights[J][i] ) # Driver codedef main() : # Training Samples ( m, n ) with their class vector X = [[ 0, 0, 1, 1 ], [ 1, 0, 0, 0 ], [ 0, 0, 0, 1 ], [ 0, 1, 1, 0 ], [ 1, 1, 0, 0 ], [ 1, 1, 1, 0 ],] Y = [ 0, 1, 0, 1, 1, 1 ] m, n = len( X ), len( X[0] ) # weight initialization ( n, c ) weights = [] weights.append( X.pop( 0 ) ) weights.append( X.pop( 0 ) ) # Samples used in weight initialization will # not use in training m = m - 2 Y.pop(0) Y.pop(0) # training ob = LVQ() epochs = 3 alpha = 0.1 for i in range( epochs ) : for j in range( m ) : # Sample selection T = X[j] # Compute winner J = ob.winner( weights, T ) # Update weights ob.update( weights, T, J, alpha , Y[j]) # classify new input sample T = [ 0, 0, 1, 0 ] J = ob.winner( weights, T ) print( "Sample T belongs to class : ", J ) print( "Trained weights : ", weights ) if __name__ == "__main__": main() prashadbhonsle031 abhinavhfs Deep-Learning Advanced Computer Subject Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n16 May, 2022" }, { "code": null, "e": 663, "s": 54, "text": "Learning Vector Quantization ( or LVQ ) is a type of Artificial Neural Network which also inspired by biological models of neural systems. It is based on prototype supervised learning classification algorithm and trained its network through a competitive learning algorithm similar to Self Organizing Map. It can also deal with the multiclass classification problem. LVQ has two layers, one is the Input layer and the other one is the Output layer. The architecture of the Learning Vector Quantization with the number of classes in an input data and n number of input features for any sample is given below: " }, { "code": null, "e": 1240, "s": 663, "text": "Let’s say that an input data of size ( m, n ) where m is the number of training examples and n is the number of features in each example and a label vector of size ( m, 1 ). First, it initializes the weights of size ( n, c ) from the first c number of training samples with different labels and should be discarded from all training samples. Here, c is the number of classes. Then iterate over the remaining input data, for each training example, it updates the winning vector ( weight vector with the shortest distance ( e.g Euclidean distance ) from the training example ). " }, { "code": null, "e": 1278, "s": 1240, "text": "The weight updation rule is given by:" }, { "code": null, "e": 1409, "s": 1278, "text": "if correctly_classified:\nwij(new) = wij(old) + alpha(t) * (xik - wij(old))\nelse:\nwij(new) = wij(old) - alpha(t) * (xik - wij(old))" }, { "code": null, "e": 1738, "s": 1409, "text": "where alpha is a learning rate at time t, j denotes the winning vector, i denotes the ith feature of training example and k denotes the kth training example from the input data. After training the LVQ network, trained weights are used for classifying new examples. A new example is labelled with the class of the winning vector." }, { "code": null, "e": 1759, "s": 1738, "text": "Steps involved are :" }, { "code": null, "e": 1781, "s": 1759, "text": "Weight initialization" }, { "code": null, "e": 1809, "s": 1781, "text": "For 1 to N number of epochs" }, { "code": null, "e": 1835, "s": 1809, "text": "Select a training example" }, { "code": null, "e": 1862, "s": 1835, "text": "Compute the winning vector" }, { "code": null, "e": 1888, "s": 1862, "text": "Update the winning vector" }, { "code": null, "e": 1935, "s": 1888, "text": "Repeat steps 3, 4, 5 for all training example." }, { "code": null, "e": 1956, "s": 1935, "text": "Classify test sample" }, { "code": null, "e": 1986, "s": 1956, "text": "Below is the implementation. " }, { "code": null, "e": 1994, "s": 1986, "text": "Python3" }, { "code": "import math class LVQ : # Function here computes the winning vector # by Euclidean distance def winner( self, weights, sample ) : D0 = 0 D1 = 0 for i in range( len( sample ) ) : D0 = D0 + math.pow( ( sample[i] - weights[0][i] ), 2 ) D1 = D1 + math.pow( ( sample[i] - weights[1][i] ), 2 ) if D0 > D1 : return 0 else : return 1 # Function here updates the winning vector def update( self, weights, sample, J, alpha, actual ) : if actual -- j: for i in range(len(weights)) : weights[J][i] = weights[J][i] + alpha * ( sample[i] - weights[J][i] ) else: for i in range(len(weights)) : weights[J][i] = weights[J][i] - alpha * ( sample[i] - weights[J][i] ) # Driver codedef main() : # Training Samples ( m, n ) with their class vector X = [[ 0, 0, 1, 1 ], [ 1, 0, 0, 0 ], [ 0, 0, 0, 1 ], [ 0, 1, 1, 0 ], [ 1, 1, 0, 0 ], [ 1, 1, 1, 0 ],] Y = [ 0, 1, 0, 1, 1, 1 ] m, n = len( X ), len( X[0] ) # weight initialization ( n, c ) weights = [] weights.append( X.pop( 0 ) ) weights.append( X.pop( 0 ) ) # Samples used in weight initialization will # not use in training m = m - 2 Y.pop(0) Y.pop(0) # training ob = LVQ() epochs = 3 alpha = 0.1 for i in range( epochs ) : for j in range( m ) : # Sample selection T = X[j] # Compute winner J = ob.winner( weights, T ) # Update weights ob.update( weights, T, J, alpha , Y[j]) # classify new input sample T = [ 0, 0, 1, 0 ] J = ob.winner( weights, T ) print( \"Sample T belongs to class : \", J ) print( \"Trained weights : \", weights ) if __name__ == \"__main__\": main()", "e": 3931, "s": 1994, "text": null }, { "code": null, "e": 3949, "s": 3931, "text": "prashadbhonsle031" }, { "code": null, "e": 3960, "s": 3949, "text": "abhinavhfs" }, { "code": null, "e": 3974, "s": 3960, "text": "Deep-Learning" }, { "code": null, "e": 4000, "s": 3974, "text": "Advanced Computer Subject" }, { "code": null, "e": 4007, "s": 4000, "text": "Python" } ]
How to merge properties of two JavaScript objects dynamically?
22 Apr, 2019 Using Spread Operator: Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected. It allows the privilege to obtain a list of parameters from an array. Javascript objects are key-value paired dictionaries. We can merge different objects into one using the spread (...) operator.Syntax: object1 = {...object2, ...object3, ... } Example 1: <script>let A = { name: "geeksforgeeks",}; let B = { domain: "https://geeksforgeeks.org"}; let Sites = { ...A, ...B }; console.log(Sites)</script> Output: Example 2: Suppose the objects have the same keys. In this case, the value of the key of the object which appears later in the distribution is used. <script>let A = { name: "geeksforgeeks",}; let B = { name: "wordpress"}; let Sites = { ...A, ...B }; console.log(Sites)</script> Output: Another method: We can also use the Object.assign() method to merge different objects. Example: <script>let A = { name: "geeksforgeeks",}; let B = { domain: "https://geeksforgeeks.org"}; let Sites = Object.assign(A, B); console.log(Sites);</script> Output: javascript-object Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2019" }, { "code": null, "e": 297, "s": 28, "text": "Using Spread Operator: Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected. It allows the privilege to obtain a list of parameters from an array." }, { "code": null, "e": 431, "s": 297, "text": "Javascript objects are key-value paired dictionaries. We can merge different objects into one using the spread (...) operator.Syntax:" }, { "code": null, "e": 473, "s": 431, "text": "object1 = {...object2, ...object3, ... }\n" }, { "code": null, "e": 484, "s": 473, "text": "Example 1:" }, { "code": "<script>let A = { name: \"geeksforgeeks\",}; let B = { domain: \"https://geeksforgeeks.org\"}; let Sites = { ...A, ...B }; console.log(Sites)</script>", "e": 640, "s": 484, "text": null }, { "code": null, "e": 648, "s": 640, "text": "Output:" }, { "code": null, "e": 797, "s": 648, "text": "Example 2: Suppose the objects have the same keys. In this case, the value of the key of the object which appears later in the distribution is used." }, { "code": "<script>let A = { name: \"geeksforgeeks\",}; let B = { name: \"wordpress\"}; let Sites = { ...A, ...B }; console.log(Sites)</script>", "e": 935, "s": 797, "text": null }, { "code": null, "e": 943, "s": 935, "text": "Output:" }, { "code": null, "e": 1030, "s": 943, "text": "Another method: We can also use the Object.assign() method to merge different objects." }, { "code": null, "e": 1039, "s": 1030, "text": "Example:" }, { "code": "<script>let A = { name: \"geeksforgeeks\",}; let B = { domain: \"https://geeksforgeeks.org\"}; let Sites = Object.assign(A, B); console.log(Sites);</script>", "e": 1197, "s": 1039, "text": null }, { "code": null, "e": 1205, "s": 1197, "text": "Output:" }, { "code": null, "e": 1223, "s": 1205, "text": "javascript-object" }, { "code": null, "e": 1230, "s": 1223, "text": "Picked" }, { "code": null, "e": 1241, "s": 1230, "text": "JavaScript" }, { "code": null, "e": 1258, "s": 1241, "text": "Web Technologies" }, { "code": null, "e": 1285, "s": 1258, "text": "Web technologies Questions" }, { "code": null, "e": 1383, "s": 1285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1444, "s": 1383, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1516, "s": 1444, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1556, "s": 1516, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1597, "s": 1556, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1639, "s": 1597, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 1672, "s": 1639, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1734, "s": 1672, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1795, "s": 1734, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1845, "s": 1795, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python Random Module
14 Dec, 2021 Python Random module is an in-built module of Python which is used to generate random numbers. These are pseudo-random numbers means these are not truly random. This module can be used to perform random actions such as generating random numbers, print random a value for a list or string, etc. Example: Printing a random value from a list Python3 # import randomimport random # prints a random value from the listlist1 = [1, 2, 3, 4, 5, 6]print(random.choice(list1)) Output: 2 As stated above random module creates pseudo-random numbers. Random numbers depend on the seeding value. For example, if the seeding value is 5 then the output of the below program will always be the same. Example: Creating random numbers with seeding value Python3 import random random.seed(5) print(random.random())print(random.random()) Output: 0.6229016948897019 0.7417869892607294 The output of the above code will always be the same. Therefore, it must not be used for encryption. Let’s discuss some common operations performed by this module. random.randint() method is used to generate random integers between the given range. Syntax : randint(start, end) Example: Creating random integers Python3 # Python3 program explaining work# of randint() function # import random moduleimport random # Generates a random number between# a given positive ranger1 = random.randint(5, 15)print("Random number between 5 and 15 is % s" % (r1)) # Generates a random number between# two given negative ranger2 = random.randint(-10, -2)print("Random number between -10 and -2 is % d" % (r2)) Output: Random number between 5 and 15 is 7 Random number between -10 and -2 is -9 random.random() method is used to generate random floats between 0.0 to 1. Syntax: random.random() Example: Python3 # Python3 program to demonstrate# the use of random() function . # import randomfrom random import random # Prints random itemprint(random()) Output: 0.3717933555623072 random.choice() function is used to return a random item from a list, tuple, or string. Syntax: random.choice(sequence) Example: Selecting random elements from the list, string, and tuple Python3 # Python3 program to demonstrate the use of# choice() method # import randomimport random # prints a random value from the listlist1 = [1, 2, 3, 4, 5, 6]print(random.choice(list1)) # prints a random item from the stringstring = "geeks"print(random.choice(string)) # prints a random item from the tupletuple1 = (1, 2, 3, 4, 5)print(random.choice(tuple1)) Output: 2 k 5 random.shuffle() method is used to shuffle a sequence (list). Shuffling means changing the position of the elements of the sequence. Here, the shuffling operation is inplace. Syntax: random.shuffle(sequence, function) Example: Shuffling a List Python3 # import the random moduleimport random # declare a listsample_list = [1, 2, 3, 4, 5] print("Original list : ")print(sample_list) # first shufflerandom.shuffle(sample_list)print("\nAfter the first shuffle : ")print(sample_list) # second shufflerandom.shuffle(sample_list)print("\nAfter the second shuffle : ")print(sample_list) Output: Original list : [1, 2, 3, 4, 5] After the first shuffle : [4, 3, 5, 2, 1] After the second shuffle : [1, 3, 4, 5, 2] mishrapriyank17 Python-random Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Dec, 2021" }, { "code": null, "e": 346, "s": 52, "text": "Python Random module is an in-built module of Python which is used to generate random numbers. These are pseudo-random numbers means these are not truly random. This module can be used to perform random actions such as generating random numbers, print random a value for a list or string, etc." }, { "code": null, "e": 391, "s": 346, "text": "Example: Printing a random value from a list" }, { "code": null, "e": 399, "s": 391, "text": "Python3" }, { "code": "# import randomimport random # prints a random value from the listlist1 = [1, 2, 3, 4, 5, 6]print(random.choice(list1))", "e": 520, "s": 399, "text": null }, { "code": null, "e": 528, "s": 520, "text": "Output:" }, { "code": null, "e": 530, "s": 528, "text": "2" }, { "code": null, "e": 736, "s": 530, "text": "As stated above random module creates pseudo-random numbers. Random numbers depend on the seeding value. For example, if the seeding value is 5 then the output of the below program will always be the same." }, { "code": null, "e": 788, "s": 736, "text": "Example: Creating random numbers with seeding value" }, { "code": null, "e": 796, "s": 788, "text": "Python3" }, { "code": "import random random.seed(5) print(random.random())print(random.random())", "e": 872, "s": 796, "text": null }, { "code": null, "e": 880, "s": 872, "text": "Output:" }, { "code": null, "e": 918, "s": 880, "text": "0.6229016948897019\n0.7417869892607294" }, { "code": null, "e": 1019, "s": 918, "text": "The output of the above code will always be the same. Therefore, it must not be used for encryption." }, { "code": null, "e": 1082, "s": 1019, "text": "Let’s discuss some common operations performed by this module." }, { "code": null, "e": 1167, "s": 1082, "text": "random.randint() method is used to generate random integers between the given range." }, { "code": null, "e": 1176, "s": 1167, "text": "Syntax :" }, { "code": null, "e": 1196, "s": 1176, "text": "randint(start, end)" }, { "code": null, "e": 1230, "s": 1196, "text": "Example: Creating random integers" }, { "code": null, "e": 1238, "s": 1230, "text": "Python3" }, { "code": "# Python3 program explaining work# of randint() function # import random moduleimport random # Generates a random number between# a given positive ranger1 = random.randint(5, 15)print(\"Random number between 5 and 15 is % s\" % (r1)) # Generates a random number between# two given negative ranger2 = random.randint(-10, -2)print(\"Random number between -10 and -2 is % d\" % (r2))", "e": 1618, "s": 1238, "text": null }, { "code": null, "e": 1626, "s": 1618, "text": "Output:" }, { "code": null, "e": 1701, "s": 1626, "text": "Random number between 5 and 15 is 7\nRandom number between -10 and -2 is -9" }, { "code": null, "e": 1776, "s": 1701, "text": "random.random() method is used to generate random floats between 0.0 to 1." }, { "code": null, "e": 1785, "s": 1776, "text": "Syntax: " }, { "code": null, "e": 1801, "s": 1785, "text": "random.random()" }, { "code": null, "e": 1810, "s": 1801, "text": "Example:" }, { "code": null, "e": 1818, "s": 1810, "text": "Python3" }, { "code": "# Python3 program to demonstrate# the use of random() function . # import randomfrom random import random # Prints random itemprint(random())", "e": 1970, "s": 1818, "text": null }, { "code": null, "e": 1978, "s": 1970, "text": "Output:" }, { "code": null, "e": 1997, "s": 1978, "text": "0.3717933555623072" }, { "code": null, "e": 2085, "s": 1997, "text": "random.choice() function is used to return a random item from a list, tuple, or string." }, { "code": null, "e": 2093, "s": 2085, "text": "Syntax:" }, { "code": null, "e": 2117, "s": 2093, "text": "random.choice(sequence)" }, { "code": null, "e": 2185, "s": 2117, "text": "Example: Selecting random elements from the list, string, and tuple" }, { "code": null, "e": 2193, "s": 2185, "text": "Python3" }, { "code": "# Python3 program to demonstrate the use of# choice() method # import randomimport random # prints a random value from the listlist1 = [1, 2, 3, 4, 5, 6]print(random.choice(list1)) # prints a random item from the stringstring = \"geeks\"print(random.choice(string)) # prints a random item from the tupletuple1 = (1, 2, 3, 4, 5)print(random.choice(tuple1))", "e": 2551, "s": 2193, "text": null }, { "code": null, "e": 2559, "s": 2551, "text": "Output:" }, { "code": null, "e": 2565, "s": 2559, "text": "2\nk\n5" }, { "code": null, "e": 2740, "s": 2565, "text": "random.shuffle() method is used to shuffle a sequence (list). Shuffling means changing the position of the elements of the sequence. Here, the shuffling operation is inplace." }, { "code": null, "e": 2748, "s": 2740, "text": "Syntax:" }, { "code": null, "e": 2783, "s": 2748, "text": "random.shuffle(sequence, function)" }, { "code": null, "e": 2809, "s": 2783, "text": "Example: Shuffling a List" }, { "code": null, "e": 2817, "s": 2809, "text": "Python3" }, { "code": "# import the random moduleimport random # declare a listsample_list = [1, 2, 3, 4, 5] print(\"Original list : \")print(sample_list) # first shufflerandom.shuffle(sample_list)print(\"\\nAfter the first shuffle : \")print(sample_list) # second shufflerandom.shuffle(sample_list)print(\"\\nAfter the second shuffle : \")print(sample_list)", "e": 3151, "s": 2817, "text": null }, { "code": null, "e": 3159, "s": 3151, "text": "Output:" }, { "code": null, "e": 3281, "s": 3159, "text": "Original list : \n[1, 2, 3, 4, 5]\n\nAfter the first shuffle : \n[4, 3, 5, 2, 1]\n\nAfter the second shuffle : \n[1, 3, 4, 5, 2]" }, { "code": null, "e": 3297, "s": 3281, "text": "mishrapriyank17" }, { "code": null, "e": 3311, "s": 3297, "text": "Python-random" }, { "code": null, "e": 3318, "s": 3311, "text": "Python" }, { "code": null, "e": 3416, "s": 3318, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3444, "s": 3416, "text": "Read JSON file using Python" }, { "code": null, "e": 3466, "s": 3444, "text": "Python map() function" }, { "code": null, "e": 3516, "s": 3466, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3534, "s": 3516, "text": "Python Dictionary" }, { "code": null, "e": 3578, "s": 3534, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 3620, "s": 3578, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3643, "s": 3620, "text": "Taking input in Python" }, { "code": null, "e": 3665, "s": 3643, "text": "Enumerate() in Python" }, { "code": null, "e": 3700, "s": 3665, "text": "Read a file line by line in Python" } ]
MFC - Quick Guide
The Microsoft Foundation Class (MFC) library provides a set of functions, constants, data types, and classes to simplify creating applications for the Microsoft Windows operating systems. In this tutorial, you will learn all about how to start and create windows based applications using MFC. We have assumed that you know the following − A little about programming for Windows. The basics of programming in C++. Understand the fundamentals of object-oriented programming. The Microsoft Foundation Class Library (MFC) is an "application framework" for programming in Microsoft Windows. MFC provides much of the code, which are required for the following − Managing Windows. Menus and dialog boxes. Performing basic input/output. Storing collections of data objects, etc. You can easily extend or override the basic functionality the MFC framework in you C++ applications by adding your application-specific code into MFC framework. The MFC framework provides a set of reusable classes designed to simplify Windows programming. The MFC framework provides a set of reusable classes designed to simplify Windows programming. MFC provides classes for many basic objects, such as strings, files, and collections that are used in everyday programming. MFC provides classes for many basic objects, such as strings, files, and collections that are used in everyday programming. It also provides classes for common Windows APIs and data structures, such as windows, controls, and device contexts. It also provides classes for common Windows APIs and data structures, such as windows, controls, and device contexts. The framework also provides a solid foundation for more advanced features, such as ActiveX and document view processing. The framework also provides a solid foundation for more advanced features, such as ActiveX and document view processing. In addition, MFC provides an application framework, including the classes that make up the application architecture hierarchy. In addition, MFC provides an application framework, including the classes that make up the application architecture hierarchy. The MFC framework is a powerful approach that lets you build upon the work of expert programmers for Windows. MFC framework has the following advantages. It shortens development time. It shortens development time. It makes code more portable. It makes code more portable. It also provides tremendous support without reducing programming freedom and flexibility. It also provides tremendous support without reducing programming freedom and flexibility. It gives easy access to "hard to program" user-interface elements and technologies. It gives easy access to "hard to program" user-interface elements and technologies. MFC simplifies database programming through Data Access Objects (DAO) and Open Database Connectivity (ODBC), and network programming through Windows Sockets. MFC simplifies database programming through Data Access Objects (DAO) and Open Database Connectivity (ODBC), and network programming through Windows Sockets. Microsoft Visual C++ is a programming environment used to create applications for the Microsoft Windows operating systems. To use MFC framework in your C++ application, you must have installed either Microsoft Visual C++ or Microsoft Visual Studio. Microsoft Visual Studio also contains the Microsoft Visual C++ environment. Microsoft provides a free version of visual studio which also contains SQL Server and it can be downloaded from https://www.visualstudio.com/en-us/downloads/downloadvisual- studio-vs.aspx. Following are the installation steps. Step 1 − Once Visual Studio is downloaded, run the installer. The following dialog box will be displayed. Step 2 − Click Install to start the installation process. Step 3 − Once Visual Studio is installed successfully, you will see the following dialog box. Step 4 − Close this dialog box and restart your computer if required. Step 5 − Open Visual studio from the Start menu, which will open the following dialog box. It will take some time for preparation, while starting for the first time. Step 6 − Next, you will see the main window of Visual Studio. Step 7 − You are now ready to start your application. In this chapter, we will be covering the different types of VC++ projects. Visual Studio includes several kinds of Visual C++ project templates. These templates help to create the basic program structure, menus, toolbars, icons, references, and include statements that are appropriate for the kind of project you want to create. Following are some of the salient features of the templates. It provides wizards for many of these project templates and helps you customize your projects as you create them. It provides wizards for many of these project templates and helps you customize your projects as you create them. Once the project is created, you can build and run the application. Once the project is created, you can build and run the application. You don't have to use a template to create a project, but in most cases it's more efficient to use project templates. You don't have to use a template to create a project, but in most cases it's more efficient to use project templates. It's easier to modify the provided project files and structure than it is to create them from scratch. It's easier to modify the provided project files and structure than it is to create them from scratch. In MFC, you can use the following project templates. MFC Application An MFC application is an executable application for Windows that is based on the Microsoft Foundation Class (MFC) Library. The easiest way to create an MFC application is to use the MFC Application Wizard. MFC ActiveX Control ActiveX control programs are modular programs designed to give a specific type of functionality to a parent application. For example, you can create a control such as a button for use in a dialog, or toolbar or on a Web page. MFC DLL An MFC DLL is a binary file that acts as a shared library of functions that can be used simultaneously by multiple applications. The easiest way to create an MFC DLL project is to use the MFC DLL Wizard. Following are some General templates which can also be used to create MFC application − Empty Project Projects are the logical containers for everything that's needed to build your application. You can then add more new or existing projects to the solution if necessary. Custom Wizard The Visual C++ Custom Wizard is the tool to use when you need to create a new custom wizard. The easiest way to create a custom wizard is to use the Custom Wizard. In this chapter, we will look at a working MFC example. To create an MFC application, you can use wizards to customize your projects. You can also create an application from scratch. Following are the steps to create a project using project templates available in Visual Studio. Step 1 − Open the Visual studio and click on the File → New → Project menu option. Step 2 − You can now see that the New Project dialog box is open. Step 3 − From the left pane, select Templates → Visual C++ → MFC Step 4 − In the middle pane, select MFC Application. Step 5 − Enter the project name ‘MFCDemo’ in the Name field and click OK to continue. You will see the following dialog. Step 6 − Click Next. Step 7 − Select the options which are shown in the dialog box given above and click Next. Step 8 − Uncheck all options and click Finish button. You can now see that the MFC wizard creates this Dialog Box and the project files by default. Step 9 − Run this application, you will see the following output. You can also create an MFC application from scratch. To create an MFC application, you need to follow the following Steps. Step 1 − Open the Visual studio and click on the File → New → Project menu option. Step 2 − You can now see the New Project dialog box. Step 3 − From the left pane, select Templates → Visual C++ → General. Step 4 − In the middle pane, select Empty Step 5 − Enter project name ‘MFCDemoFromScratch’ in the Name field and click OK to continue. You will see that an empty project is created. Step 6 − To make it an MFC project, right-click on the project and select Properties. Step 7 − In the left section, click Configuration Properties → General. Step 8 − Select the Use MFC in Shared DLL option in Project Defaults section and click OK. Step 9 − As it is an empty project now; we need to add a C++ file. So, right-click on the project and select Add → New Item... Step 10 − Select C++ File (.cpp) in the middle pane and enter file name in the Name field and click Add button. Step 11 − You can now see the main.cpp file added under the Source Files folder. Step 12 − Let us add the following code in this file. #include <iostream> using namespace std; void main() { cout << "***************************************\n"; cout << "MFC Application Tutorial"; cout << "\n***************************************"; getchar(); } Step 13 − When you run this application, you will see the following output on console. *************************************** MFC Application Tutorial *************************************** In this chapter, we will be covering the fundamentals of Windows. To create a program, also called an application, you derive a class from the MFC's CWinApp. CWinApp stands for Class for a Windows Application. Let us look into a simple example by creating a new Win32 project. Step 1 − Open the Visual studio and click on the File → New → Project menu option. Step 2 − You can now see the New Project dialog box. Step 3 − From the left pane, select Templates → Visual C++ → Win32. Step 4 − In the middle pane, select Win32 Project. Step 5 − Enter the project name ‘MFCWindowDemo’ in the Name field and click OK to continue. You will see the following dialog box. Step 6 − Click Next. Step 7 − Select the options as shown in the dialog box given above and click Finish. Step 8 − An empty project is created. Step 9 − To make it an MFC project, right-click on the project and select Properties. Step 10 − In the left section, click Configuration Properties → General. Step 11 − Select the Use MFC in Shared DLL option in Project Defaults section and click OK. Step 12 − Add a new source file. Step 13 − Right-click on your Project and select Add → New Item... Step 14 − In the Templates section, click C++ File (.cpp). Step 15 − Set the Name as Example and click Add. Any application has two main sections − Class Frame or Window Let us create a window using the following steps − Step 1 − To create an application, we need to derive a class from the MFC's CWinApp. #include class CExample : public CWinApp { BOOL InitInstance() { return TRUE; } }; Step 2 − We also need a frame/window to show the content of our application. Step 3 − For this, we need to add another class and derive it from the MFC's CFrameWnd class and implement its constructor and a call the Create() method, which will create a frame/window as shown in the following code. class CMyFrame : public CFrameWnd { public: CMyFrame() { Create(NULL, _T("MFC Application Tutorial")); } }; Step 4 − As you can see that Create() method needs two parameters, the name of the class, which should be passed as NULL, and the name of the window, which is the string that will be shown on the title bar. After creating a window, to let the application use it, you can use a pointer to show the class used to create the window. In this case, the pointer would be CFrameWnd. To use the frame window, assign its pointer to the CWinThread::m_pMainWnd member variable. This is done in the InitInstance() implementation of your application. Step 1 − Here is the implementation of InitInstance() in CExample class. class CExample : public CWinApp { BOOL InitInstance() { CMyFrame *Frame = new CMyFrame(); m_pMainWnd = Frame; Frame->ShowWindow(SW_NORMAL); Frame->UpdateWindow(); return TRUE; } }; Step 2 − Following is the complete implementation of Example.cpp file. #include <afxwin.h> class CMyFrame : public CFrameWnd { public: CMyFrame() { Create(NULL, _T("MFC Application Tutorial")); } }; class CExample : public CWinApp { BOOL InitInstance() { CMyFrame *Frame = new CMyFrame(); m_pMainWnd = Frame; Frame->ShowWindow(SW_NORMAL); Frame->UpdateWindow(); return TRUE; } }; CExample theApp; Step 3 − When we run the above application, the following window is created. Windows styles are characteristics that control features such as window appearance, borders, minimized or maximized state, or other resizing states, etc. WS_BORDER Creates a window that has a border. WS_CAPTION Creates a window that has a title bar (implies the WS_BORDER style). Cannot be used with the WS_DLGFRAME style. WS_CHILD Creates a child window. Cannot be used with the WS_POPUP style. WS_CHILDWINDOW Same as the WS_CHILD style. WS_CLIPCHILDREN Excludes the area occupied by child windows when you draw within the parent window. Used when you create the parent window. WS_CLIPSIBLINGS Clips child windows relative to each other; that is, when a particular child window receives a paint message, the WS_CLIPSIBLINGS style clips all other overlapped child windows out of the region of the child window to be updated. (If WS_CLIPSIBLINGS is not given and child windows overlap, when you draw within the client area of a child window, it is possible to draw within the client area of a neighboring child window.) For use with the WS_CHILD style only. WS_DISABLED Creates a window that is initially disabled. WS_DLGFRAME Creates a window with a double border but no title. WS_GROUP Specifies the first control of a group of controls in which the user can move from one control to the next with the arrow keys. All controls defined with the WS_GROUP style FALSE after the first control belong to the same group. The next control with the WS_GROUP style starts the next group (that is, one group ends where the next begins). WS_HSCROLL Creates a window that has a horizontal scroll bar. WS_ICONIC Creates a window that is initially minimized. Same as the WS_MINIMIZE style. WS_MAXIMIZE Creates a window of maximum size. WS_MAXIMIZEBOX Creates a window that has a Maximize button. WS_MINIMIZE Creates a window that is initially minimized. For use with the WS_OVERLAPPED style only. WS_MINIMIZEBOX Creates a window that has a Minimize button. WS_OVERLAPPED Creates an overlapped window. An overlapped window usually has a caption and a border. WS_OVERLAPPED WINDOW Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. WS_POPUP Creates a pop-up window. Cannot be used with the WS_CHILD style. WS_POPUPWINDOW Creates a pop-up window with the WS_BORDER, WS_POPUP, and WS_SYSMENU styles. The WS_CAPTION style must be combined with the WS_POPUPWINDOW style to make the Control menu visible. WS_SIZEBOX Creates a window that has a sizing border. Same as the WS_THICKFRAME style. WS_SYSMENU Creates a window that has a Control-menu box in its title bar. Used only for windows with title bars. WS_TABSTOP Specifies one of any number of controls through which the user can move by using the TAB key. The TAB key moves the user to the next control specified by the WS_TABSTOP style. WS_THICKFRAME Creates a window with a thick frame that can be used to size the window. WS_TILED Creates an overlapped window. An overlapped window has a title bar and a border. Same as the WS_OVERLAPPED style. WS_TILEDWINDOW Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. Same as the WS_OVERLAPPEDWINDOW style. WS_VISIBLE Creates a window that is initially visible. WS_VSCROLL Creates a window that has a vertical scroll bar. Step 1 − Let us look into a simple example in which we will add some styling. After creating a window, to display it to the user, we can apply the WS_VISIBLE style to it and additionally, we will also add WS_OVERLAPPED style. Here is an implementation − class CMyFrame : public CFrameWnd { public: CMyFrame() { Create(NULL, _T("MFC Application Tutorial"), WS_VISIBLE | WS_OVERLAPPED); } }; Step 2 − When you run this application, the following window is created. You can now see that the minimize, maximize, and close options do not appear anymore. To locate things displayed on the monitor, the computer uses a coordinate system similar to the Cartesian's, but the origin is located on the top left corner of the screen. Using this coordinate system, any point can be located by its distance from the top left corner of the screen of the horizontal and the vertical axes. The Win32 library provides a structure called POINT defined as follows − typedef struct tagPOINT { LONG x; LONG y; } POINT; The ‘x’ member variable is the distance from the left border of the screen to the point. The ‘x’ member variable is the distance from the left border of the screen to the point. The ‘y’ variable represents the distance from the top border of the screen to the point. The ‘y’ variable represents the distance from the top border of the screen to the point. Besides the Win32's POINT structure, the Microsoft Foundation Class (MFC) library provides the CPoint class. Besides the Win32's POINT structure, the Microsoft Foundation Class (MFC) library provides the CPoint class. This provides the same functionality as the POINT structure. As a C++ class, it adds more functionality needed to locate a point. It provides two constructors. This provides the same functionality as the POINT structure. As a C++ class, it adds more functionality needed to locate a point. It provides two constructors. CPoint(); CPoint(int X, int Y); While a point is used to locate an object on the screen, each window has a size. The size provides two measures related to an object. The width of an object. The height of an object. The Win32 library uses the SIZE structure defined as follows − typedef struct tagSIZE { int cx; int cy; } SIZE; Besides the Win32's SIZE structure, the MFC provides the CSize class. This class has the same functionality as SIZE but adds features of a C++ class. It provides five constructors that allow you to create a size variable in any way of your choice. CSize(); CSize(int initCX, int initCY); CSize(SIZE initSize); CSize(POINT initPt); CSize(DWORD dwSize); When a Window displays, it can be identified on the screen by its location with regards to the borders of the monitor. A Window can also be identified by its width and height. These characteristics are specified or controlled by the rect argument of the Create() method. This argument is a rectangle that can be created through the Win32 RECT structure. typedef struct _RECT { LONG left; LONG top; LONG right; LONG bottom; } RECT, *PRECT; Besides the Win32's RECT structure, the MFC provides the CRect class which has the following constructors − CRect(); CRect(int l, int t, int r, int b); CRect(const RECT& srcRect); CRect(LPCRECT lpSrcRect); CRect(POINT point, SIZE size); CRect(POINT topLeft, POINT bottomRight); Let us look into a simple example in which we will specify the location and the size of the window class CMyFrame : public CFrameWnd { public: CMyFrame() { Create(NULL, _T("MFC Application Tutorial"), WS_SYSMENU, CRect(90, 120, 550, 480)); } }; When you run this application, the following window is created on the top left corner of your screen as specified in CRect constructor in the first two parameters. The last two parameters are the size of the Window. In the real world, many applications are made of different Windows. When an application uses various Windows, most of the objects depend on a particular one. It could be the first Window that was created or another window that you designated. Such a Window is referred to as the Parent Window. All the other windows depend on it directly or indirectly. If the Window you are creating is dependent of another, you can specify that it has a parent. If the Window you are creating is dependent of another, you can specify that it has a parent. This is done with the pParentWnd argument of the CFrameWnd::Create() method. This is done with the pParentWnd argument of the CFrameWnd::Create() method. If the Window does not have a parent, pass the argument with a NULL value. If the Window does not have a parent, pass the argument with a NULL value. Let us look into an example which has only one Window, and there is no parent Window available, so we will pass the argument with NULL value as shown in the following code − class CMyFrame : public CFrameWnd { public: CMyFrame() { Create(NULL, _T("MFC Application Tutorial"), WS_SYSMENU, CRect(90, 120, 550, 480), NULL); } }; When you run the above application, you see the same output. In this chapter, we will be covering the Dialog boxes. Applications for Windows frequently communicate with the user through dialog boxes. CDialog class provides an interface for managing dialog boxes. The Visual C++ dialog editor makes it easy to design dialog boxes and create their dialog-template resources. Creating a dialog object is a two-phase operation − Construct the dialog object. Create the dialog window. Creating a dialog object is a two-phase operation − Construct the dialog object. Construct the dialog object. Create the dialog window. Create the dialog window. Let us look into a simple example by creating a new Win32 project. Step 1 − Open the Visual studio and click on the File → New → Project menu option. Step 2 − You can now see the New Project dialog box. Step 3 − From the left pane, select Templates → Visual C++ → Win32. Step 4 − In the middle pane, select Win32 Project. Step 5 − Enter project name ‘MFCDialogDemo’ in the Name field and click OK to continue. You will see the following dialog. Step 6 − Click Next. Step 7 − Select the options shown in the dialog box given above and click Finish. Step 8 − An empty project is created. Step 9 − To make it a MFC project, right-click on the project and select Properties. Step 10 − In the left section, click Configuration Properties → General. Step 11 − Select the Use MFC in Shared DLL option in Project Defaults section and click OK. Step 12 − Add a new source file. Step 13 − Right-click on your Project and select Add → New Item. Step 14 − In the Templates section, click C++ File (.cpp) Step 15 − Set the Name as Example and click Add. Step 16 − To create an application, we need to add a class and derive it from the MFC's CWinApp. #include <afxwin.h> class CExample : public CWinApp { public: BOOL InitInstance(); }; Step 1 − To create a dialog box, right-click on the Resource Files folder in solution explorer and select Add → Resource. Step 2 − In the Add Resource dialog box, select Dialog and click New. Step 3 − A dialog box requires some preparation before actually programmatically creating it. Step 4 − A dialog box can first be manually created as a text file (in a resource file). Step 5 − You can now see the MFCDialogDemo.rc file created under Resource Files. Step 6 − The resource file is open in designer. The same can be opened as a text file. Rightclick on the resource file and select Open With. Step 7 − Select the Source Code (Text) editor and click Add button. Step 8 − Go back to the designer and right-click on the dialog and select Properties. Step 9 − You need to choose out of the many options. Step 10 − Like most other controls, a dialog box must be identified. The identifier (ID) of a dialog box usually starts with IDD_, Let us change the ID to IDD_EXAMPLE_DLG. A dialog box must be “physically” located on an application. Because a dialog box is usually created as a parent to other controls, its location depends on its relationship to its parent window or to the desktop. If you look and the Properties window, you see two fields, X Pos and Y Pos. X is the distance from the left border of the monitor to the left border of the dialog box. X is the distance from the left border of the monitor to the left border of the dialog box. Y is the distance from the top border of the monitor to the top border of the dialog box. Y is the distance from the top border of the monitor to the top border of the dialog box. By default, these fields are set to zero. You can also change as shown above. If you specify these two dimensions as 0, the left and top borders of the dialog box would be set so the object appears in the center-middle of the screen. The dimensions of a dialog box refer to its width and its height. You can resize the width and height with the help of mouse in designer window. You can see the changes in width and height on the Status Bar. The base class used for displaying dialog boxes on the screen is CDialog class. To create a dialog box, we need to derive a class from CDialog. The CDialog class itself provides three constructors which are as follows − CDialog(); CDialog(UINT nIDTemplate, CWnd* pParentWnd = NULL); CDialog(LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL); Let us create another class CExampleDlg and derive it from CDialog. We will implement its default constructor destructor as shown in the following code. class CExampleDlg : public CDialog { public: enum { IDD = IDD_EXAMPLE_DLG }; CExampleDlg(); ~CExampleDlg(); }; CExampleDlg::CExampleDlg():CDialog(CExampleDlg::IDD) { } CExampleDlg::~CExampleDlg() { } We need to instantiate this dialog on CExample::InitInstance() method as shown in the following code. BOOL CExample::InitInstance() { CExampleDlg myDlg; m_pMainWnd = &myDlg; return TRUE; } There are two types of dialog boxes − modeless and modal. Modal and modeless dialog boxes differ by the process used to create and display them. For a modeless dialog box, you must provide your own public constructor in your dialog class. For a modeless dialog box, you must provide your own public constructor in your dialog class. To create a modeless dialog box, call your public constructor and then call the dialog object's Create member function to load the dialog resource. To create a modeless dialog box, call your public constructor and then call the dialog object's Create member function to load the dialog resource. You can call Create either during or after the constructor call. If the dialog resource has the property WS_VISIBLE, the dialog box appears immediately. You can call Create either during or after the constructor call. If the dialog resource has the property WS_VISIBLE, the dialog box appears immediately. If not, you must call its ShowWindow member function. If not, you must call its ShowWindow member function. To create a modal dialog box, call either of the two public constructors declared in CDialog. To create a modal dialog box, call either of the two public constructors declared in CDialog. Next, call the dialog object's DoModal member function to display the dialog box and manage interaction with it until the user chooses OK or Cancel. Next, call the dialog object's DoModal member function to display the dialog box and manage interaction with it until the user chooses OK or Cancel. This management by DoModal is what makes the dialog box modal. For modal dialog boxes, DoModal loads the dialog resource. This management by DoModal is what makes the dialog box modal. For modal dialog boxes, DoModal loads the dialog resource. Step 1 − To display the dialog box as modal, in the CExample::InitInstance() event call the DoModal() method using your dialog variable − BOOL CExample::InitInstance() { CExampleDlg myDlg; m_pMainWnd = &myDlg; myDlg.DoModal(); return TRUE; } Step 2 − Here is the complete implementation of Example.cpp file. #include <afxwin.h> #include "resource.h" class CExample : public CWinApp { public: BOOL InitInstance(); }; class CExampleDlg : public CDialog { public: enum { IDD = IDD_EXAMPLE_DLG }; CExampleDlg(); ~CExampleDlg(); }; CExampleDlg::CExampleDlg():CDialog(CExampleDlg::IDD) { } CExampleDlg::~CExampleDlg() { } BOOL CExample::InitInstance() { CExampleDlg myDlg; m_pMainWnd = &myDlg; myDlg.DoModal(); return TRUE; } CExample MyApp; Step 3 − When the above code is compiled and executed, you will see the following dialog box. Microsoft Visual Studio provides an easier way to create an application that is mainly based on a dialog box. Here are the steps to create a dialog base project using project templates available in Visual Studio − Step 1 − Open the Visual studio and click on the File → New → Project menu option. You can see the New Project dialog box. Step 2 − From the left pane, select Templates → Visual C++ → MFC. Step 3 − In the middle pane, select MFC Application. Step 4 − Enter project name ‘MFCModalDemo’ in the Name field and click OK to continue. You will see the following dialog box. Step 5 − Click Next. Step 6 − Select the options shown in the above dialog box and click Next. Step 7 − Check all the options that you choose to have on your dialog box like Maximize and Minimize Boxes and click Next. Step 8 − Click Next. Step 9 − It will generate these two classes. You can change the name of the classes and click Finish. Step 10 − You can now see that the MFC wizard creates this Dialog Box and the project files by default. Step 11 − When you run this application, you will see the following output. A resource is a text file that allows the compiler to manage objects such as pictures, sounds, mouse cursors, dialog boxes, etc. Microsoft Visual Studio makes creating a resource file particularly easy by providing the necessary tools in the same environment used to program. This means, you usually do not have to use an external application to create or configure a resource file. Following are some important features related to resources. Resources are interface elements that provide information to the user. Resources are interface elements that provide information to the user. Bitmaps, icons, toolbars, and cursors are all resources. Bitmaps, icons, toolbars, and cursors are all resources. Some resources can be manipulated to perform an action such as selecting from a menu or entering data in dialog box. Some resources can be manipulated to perform an action such as selecting from a menu or entering data in dialog box. An application can use various resources that behave independently of each other, these resources are grouped into a text file that has the *.rc extension. An application can use various resources that behave independently of each other, these resources are grouped into a text file that has the *.rc extension. Most resources are created by selecting the desired one from the Add Resource dialog box. Most resources are created by selecting the desired one from the Add Resource dialog box. The Add Resource dialog box provides an extensive list of resources which can be used as per requirements, but if you need something which is not available then you can add it manually to the *.rc file before executing the program. The Add Resource dialog box provides an extensive list of resources which can be used as per requirements, but if you need something which is not available then you can add it manually to the *.rc file before executing the program. An identifier is a symbol which is a constant integer whose name usually starts with ID. It consists of two parts − a text string (symbol name) mapped to an integer value (symbol value). Symbols provide a descriptive way of referring to resources and user-interface objects, both in your source code and while you're working with them in the resource editors. Symbols provide a descriptive way of referring to resources and user-interface objects, both in your source code and while you're working with them in the resource editors. When you create a new resource or resource object, the resource editors provide a default name for the resource, for example, IDC_DIALOG1, and assign a value to it. When you create a new resource or resource object, the resource editors provide a default name for the resource, for example, IDC_DIALOG1, and assign a value to it. The name-plus-value definition is stored in the Resource.h file. The name-plus-value definition is stored in the Resource.h file. Step 1 − Let us look into our CMFCDialogDemo example from the last chapter in which we have created a dialog box and its ID is IDD_EXAMPLE_DLG. Step 2 − Go to the Solution Explorer, you will see the resource.h file under Header Files. Continue by opening this file in editor and you will see the dialog box identifier and its integer value as well. An icon is a small picture used on a window which represents an application. It is used in two main scenarios. On a Window's frame, it is displayed on the left side of the Window name on the title bar. On a Window's frame, it is displayed on the left side of the Window name on the title bar. In Windows Explorer, on the Desktop, in My Computer, or in the Control Panel window. In Windows Explorer, on the Desktop, in My Computer, or in the Control Panel window. If you look at our MFCModalDemo example, you will see that Visual studio was using a default icon for the title bar as shown in the following snapshot. You can create your own icon by following the steps given below − Step 1 − Right-click on your project and select Add → Resources, you will see the Add Resources dialog box. Step 2 − Select Icon and click New button and you will see the following icon. Step 3 − In Solution Explorer, go to Resource View and expand MFCModalDemo > Icon. You will see two icons. The IDR_MAINFRAME is the default one and IDI_ICON1 is the newly created icon. Step 4 − Right-click on the newly Created icon and select Properties. Step 5 − IDI_ICON1 is the ID of this icon, now Let us change this ID to IDR_MYICON. Step 6 − You can now change this icon in the designer as per your requirements. We will use the same icon. Step 7 − Save this icon. Step 8 − Go to the CMFCModalDemoDlg constructor in CMFCModalDemoDlg.cpp file which will look like the following code. CMFCModalDemoDlg::CMFCModalDemoDlg(CWnd* pParent /* = NULL*/) : CDialogEx(IDD_MFCMODALDEMO_DIALOG, pParent) { m_hIcon = AfxGetApp() -> LoadIcon(IDR_MAINFRAME); } Step 9 − You can now see that the default icon is loaded in the constructor. Let us change it to IDR_ MYICON as shown in the following code. CMFCModalDemoDlg::CMFCModalDemoDlg(CWnd* pParent /* = NULL*/) : CDialogEx(IDD_MFCMODALDEMO_DIALOG, pParent) { m_hIcon = AfxGetApp() -> LoadIcon(IDR_ MYICON); } Step 10 − When the above code is compiled and executed, you will see the new icon is displayed on the dialog box. Menus allow you to arrange commands in a logical and easy-to-find fashion. With the Menu editor, you can create and edit menus by working directly with a menu bar that closely resembles the one in your finished application. To create a menu, follow the steps given below − Step 1 − Right-click on your project and select Add → Resources. You will see the Add Resources dialog box. Step 2 − Select Menu and click New. You will see the rectangle that contains "Type Here" on the menu bar. Step 3 − Write some menu options like File, Edit, etc. as shown in the following snapshot. Step 4 − If you expand the Menu folder in Resource View, you will see the Menu identifier IDR_MENU1. Right-click on this identifier and change it to IDM_MAINMENU. Step 5 − Save all the changes. Step 6 − We need to attach this menu to our dialog box. Expand your Dialog folder in Solution Explorer and double click on the dialog box identifier. Step 7 − You will see the menu field in the Properties. Select the Menu identifier from the dropdown as shown above. Step 8 − Run this application and you will see the following dialog box which also contains menu options. A toolbar is a Windows control that allows the user to perform some actions on a form by clicking a button instead of using a menu. A toolbar provides a convenient group of buttons that simplifies the user's job by bringing the most accessible actions as buttons. A toolbar provides a convenient group of buttons that simplifies the user's job by bringing the most accessible actions as buttons. A toolbar can bring such common actions closer to the user. A toolbar can bring such common actions closer to the user. Toolbars usually display under the main menu. Toolbars usually display under the main menu. They can be equipped with buttons but sometimes their buttons or some of their buttons have a caption. They can be equipped with buttons but sometimes their buttons or some of their buttons have a caption. Toolbars can also be equipped with other types of controls. Toolbars can also be equipped with other types of controls. To create a toolbar, following are the steps. Step 1 − Right-click on your project and select Add → Resources. You will see the Add Resources dialog box. Step 2 − Select Toolbar and click New. You will see the following screen. Step 3 − Design your toolbar in the designer as shown in the following screenshot and specify the IDs as well. Step 4 − Add these two variables in CMFCModalDemoDlg class. CToolBar m_wndToolBar; BOOL butD; Step 5 − Following is the complete implementation of CMFCModalDemoDlg in CMFCModalDemoDlg.h file − class CMFCModalDemoDlg : public CDialogEx { // Construction public: CMFCModalDemoDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data #ifdef AFX_DESIGN_TIME enum { IDD = IDD_MFCMODALDEMO_DIALOG }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: HICON m_hIcon; CToolBar m_wndToolBar; BOOL butD; // Generated message map functions virtual BOOL OnInitDialog(); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedOk(); }; Step 6 − Update CMFCModalDemoDlg::OnInitDialog() as shown in the following code. BOOL CMFCModalDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon if (!m_wndToolBar.Create(this) || !m_wndToolBar.LoadToolBar(IDR_TOOLBAR1)) //if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | // WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | // CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || // !m_wndToolBar.LoadToolBar(IDR_TOOLBAR1)) { TRACE0("Failed to Create Dialog Toolbar\n"); EndDialog(IDCANCEL); } butD = TRUE; CRect rcClientOld; // Old Client Rect CRect rcClientNew; // New Client Rect with Tollbar Added // Retrive the Old Client WindowSize // Called to reposition and resize control bars in the client area of a window // The reposQuery FLAG does not really traw the Toolbar. It only does the calculations. // And puts the new ClientRect values in rcClientNew so we can do the rest of the Math. GetClientRect(rcClientOld); RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0, reposQuery, rcClientNew); // All of the Child Windows (Controls) now need to be moved so the Tollbar does not cover them up. // Offest to move all child controls after adding Tollbar CPoint ptOffset(rcClientNew.left - rcClientOld.left, rcClientNew.top - rcClientOld.top); CRect rcChild; CWnd* pwndChild = GetWindow(GW_CHILD); //Handle to the Dialog Controls while (pwndChild) // Cycle through all child controls { pwndChild -> GetWindowRect(rcChild); // Get the child control RECT ScreenToClient(rcChild); // Changes the Child Rect by the values of the claculated offset rcChild.OffsetRect(ptOffset); pwndChild -> MoveWindow(rcChild, FALSE); // Move the Child Control pwndChild = pwndChild -> GetNextWindow(); } CRect rcWindow; // Get the RECT of the Dialog GetWindowRect(rcWindow); // Increase width to new Client Width rcWindow.right += rcClientOld.Width() - rcClientNew.Width(); // Increase height to new Client Height rcWindow.bottom += rcClientOld.Height() - rcClientNew.Height(); // Redraw Window MoveWindow(rcWindow, FALSE); // Now we REALLY Redraw the Toolbar RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0); // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control } Step 7 − Run this application. You will see the following dialog box which also contains the toolbar. An access key is a letter that allows the user to perform a menu action faster by using the keyboard instead of the mouse. This is usually faster because the user would not need to position the mouse anywhere, which reduces the time it takes to perform the action. Step 1 − To create an access key, type an ampersand "&" on the left of the menu item. Step 2 − Repeat this step for all menu options. Run this application and press Alt. You will see that the first letter of all menu options are underlined. A shortcut key is a key or a combination of keys used by advanced users to perform an action that would otherwise be done on a menu item. Most shortcuts are a combination of the Ctrl key simultaneously pressed with a letter key. For example, Ctrl + N, Ctrl + O, or Ctrl + D. To create a shortcut, on the right side of the string that makes up a menu caption, rightclick on the menu item and select properties. In the Caption field type \t followed by the desired combination as shown below for the New menu option. Repeat the step for all menu options. An Accelerator Table is a list of items where each item of the table combines an identifier, a shortcut key, and a constant number that specifies the kind of accelerator key. Just like the other resources, an accelerator table can be created manually in a .rc file. Following are the steps to create an accelerator table. Step 1 − To create an accelerator table, right-click on *.rc file in the solution explorer. Step 2 − Select Accelerator and click New. Step 3 − Click the arrow of the ID combo box and select menu Items. Step 4 − Select Ctrl from the Modifier dropdown. Step 5 − Click the Key box and type the respective Keys for both menu options. We will also add New menu item event handler to testing. Right-click on the New menu option. Step 6 − You can specify a class, message type and handler name. For now, let us leave it as it is and click Add and Edit button. Step 7 − Select Add Event Handler. Step 8 − You will now see the event added at the end of the CMFCModalDemoDlg.cpp file. void CMFCModalDemoDlg::OnFileNew() { // TODO: Add your command handler code here MessageBox(L"File > New menu option"); } Step 9 − Now Let us add a message box that will display the simple menu option message. To start accelerator table in working add the HACCEL variable and ProcessMessageFilter as shown in the following CMFCModalDemoApp. class CMFCModalDemoApp : public CWinApp { public: CMFCModalDemoApp(); // Overrides public: virtual BOOL InitInstance(); HACCEL m_hAccelTable; // Implementation DECLARE_MESSAGE_MAP() virtual BOOL ProcessMessageFilter(int code, LPMSG lpMsg); }; Step 10 − Load Accelerator and the following call in the CMFCModalDemoApp::InitInstance(). m_hAccelTable = LoadAccelerators(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_ACCELERATOR1)); Step 11 − Here is the implementation of ProcessMessageFilter. BOOL CMFCModalDemoApp::ProcessMessageFilter(int code, LPMSG lpMsg) { if (code >= 0 && m_pMainWnd && m_hAccelTable) { if (::TranslateAccelerator(m_pMainWnd -> m_hWnd, m_hAccelTable, lpMsg)) return TRUE; } return CWinApp::ProcessMessageFilter(code, lpMsg); } Step 12 − When the above code is compiled and executed, you will see the following output. Step 13 − Press Alt button followed by F key and then N key or Ctrl + N. You will see the following message. A property sheet, also known as a tab dialog box, is a dialog box that contains property pages. Each property page is based on a dialog template resource and contains controls. It is enclosed on a page with a tab on top. The tab names the page and indicates its purpose. Users click a tab in the property sheet to select a set of controls. To create property pages, let us look into a simple example by creating a dialog based MFC project. Once the project is created, we need to add some property pages. Visual Studio makes it easy to create resources for property pages by displaying the Add Resource dialog box, expanding the Dialog node and selecting one of the IDD_PROPPAGE_X items. Step 1 − Right-click on your project in solution explorer and select Add → Resources. Step 2 − Select the IDD_PROPPAGE_LARGE and click NEW. Step 3 − Let us change ID and Caption of this property page to IDD_PROPPAGE_1 and Property Page 1 respectively as shown above. Step 4 − Right-click on the property page in designer window. Step 5 − Select the Add Class option. Step 6 − Enter the class name and select CPropertyPage from base class dropdown list. Step 7 − Click Finish to continue. Step 8 − Add one more property page with ID IDD_PROPPAGE_2 and Caption Property Page 2 by following the above mentioned steps. Step 9 − You can now see two property pages created. To implement its functionality, we need a property sheet. The Property Sheet groups the property pages together and keeps it as entity. To create a property sheet, follow the steps given below − Step 1 − Right-click on your project and select Add > Class menu options. Step 2 − Select Visual C++ → MFC from the left pane and MFC Class in the template pane and click Add. Step 3 − Enter the class name and select CPropertySheet from base class dropdown list. Step 4 − Click finish to continue. Step 5 − To launch this property sheet, we need the following changes in our main project class. Step 6 − Add the following references in CMFCPropSheetDemo.cpp file. #include "MySheet.h" #include "PropPage1.h" #include "PropPage2.h" Step 7 − Modify the CMFCPropSheetDemoApp::InitInstance() method as shown in the following code. CMySheet mySheet(L"Property Sheet Demo"); CPropPage1 page1; CPropPage2 page2; mySheet.AddPage(&page1); mySheet.AddPage(&page2); m_pMainWnd = &mySheet; INT_PTR nResponse = mySheet.DoModal(); Step 8 − Here is the complete implementation of CMFCPropSheetDemo.cpp file. // MFCPropSheetDemo.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "MFCPropSheetDemo.h" #include "MFCPropSheetDemoDlg.h" #include "MySheet.h" #include "PropPage1.h" #include "PropPage2.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMFCPropSheetDemoApp BEGIN_MESSAGE_MAP(CMFCPropSheetDemoApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CMFCPropSheetDemoApp construction CMFCPropSheetDemoApp::CMFCPropSheetDemoApp() { // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART; // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CMFCPropSheetDemoApp object CMFCPropSheetDemoApp theApp; // CMFCPropSheetDemoApp initialization BOOL CMFCPropSheetDemoApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); AfxEnableControlContainer(); // Create the shell manager, in case the dialog contains // any shell tree view or shell list view controls. CShellManager *pShellManager = new CShellManager; // Activate "Windows Native" visual manager for enabling themes in MFC controls CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); CMySheet mySheet(L"Property Sheet Demo"); CPropPage1 page1; CPropPage2 page2; mySheet.AddPage(&page1); mySheet.AddPage(&page2); m_pMainWnd = &mySheet; INT_PTR nResponse = mySheet.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK }else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel }else if (nResponse == -1) { TRACE(traceAppMsg, 0, "Warning: dialog creation failed, so application is terminating unexpectedly.\n"); TRACE(traceAppMsg, 0, "Warning: if you are using MFC controls on the dialog, you cannot #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS.\n"); } // Delete the shell manager created above. if (pShellManager != NULL) { delete pShellManager; } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; } Step 9 − When the above code is compiled and executed, you will see the following dialog box. This dialog box contains two property pages. Layout of controls is very important and critical for application usability. It is used to arrange a group of GUI elements in your application. There are certain important things to consider while selecting layout − Positions of the child elements. Sizes of the child elements. Let us create new Dialog based MFC Project MFCLayoutDemo. Step 1 − Once the project is created, you will see the following screen. Step 2 − Delete the TODO from the dialog box. Step 3 − Drag some controls from the Toolbox which you can see on the left side. (We will drag one Static Text and one Edit Control as shown in the following snapshot). Step 4 − Change the Caption of the Static Text to Name. Control grid is the guiding grid dots, which can help in positioning of the controls you are adding at the time of designing. To enable the control grid, you need to click the Toggle Grid button in the toolbar as shown in the following snapshot. After you have added a control to a dialog box, it assumes either its default size or the size you drew it with. To help with the sizes of controls on the form or dialog box, Visual Studio provides a visual grid made of black points. To resize a control, that is, to give it a particular width or height, position the mouse on one of the handles and drag it in the desired direction. You can now resize the controls with the help of this dotted grid. The controls you position on a dialog box or a form assume their given place. Most of the time, these positions are not practical. You can move them around to any position of your choice. Let us add some more controls − Step 1 − To move a control, click and drag it in the desired direction until it reaches the intended position. Step 2 − To move a group of controls, first select them. Then drag the selection to the desired location. Let us select the Static Texts and Edit Controls. Step 3 − Move these selected controls to the left side. To help with positioning the controls, Visual Studio provides the Dialog toolbar with the following buttons. Step 1 − Let us align the Check box and Static Text controls to the left by selecting all these controls. Step 2 − Select the Format → Align → Lefts. Step 3 − You can now see all these controls are aligned to the left. The controls you add to a form or a dialog box are positioned in a sequence that follows the order they were added. When you add control(s) regardless of the section or area you place the new control, it is sequentially positioned at the end of the existing controls. If you do not fix it, the user would have a hard time navigating the controls. The sequence of controls navigation is also known as the tab order. To change the tab, you can either use the Format → Tab Order menu option or you can also use the Ctrl + D shortcut. Let us press Ctrl + D. You can now see the order in which all these controls are added to this dialog box. To Change the order or sequence of controls, click on all the controls in sequence in which you want to navigate. In this example, we will first click on the checkbox followed by Name and Address Edit controls. Then click OK and Cancel as shown in the following snapshot. Let us run this application and you will see the following output. In MFC applications, after visually adding a control to your application, if you want to refer to it in your code, you can declare a variable based on, or associated with that control. The MFC library allows you to declare two types of variables for some of the controls used in an application a value or a control variable. One variable is used for the information stored in the control, which is also known as Control Variable/Instance. One variable is used for the information stored in the control, which is also known as Control Variable/Instance. The other variable is known as Control Value Variable. A user can perform some sort of actions on that control with this variable. The other variable is known as Control Value Variable. A user can perform some sort of actions on that control with this variable. A control variable is a variable based on the class that manages the control. For example, a button control is based on the CButton class. To see these concepts in real programming, let us create an MFC dialog based project MFCControlManagement. Once the project is created, you will see the following dialog box in designer window. Step 1 − Delete the TODO line and drag one checkbox and one Edit control as shown in the following snapshot. Change the caption of checkbox to Enable Control. Step 2 − Right-click on the checkbox. Step 3 − Select Add Variable. Step 4 − You can now see the Add Member Variable Wizard. You can select different options on this dialog box. For checkbox, the variable type is CButton. It is selected by default in this dialog box. Similarly, the control ID is also selected by default now we need to select Control in the Category combo box, and type m_enableDisableCheck in the Variable Name edit box and click finish. Step 5 − Similarly, add Control Variable of Edit control with the settings as shown in the following snapshot. Observe the header file of the dialog class. You can see that the new variables have been added now. CButton m_enableDisableCheck; CEdit m_myEditControl; Another type of variable you can declare for a control is the value variable. Not all controls provide a value variable. The value variable must be able to handle the type of value stored in the control it is intended to refer to. The value variable must be able to handle the type of value stored in the control it is intended to refer to. For example, because a text based control is used to handle text, you can declare a text-based data type for it. This would usually be a CString variable. For example, because a text based control is used to handle text, you can declare a text-based data type for it. This would usually be a CString variable. Let us look into this type of variable for checkbox and edit control. Step 1 − Right-click on the checkbox and select Add Variable. Step 2 − The Variable type is BOOL. Select Value from the Category dropdown list. Step 3 − Click Finish to continue. Step 4 − Similarly, add value Variable for Edit control with the settings as shown in the following snapshot. Step 5 − Type CString in variable type and m_editControlVal in the variable name field. Step 6 − You can now see these variables added in the Header file. bool m_enableDisableVal; CString m_editControlVal; After adding a control to your application, whether you visually added it or created it dynamically, you will also decide how to handle the possible actions that the user can perform on the control. For project dialog boxes that are already associated with a class, you can take advantage of some shortcuts when you create event handlers. For project dialog boxes that are already associated with a class, you can take advantage of some shortcuts when you create event handlers. You can quickly create a handler either for the default control notification event or for any applicable Windows message. You can quickly create a handler either for the default control notification event or for any applicable Windows message. Let us look into the same example in which we added event handler for checkbox. Step 1 − Right-click the control for which you want to handle the notification event. Step 2 − On the shortcut menu, click Add Event Handler to display the Event Handler Wizard. Step 3 − Select the event in the Message type box to add to the class selected in the Class list box. Step 4 − Accept the default name in the Function handler name box, or provide the name of your choice. Step 5 − Click Add and edit to add the event handler. Step 6 − You can now see the following event added at the end of CMFCControlManagementDlg.cpp file. void CMFCControlManagementDlg::OnBnClickedCheck1() { // TODO: Add your control notification handler code here } So far, we have seen how to add controls to an application. We will now see how to manage these controls as per user requirement. We can use the control variable/instance in a particular event handler. Step 1 − Let us look into the following example. Here, we will enable/disable the edit control when the checkbox is checked/unchecked. Step 2 − We have now added the checkbox click event handler. Here is the implementation − void CMFCControlManagementDlg::OnBnClickedCheck1() { // TODO: Add your control notification handler code here UpdateData(TRUE); if (m_enableDisableVal) m_myEditControl.EnableWindow(TRUE); else m_myEditControl.EnableWindow(FALSE); } Step 3 − When the dialog is created, we need to add the following code to CMFCControlManagementDlg::OnInitDialog(). This will manage these controls. UpdateData(TRUE); if (m_enableDisableVal) m_myEditControl.EnableWindow(TRUE); else m_myEditControl.EnableWindow(FALSE); Step 4 − Here is the complete implementation of CMFCControlManagementDlg.cpp file. // MFCControlManagementDlg.cpp : implementation file // #include "stdafx.h" #include "MFCControlManagement.h" #include "MFCControlManagementDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CMFCControlManagementDlg dialog CMFCControlManagementDlg::CMFCControlManagementDlg(CWnd* pParent /* = NULL*/) :CDialogEx(IDD_MFCCONTROLMANAGEMENT_DIALOG, pParent) , m_enableDisableVal(FALSE) , m_editControlVal(_T("")) { m_hIcon = AfxGetApp()&rarr LoadIcon(IDR_MAINFRAME); } void CMFCControlManagementDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_CHECK1, m_enableDisableCheck); DDX_Control(pDX, IDC_EDIT1, m_myEditControl); DDX_Check(pDX, IDC_CHECK1, m_enableDisableVal); DDX_Text(pDX, IDC_EDIT1, m_editControlVal); } BEGIN_MESSAGE_MAP(CMFCControlManagementDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_CHECK1, &CMFCControlManagementDlg::OnBnClickedCheck1) END_MESSAGE_MAP() // CMFCControlManagementDlg message handlers BOOL CMFCControlManagementDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu → AppendMenu(MF_SEPARATOR); pSysMenu → AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here UpdateData(TRUE); if (m_enableDisableVal) m_myEditControl.EnableWindow(TRUE); else m_myEditControl.EnableWindow(FALSE); return TRUE; // return TRUE unless you set the focus to a control } void CMFCControlManagementDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); }else { CDialogEx::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CMFCControlManagementDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); }else { CDialogEx::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMFCControlManagementDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CMFCControlManagementDlg::OnBnClickedCheck1() { // TODO: Add your control notification handler code here UpdateData(TRUE); if (m_enableDisableVal) m_myEditControl.EnableWindow(TRUE); else m_myEditControl.EnableWindow(FALSE); } Step 5 − When the above code is compiled and executed, you will see the following output. The checkbox is unchecked by default. This disables the edit control too. Step 6 − Check the Enable Control checkbox. This will automatically enable the edit control. Windows controls are objects that users can interact with to enter or manipulate data. They commonly appear in dialog boxes or on toolbars. There are various types of controls − A text based control which is used to display text to the user or request text from the user. A text based control which is used to display text to the user or request text from the user. A list based control displays a list of items. A list based control displays a list of items. A progress based control is used to show the progress of an action. A progress based control is used to show the progress of an action. A static control can be used to show colors, a picture or something that does not regularly fit in the above categories. A static control can be used to show colors, a picture or something that does not regularly fit in the above categories. A static control is an object that displays information to the user without his or her direct intervention. It can be used to show colors, a geometric shape, or a picture such as an icon, a bitmap, or an animation. An animation control is a window that displays an Audio clip in AVI format. An AVI clip is a series of bitmap frames, like a movie. Animation controls can only play simple AVI clips, and they do not support sound. It is represented by the CAnimateCtrl class. A button is an object that the user clicks to initiate an action. Button control is represented by CButton class. A bitmap button displays a picture or a picture and text on its face. This is usually intended to make the button a little explicit. A bitmap button is created using the CBitmapButton class, which is derived from CButton. A command button is an enhanced version of the regular button. It displays a green arrow icon on the left, followed by a caption in regular size. Under the main caption, it can display another smaller caption that serves as a hint to provide more information. A static control displays a text string, box, rectangle, icon, cursor, bitmap, or enhanced metafile. It is represented by CStatic class. It can be used to label, box, or separateother controls. A static control normally takes no input and provides no output. A list box displays a list of items, such as filenames, that the user can view and select. A List box is represented by CListBox class. In a single-selection list box, the user can select only one item. In a multiple-selection list box, a range of items can be selected. When the user selects an item, it is highlighted and the list box sends a notification message to the parent window. A combo box consists of a list box combined with either a static control or edit control. it is represented by CComboBox class. The list-box portion of the control may be displayed at all times or may only drop down when the user selects the drop-down arrow next to the control. A radio button is a control that appears as a dot surrounded by a round box. In reality, a radio button is accompanied by one or more other radio buttons that appear and behave as a group. A checkbox is a Windows control that allows the user to set or change the value of an item as true or false. An Image List is a collection of same-sized images, each of which can be referred to by its zero-based index. Image lists are used to efficiently manage large sets of icons or bitmaps. Image lists are represented by CImageList class. An Edit Box is a rectangular child window in which the user can enter text. It is represented by CEdit class. A Rich Edit Control is a window in which the user can enter and edit text. The text can be assigned character and paragraph formatting, and can include embedded OLE objects. It is represented by CRichEditCtrl class. A group box is a static control used to set a visible or programmatic group of controls. The control is a rectangle that groups other controls together. A Spin Button Control (also known as an up-down control) is a pair of arrow buttons that the user can click to increment or decrement a value, such as a scroll position or a number displayed in a companion control. it is represented by CSpinButtonCtrl class. It manages the Updown Controls. A progress bar control is a window that an application can use to indicate the progress of a lengthy operation. It consists of a rectangle that is gradually filled, from left to right, with the system highlight color as an operation progresses. It is represented by CProgressCtrl class. A progress bars is a window that an application can use to indicate the progress of a operation. A timer is a non-spatial object that uses recurring lapses of time from a computer or fromyour application. To work, every lapse of period, the control sends a message to the operating system. Unlike most other controls, the MFC timer has neither a button to represent it nor a class. To create a timer, you simply call the CWnd::SetTimer() method. This function call creates a timer for your application. Like the other controls, a timer uses an identifier. The date and time picker control (CDateTimeCtrl) implements an intuitive and recognizable method of entering or selecting a specific date. The main interface of the control is similar in functionality to a combo box. However, if the user expands the control, a month calendar control appears (by default), allowing the user to specify a particular date. When a date is chosen, the month calendar control automatically disappears. If you need to display a picture for your application, Visual C++ provides a special control for that purpose. The Image editor has an extensive set of tools for creating and editing images, as wellas features to help you create toolbar bitmaps. In addition to bitmaps, icons, and cursors, you can edit images in GIF or JPEG format using commands on the Image menu and tools on the Image Editor Toolbar. A Slider Control (also known as a trackbar) is a window containing a slider and optional tick marks. When the user moves the slider, using either the mouse or the direction keys, the control sends notification messages to indicate the change. There are two types of sliders − horizontal and vertical. It is represented by CSliderCtrl class. A scrollbar is a graphical control element with which continuous text, pictures or anything else can be scrolled in two directions along a control by clicking an arrow. This control can assume one of two directions − horizontal or vertical. It is represented by CScrollBar class. A Tree View Control is a window that displays a hierarchical list of items, such as the headings in a document, the entries in an index, or the files and directories on a disk. Each item consists of a label and an optional bitmapped image, and each item can have a list of subitems associated with it. By clicking an item, the user can expand and collapse the associated list of subitems. It is represented by CTreeCtrl class. Encapsulates the functionality of a List View Control, which displays a collection of items each consisting of an icon (from an image list) and a label. It is represented by CListCtrl class. A list control consists of using one of four views to display a list of items. An application is made of various objects. Most of the time, more than one application is running on the computer and the operating system is constantly asked to perform some assignments. Because there can be so many requests presented unpredictably, the operating system leaves it up to the objects to specify what they want, when they want it, and what behavior or result they expect. The Microsoft Windows operating system cannot predict what kinds of requests one object would need to be taken care of and what type of assignment another object would need. The Microsoft Windows operating system cannot predict what kinds of requests one object would need to be taken care of and what type of assignment another object would need. To manage all these assignments and requests, the objects send messages. To manage all these assignments and requests, the objects send messages. Each object has the responsibility to decided what message to send and when. Each object has the responsibility to decided what message to send and when. In order to send a message, a control must create an event. In order to send a message, a control must create an event. To make a distinction between the two, a message's name usually starts with WM_ which stands for Window Message. To make a distinction between the two, a message's name usually starts with WM_ which stands for Window Message. The name of an event usually starts with On which indicates an action. The name of an event usually starts with On which indicates an action. The event is the action of sending the message. The event is the action of sending the message. Since Windows is a message-oriented operating system, a large portion of programming for the Windows environment involves message handling. Each time an event such as a keystroke or mouse click occurs, a message is sent to the application, which must then handle the event. For the compiler to manage messages, they should be included in the class definition. For the compiler to manage messages, they should be included in the class definition. The DECLARE_MESSAGE_MAP macro should be provided at the end of the class definition as shown in the following code. The DECLARE_MESSAGE_MAP macro should be provided at the end of the class definition as shown in the following code. class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: DECLARE_MESSAGE_MAP() }; The actual messages should be listed just above the DECLARE_MESSAGE_MAP line. The actual messages should be listed just above the DECLARE_MESSAGE_MAP line. To implement the messages, you need to create a table of messages that your program is using. To implement the messages, you need to create a table of messages that your program is using. This table uses two delimiting macros; This table uses two delimiting macros; Its starts with a BEGIN_MESSAGE_MAP and ends with an END_MESSAGE_MAP macros. Its starts with a BEGIN_MESSAGE_MAP and ends with an END_MESSAGE_MAP macros. The BEGIN_MESSAGE_MAP macro takes two arguments, the name of your class and the MFC class you derived your class from as shown in the following code. The BEGIN_MESSAGE_MAP macro takes two arguments, the name of your class and the MFC class you derived your class from as shown in the following code. #include <afxwin.h> class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: DECLARE_MESSAGE_MAP() }; CMainFrame::CMainFrame() { // Create the window's frame Create(NULL, L"MFC Messages Demo", WS_OVERLAPPEDWINDOW, CRect(120, 100, 700, 480), NULL); } class CMessagesApp : public CWinApp { public: BOOL InitInstance(); }; BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) END_MESSAGE_MAP() BOOL CMessagesApp::InitInstance(){ m_pMainWnd = new CMainFrame; m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); return TRUE; } CMessagesApp theApp; Let us look into a simple example by creating a new Win32 project. Step 1 − To create an MFC project, right-click on the project and select Properties. Step 2 − In the left section, click Configuration Properties → General. Step 3 − Select the ‘Use MFC in Shared DLL’ option in Project Defaults section and click OK. Step 4 − We need to add a new source file. Step 5 − Right-click on your Project and select Add → New Item. Step 6 − In the Templates section, click C++ File (.cpp). Step 7 − Click Add to Continue. Step 8 − Now, add the following code in the *.cpp file. #include <afxwin.h> class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: DECLARE_MESSAGE_MAP() }; CMainFrame::CMainFrame() { // Create the window's frame Create(NULL, L"MFC Messages Demo", WS_OVERLAPPEDWINDOW, CRect(120, 100, 700, 480), NULL); } class CMessagesApp : public CWinApp { public: BOOL InitInstance(); }; BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) END_MESSAGE_MAP() BOOL CMessagesApp::InitInstance() { m_pMainWnd = new CMainFrame; m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); return TRUE; } CMessagesApp theApp; There are different types of Windows messages like creating a window, showing a window etc. Here are some of the commonly used windows messages. Let us look into a simple example of window creation. WM_CREATE − When an object, called a window, is created, the frame that creates the objects sends a message identified as ON_WM_CREATE. Step 1 − To create ON_WM_CREATE, add afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); before the DECLARE_MESSAGE_MAP() as shown below. class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); DECLARE_MESSAGE_MAP() }; Step 2 − Add the ON_WM_CREATE() after the BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) and before END_MESSAGE_MAP() BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() END_MESSAGE_MAP() Step 3 − Here is the Implementation of OnCreate() int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { // Call the base class to create the window if (CFrameWnd::OnCreate(lpCreateStruct) == 0) { // If the window was successfully created, let the user know MessageBox(L"The window has been created!!!"); // Since the window was successfully created, return 0 return 0; } // Otherwise, return -1 return -1; } Step 4 − Now your *.cpp file will look like as shown in the following code. #include <afxwin.h> class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); DECLARE_MESSAGE_MAP() }; CMainFrame::CMainFrame() { // Create the window's frame Create(NULL, L"MFC Messages Demo", WS_OVERLAPPEDWINDOW, CRect(120, 100, 700, 480), NULL); } class CMessagesApp : public CWinApp { public: BOOL InitInstance(); }; BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() END_MESSAGE_MAP() int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { // Call the base class to create the window if (CFrameWnd::OnCreate(lpCreateStruct) == 0) { // If the window was successfully created, let the user know MessageBox(L"The window has been created!!!"); // Since the window was successfully created, return 0 return 0; } // Otherwise, return -1 return -1; } BOOL CMessagesApp::InitInstance() { m_pMainWnd = new CMainFrame; m_pMainWnd -> ShowWindow(SW_SHOW); m_pMainWnd -> UpdateWindow(); return TRUE; } CMessagesApp theApp; Step 5 − When the above code is compiled and executed, you will see the following output. Step 6 − When you click OK, it will display the main window. One of the main features of a graphical application is to present Windows controls and resources that allow the user to interact with the machine. Examples of controls that we will learn are buttons, list boxes, combo boxes, etc. One type of resource we introduced in the previous lesson is the menu. Such controls and resources can initiate their own messages when the user clicks them. A message that emanates from a Windows control or a resource is called a command message. Let us look into a simple example of Command messages. To provide your application the ability to create a new document, the CWinApp class provides the OnFileNew() method. afx_msg void OnFileNew(); BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_COMMAND(ID_FILE_NEW, CMainFrame::OnFileNew) END_MESSAGE_MAP() Here is the method definition − void CMainFrame::OnFileNew() { // Create New file } A keyboard is a hardware object attached to the computer. By default, it is used to enter recognizable symbols, letters, and other characters on a control. Each key on the keyboard displays a symbol, a letter, or a combination of those, to give an indication of what the key could be used for. The user typically presses a key, which sends a signal to a program. Each key has a code that the operating system can recognize. This code is known as the virtual key code. VK_LBUTTON Left mouse button VK_RBUTTON Right mouse button VK_CANCEL Control-break processing VK_MBUTTON Middle mouse button (three-button mouse) VK_BACK BACKSPACE key VK_RETURN ENTER key VK_TAB TAB key VK_CLEAR CLEAR key VK_SHIFT SHIFT key VK_CONTROL CTRL key VK_MENU ALT key VK_PAUSE PAUSE key VK_CAPITAL CAPS LOCK key VK_ESCAPE ESC key VK_SPACE SPACEBAR VK_PRIOR PAGE UP key VK_NEXT PAGE DOWN key VK_END END key VK_HOME HOME key VK_LEFT LEFT ARROW key VK_UP UP ARROW key VK_RIGHT RIGHT ARROW key VK_DOWN DOWN ARROW key VK_SELECT SELECT key VK_PRINT PRINT key VK_EXECUTE EXECUTE key VK_SNAPSHOT PRINT SCREEN key VK_INSERT INS key VK_DELETE DEL key VK_NUMPAD0 Numeric keypad 0 key VK_NUMPAD1 Numeric keypad 1 key VK_NUMPAD2 Numeric keypad 2 key VK_NUMPAD3 Numeric keypad 3 key VK_NUMPAD4 Numeric keypad 4 key VK_NUMPAD5 Numeric keypad 5 key VK_NUMPAD6 Numeric keypad 6 key VK_NUMPAD7 Numeric keypad 7 key VK_NUMPAD8 Numeric keypad 8 key VK_NUMPAD9 Numeric keypad 9 key VK_MULTIPLY Multiply key VK_ADD Add key VK_SEPARATOR Separator key VK_SUBTRACT Subtract key VK_DECIMAL Decimal key VK_DIVIDE Divide key VK_F1 F1 key VK_F2 F2 key VK_F3 F3 key VK_F4 F4 key VK_F5 F5 key VK_F6 F6 key VK_F7 F7 key VK_F8 F8 key VK_F9 F9 key VK_F10 F10 key VK_F11 F11 key VK_F12 F12 key VK_NUMLOCK NUM LOCK key VK_SCROLL SCROLL LOCK key VK_LSHIFT Left SHIFT key VK_RSHIFT Right SHIFT key VK_LCONTROL Left CONTROL key VK_RCONTROL Right CONTROL key Pressing a key causes a WM_KEYDOWN or WM_SYSKEYDOWN message to be placed in the thread message. This can be defined as follows − afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); Let us look into a simple example. Step 1 − Here is the message. BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() ON_WM_KEYDOWN() END_MESSAGE_MAP() Step 2 − Here is the implementation of OnKeyDown(). void CMainFrame::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { switch (nChar) { case VK_RETURN: MessageBox(L"You pressed Enter"); break; case VK_F1: MessageBox(L"Help is not available at the moment"); break; case VK_DELETE: MessageBox(L"Can't Delete This"); break; default: MessageBox(L"Whatever"); } } Step 3 − When the above code is compiled and executed, you will see the following output. Step 4 − When you press Enter, it will display the following message. The mouse is another object that is attached to the computer allowing the user to interact with the machine. If the left mouse button was pressed, an ON_WM_LBUTTONDOWN message is sent. The syntax of this message is − afx_msg void OnLButtonDown(UINT nFlags, CPoint point) If the left mouse button was pressed, an ON_WM_LBUTTONDOWN message is sent. The syntax of this message is − afx_msg void OnLButtonDown(UINT nFlags, CPoint point) afx_msg void OnLButtonDown(UINT nFlags, CPoint point) If the right mouse button was pressed, an ON_WM_RBUTTONDOWN message is sent. Its syntax is − afx_msg void OnRButtonDown(UINT nFlags, CPoint point) If the right mouse button was pressed, an ON_WM_RBUTTONDOWN message is sent. Its syntax is − afx_msg void OnRButtonDown(UINT nFlags, CPoint point) afx_msg void OnRButtonDown(UINT nFlags, CPoint point) Similarly If the left mouse is being released, the ON_WM_LBUTTONUP message is sent. Its syntax is − afx_msg void OnLButtonUp(UINT nFlags, CPoint point) Similarly If the left mouse is being released, the ON_WM_LBUTTONUP message is sent. Its syntax is − afx_msg void OnLButtonUp(UINT nFlags, CPoint point) afx_msg void OnLButtonUp(UINT nFlags, CPoint point) If the right mouse is being released, the ON_WM_TBUTTONUP message is sent. Its syntax is − afx_msg void OnRButtonUp(UINT nFlags, CPoint point) If the right mouse is being released, the ON_WM_TBUTTONUP message is sent. Its syntax is − afx_msg void OnRButtonUp(UINT nFlags, CPoint point) afx_msg void OnRButtonUp(UINT nFlags, CPoint point) Let us look into a simple example. Step 1 − Add the following two functions in CMainFrame class definition as shown in the following code. class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnRButtonUp(UINT nFlags, CPoint point); DECLARE_MESSAGE_MAP() }; Step 2 − Add the following two Message Maps. BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_KEYDOWN() ON_WM_LBUTTONDOWN() ON_WM_RBUTTONUP() END_MESSAGE_MAP() Step 3 − Here is the functions definition. void CMainFrame::OnLButtonDown(UINT nFlags, CPoint point) { CString MsgCoord; MsgCoord.Format(L"Left Button at P(%d, %d)", point.x, point.y); MessageBox(MsgCoord); } void CMainFrame::OnRButtonUp(UINT nFlags, CPoint point) { MessageBox(L"Right Mouse Button Up"); } Step 4 − When you run this application, you will see the following output. Step 5 − When you click OK, you will see the following message. Step 6 − Right-click on this window. Now, when you release the right button of the mouse, it will display the following message. An ActiveX control container is a parent program that supplies the environment for an ActiveX (formerly OLE) control to run. ActiveX control is a control using Microsoft ActiveX technologies. ActiveX control is a control using Microsoft ActiveX technologies. ActiveX is not a programming language, but rather a set of rules for how applications should share information. ActiveX is not a programming language, but rather a set of rules for how applications should share information. Programmers can develop ActiveX controls in a variety of languages, including C, C++, Visual Basic, and Java. Programmers can develop ActiveX controls in a variety of languages, including C, C++, Visual Basic, and Java. You can create an application capable of containing ActiveX controls with or without MFC, but it is much easier to do with MFC. You can create an application capable of containing ActiveX controls with or without MFC, but it is much easier to do with MFC. Let us look into simple example of add ActiveX controls in your MFC dialog based application. Step 1 − Right-click on the dialog in the designer window and select Insert ActiveX Control. Step 2 − Select the Microsoft Picture Clip Control and click OK. Step 3 − Resize the Picture control and in the Properties window, click the Picture field. Step 4 − Browse the folder that contains Pictures. Select any picture. Step 5 − When you run this application, you will see the following output. Let us have a look into another simple example. Step 1 − Right-click on the dialog in the designer window. Step 2 − Select Insert ActiveX Control. Step 3 − Select the Microsoft ProgressBar Control 6.0, click OK. Step 4 − Select the progress bar and set its Orientation in the Properties Window to 1 – ccOrientationVertical. Step 5 − Add control variable for Progress bar. Step 6 − Add the following code in the OnInitDialog() m_progBarCtrl.SetScrollRange(0,100,TRUE); m_progBarCtrl.put_Value(53); Step 7 − When you run this application again, you will see the progress bar in Vertical direction as well. In this chapter, we will discuss the various components of the file system. A drive is a physical device attached to a computer so it can store information. A logical disk, logical volume or virtual disk (VD or vdisk for short) is a virtual device that provides an area of usable storage capacity on one or more physical disk drive(s) in a computer system. A drive can be a hard disk, a CD ROM, a DVD ROM, a flash (USB) drive, a memory card, etc. One of the primary operations you will want to perform is to get a list of drives on the computer. Let us look into a simple example by creating a new MFC dialog based application. Step 1 − Drag one button from the toolbox, change its Caption to Get Drives Info. Step 2 − Remove the Caption of Static control (TODO line) and change its ID to IDC_STATIC_TEXT. Step 3 − Right-click on the button and select Add Event Handler. Step 4 − Select the BN_CLICKED message type and click the Add and Edit button. Step 5 − Add the value variable m_strDrives for Static Text control. To support drives on a computer, the Win32 library provides the GetLogicalDrives() function of Microsoft Window, which will retrieve a list of all drives on the current computer. Step 6 − When the above code is compiled and executed, you will see the following output. Step 7 − When you click the button, you can see all the drives on your computer. In computing, a directory is a file system cataloging structure which contains references to other computer files, and possibly other directories. Directory is a physical location. It can handle operations not available on a drive. Let us look into a simple example by creating a new MFC dialog based application Step 1 − Drag three buttons from the toolbox. Change their Captions to Create Directory, Delete Directory and Move Directory. Step 2 − Change the IDs of these buttons to IDC_BUTTON_CREATE, IDC_BUTTON_DELETE and IDC_BUTTON_MOVE. Step 3 − Remove the TODO line. Step 4 − Add event handler for each button. Step 5 − To create a directory, you can call the CreateDirectory() method of the Win32 library. Step 6 − Here is the Create button event handler implementation in which we will create one directory and then two more sub directories. void CMFCDirectoriesDemoDlg::OnBnClickedButtonCreate() { // TODO: Add your control notification handler code here SECURITY_ATTRIBUTES saPermissions; saPermissions.nLength = sizeof(SECURITY_ATTRIBUTES); saPermissions.lpSecurityDescriptor = NULL; saPermissions.bInheritHandle = TRUE; if (CreateDirectory(L"D:\\MFCDirectoryDEMO", &saPermissions) == TRUE) AfxMessageBox(L"The directory was created."); CreateDirectory(L"D:\\MFCDirectoryDEMO\\Dir1", NULL); CreateDirectory(L"D:\\MFCDirectoryDEMO\\Dir2", NULL); } Step 7 − To get rid of a directory, you can call the RemoveDirectory() function of the Win32 library. Here is the implementation of delete button event handler. void CMFCDirectoriesDemoDlg::OnBnClickedButtonDelete() { // TODO: Add your control notification handler code here if (RemoveDirectory(L"D:\\MFCDirectoryDEMO\\Dir1") == TRUE) AfxMessageBox(L"The directory has been deleted"); } Step 8 − If you want to move a directory, you can also call the same MoveFile() function. Here is the implementation of move button event handler in which we will create first new directory and then move the Dir2 to that directory. void CMFCDirectoriesDemoDlg::OnBnClickedButtonMove() { // TODO: Add your control notification handler code here CreateDirectory(L"D:\\MFCDirectory", NULL); if (MoveFile(L"D:\\MFCDirectoryDEMO\\Dir1", L"D:\\MFCDirectory\\Dir1") == TRUE) AfxMessageBox(L"The directory has been moved"); } Step 9 − When the above code is compiled and executed, you will see the following output. Step 10 − When you click the Create Directory button, it will create these directories. Step 11 − When you click on Delete Directory button, it will delete the Dir1. Most of the file processing in an MFC application is performed in conjunction with a class named CArchive. The CArchive class serves as a relay between the application and the medium used to either store data or make it available. It allows you to save a complex network of objects in a permanent binary form (usually disk storage) that persists after those objects are deleted. Here is the list of methods in CArchive class − Abort Closes an archive without throwing an exception. Close Flushes unwritten data and disconnects from the CFile. Flush Flushes unwritten data from the archive buffer. GetFile Gets the CFile object pointer for this archive. GetObjectSchema Called from the Serialize function to determine the version of the object that is being deserialized. IsBufferEmpty Determines whether the buffer has been emptied during a Windows Sockets receive process. IsLoading Determines whether the archive is loading. IsStoring Determines whether the archive is storing. MapObject Places objects in the map that are not serialized to the file, but that are available for subobjects to reference. Read Reads raw bytes. ReadClass Reads a class reference previously stored with WriteClass. ReadObject Calls an object's Serialize function for loading. ReadString Reads a single line of text. SerializeClass Reads or writes the class reference to the CArchive object depending on the direction of the CArchive. SetLoadParams Sets the size to which the load array grows. Must be called before any object is loaded or before MapObject or ReadObject is called. SetObjectSchema Sets the object schema stored in the archive object. SetStoreParams Sets the hash table size and the block size of the map used to identify unique objects during the serialization process. Write Writes raw bytes. WriteClass Writes a reference to the CRuntimeClass to the CArchive. WriteObject Calls an object's Serialize function for storing. WriteString Writes a single line of text. Here is the list of operators used to store and retrieve data operator << Stores objects and primitive types to the archive. operator >> Loads objects and primitive types from the archive. Let us look into a simple example by creating a new MFC dialog based application. Step 1 − Drag one edit control and two buttons as shown in the following snapshot. Step 2 − Add control variable m_editCtrl and value variable m_strEdit for edit control. Step 3 − Add click event handler for Open and Save buttons. Step 4 − Here is the implementation of event handlers. void CMFCFileProcessingDlg::OnBnClickedButtonOpen() { // TODO: Add your control notification handler code here UpdateData(TRUE); CFile file; file.Open(L"ArchiveText.rpr", CFile::modeRead); if(file) { CArchive ar(&file, CArchive::load); ar >> m_strEdit; ar.Close(); file.Close(); } UpdateData(FALSE); } void CMFCFileProcessingDlg::OnBnClickedButtonSave() { // TODO: Add your control notification handler code here UpdateData(TRUE); if (m_strEdit.GetLength() == 0) { AfxMessageBox(L"You must enter the name of the text."); return; } CFile file; file.Open(L"ArchiveText.rpr", CFile::modeCreate | CFile::modeWrite); CArchive ar(&file, CArchive::store); ar << m_strEdit; ar.Close(); file.Close(); } Step 5 − When the above code is compiled and executed, you will see the following output. Step 6 − Write something and click Save. It will save the data in binary format. Step 7 − Remove the test from edit control. As you click Open, observe that the same text is loaded again. The MFC library provides its own version of file processing. This is done through a class named CStdioFile. The CStdioFile class is derived from CFile. It can handle the reading and writing of Unicode text files as well as ordinary multi-byte text files. Here is the list of constructors, which can initialize a CStdioFile object − CStdioFile(); CStdioFile(CAtlTransactionManager* pTM); CStdioFile(FILE* pOpenStream); CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags); CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags, CAtlTransactionManager* pTM); Here is the list of methods in CStdioFile − Open Overloaded. Open is designed for use with the default CStdioFile constructor (Overrides CFile::Open). ReadString Reads a single line of text. Seek Positions the current file pointer. WriteString Writes a single line of text. Let us look into a simple example again by creating a new MFC dialog based application. Step 1 − Drag one edit control and two buttons as shown in the following snapshot. Step 2 − Add value variable m_strEditCtrl for edit control. Step 3 − Add click event handler for Open and Save buttons. Step 4 − Here is the implementation of event handlers. void CMFCStandardIODlg::OnBnClickedButtonOpen() { // TODO: Add your control notification handler code here UpdateData(TRUE); CStdioFile file; file.Open(L"D:\\MFCDirectoryDEMO\\test.txt", CFile::modeRead | CFile::typeText); file.ReadString(m_strEditCtrl); file.Close(); UpdateData(FALSE); } void CMFCStandardIODlg::OnBnClickedButtonSave() { // TODO: Add your control notification handler code here UpdateData(TRUE); CStdioFile file; if (m_strEditCtrl.GetLength() == 0) { AfxMessageBox(L"You must specify the text."); return; } file.Open(L"D:\\MFCDirectoryDEMO\\test.txt", CFile::modeCreate | CFile::modeWrite | CFile::typeText); file.WriteString(m_strEditCtrl); file.Close(); } Step 5 − When the above code is compiled and executed, you will see the following output. Step 6 − Write something and click Save. It will save the data in *.txt file. Step 7 − If you look at the location of the file, you will see that it contains the test.txt file. Step 8 − Now, close the application. Run the same application. When you click Open, the same text loads again. Step 9 − It starts by opening the file, reading the file, followed by updating the Edit Control. The Document/View architecture is the foundation used to create applications based on the Microsoft Foundation Classes library. It allows you to make distinct the different parts that compose a computer program including what the user sees as part of your application and the document a user would work on. This is done through a combination of separate classes that work as an ensemble. The parts that compose the Document/View architecture are a frame, one or more documents, and the view. Put together, these entities make up a usable application. A view is the platform the user is working on to do his or her job. To let the user do anything on an application, you must provide a view, which is an object based on the CView class. You can either directly use one of the classes derivedfrom CView or you can derive your own custom class from CView or one of its child classes. A document is similar to a bucket. For a computer application, a document holds the user's data. To create the document part of this architecture, you must derive an object from the CDocument class. As the name suggests, a frame is a combination of the building blocks, the structure, and the borders of an item. A frame gives "physical" presence to a window. It also defines the location of an object with regards to the Windows desktop. The expression Single Document Interface or SDI refers to a document that can present only one view to the user. This means that the application cannot display more than one document at a time. If you want to view another type of document of the current application, you must create another instance of the application. Notepad and WordPad are examples of SDI applications. Let us look into a simple example of single document interface or SDI by creating a new MFC dialog based application. Step 1 − Let us create a new MFC Application MFCSDIDemo with below mentioned settings. Step 2 − Select Single document from the Application type and MFC standard from Project Style. Step 3 − Click Finish to Continue. Step 4 − Once the project is created, run the application and you will see the following output. An application is referred to as a Multiple Document Interface, or MDI, if the user can open more than one document in the application without closing it. To provide this functionality, the application provides a parent frame that acts as the main frame of the computer program. Inside this frame, the application allows creating views with individual frames, making each view distinct from the other. Let us look into a simple example of multiple document interface or MDI by creating a new MFC dialog based application. Step 1 − Let us create a new MFC Application MFCMDIDemo with below mentioned settings. Step 2 − Select Multiple document from the Application type and MFC standard from Project Style. Step 3 − Click Finish to Continue. Step 4 − Once the project is created, run the application and you will see the following output. Step 5 − When you click on File → New menu option, it will create another child window as shown in the following snapshot. Step 6 − In Multiple Document Interface (MDI) applications, there is one main frame per application. In this case, a CMDIFrameWnd, and one CMDIChildWnd derived child frame for each document. Strings are objects that represent sequences of characters. The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a null character '\0'. This string is actually a one-dimensional array of characters which is terminated by a null character '\0'. A null-terminated string contains the characters that comprise the string followed by a null. A null-terminated string contains the characters that comprise the string followed by a null. Here is the simple example of character array. char word[12] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0' }; Following is another way to represent it. char word[] = "Hello, World"; Microsoft Foundation Class (MFC) library provides a class to manipulate string called CString. Following are some important features of CString. CString does not have a base class. CString does not have a base class. A CString object consists of a variable-length sequence of characters. A CString object consists of a variable-length sequence of characters. CString provides functions and operators using a syntax similar to that of Basic. CString provides functions and operators using a syntax similar to that of Basic. Concatenation and comparison operators, together with simplified memory management, make CString objects easier to use than ordinary character arrays. Concatenation and comparison operators, together with simplified memory management, make CString objects easier to use than ordinary character arrays. Here is the constructor of CString. CString Constructs CString objects in various ways Here is a list of Array Methods − GetLength Returns the number of characters in a CString object. IsEmpty Tests whether a CString object contains no characters. Empty Forces a string to have 0 length. GetAt Returns the character at a specified position. SetAt Sets a character at a specified position. Here is a list of Comparison Methods − Compare Compares two strings (case sensitive). CompareNoCase Compares two strings (case insensitive). Here is a list of Extraction Methods − Mid Extracts the middle part of a string (like the Basic MID$ function). Left Extracts the left part of a string (like the Basic LEFT$ function). Right Extracts the right part of a string (like the Basic RIGHT$ function). SpanIncluding Extracts the characters from the string, which are in the given character set. SpanExcluding Extracts the characters from the string which are not in the given character set. Here is a list of Conversion Methods. MakeUpper Converts all the characters in this string to uppercase characters. MakeLower Converts all the characters in this string to lowercase characters. MakeReverse Reverses the characters in this string. Format Format the string as sprintf does. TrimLeft Trim leading white-space characters from the string. TrimRight Trim trailing white-space characters from the string. Here is a list of Searching Methods. Find Finds a character or substring inside a larger string. ReverseFind Finds a character inside a larger string; starts from the end. FindOneOf Finds the first matching character from a set. Here is a list of Buffer Access Methods. GetBuffer Returns a pointer to the characters in the CString. GetBufferSetLength Returns a pointer to the characters in the CString, truncating to the specified length. ReleaseBuffer Releases control of the buffer returned by GetBuffer FreeExtra Removes any overhead of this string object by freeing any extra memory previously allocated to the string. LockBuffer Disables reference counting and protects the string in the buffer. UnlockBuffer Enables reference counting and releases the string in the buffer. Here is a list of Windows-Specific Methods. AllocSysString Allocates a BSTR from CString data. SetSysString Sets an existing BSTR object with data from a CString object. LoadString Loads an existing CString object from a Windows CE resource. Following are the different operations on CString objects − You can create a string by either using a string literal or creating an instance of CString class. BOOL CMFCStringDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon CString string1 = _T("This is a string1"); CString string2("This is a string2"); m_strText.Append(string1 + L"\n"); m_strText.Append(string2); UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } When the above code is compiled and executed, you will see the following output. You can create an empty string by either using an empty string literal or by using CString::Empty() method. You can also check whether a string is empty or not using Boolean property isEmpty. BOOL CMFCStringDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon CString string1 = _T(""); CString string2; string2.Empty(); if(string1.IsEmpty()) m_strText.Append(L"String1 is empty\n"); else m_strText.Append(string1 + L"\n"); if(string2.IsEmpty()) m_strText.Append(L"String2 is empty"); else m_strText.Append(string2); UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } When the above code is compiled and executed you will see the following output. To concatenate two or more strings, you can use + operator to concatenate two strings or a CString::Append() method. BOOL CMFCStringDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon //To concatenate two CString objects CString s1 = _T("This "); // Cascading concatenation s1 += _T("is a "); CString s2 = _T("test"); CString message = s1; message.Append(_T("big ") + s2); // Message contains "This is a big test". m_strText = L"message: " + message; UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } When the above code is compiled and executed you will see the following output. To find the length of the string you can use the CString::GetLength() method, which returns the number of characters in a CString object. BOOL CMFCStringDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon CString string1 = _T("This is string 1"); int length = string1.GetLength(); CString strLen; strLen.Format(L"\nString1 contains %d characters", length); m_strText = string1 + strLen; UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } When the above code is compiled and executed you will see the following output. To compare two strings variables you can use == operator BOOL CMFCStringDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon CString string1 = _T("Hello"); CString string2 = _T("World"); CString string3 = _T("MFC Tutorial"); CString string4 = _T("MFC Tutorial"); if (string1 == string2) m_strText = "string1 and string1 are same\n"; else m_strText = "string1 and string1 are not same\n"; if (string3 == string4) m_strText += "string3 and string4 are same"; else m_strText += "string3 and string4 are not same"; UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } When the above code is compiled and executed you will see the following output. CArray is a collection that is best used for data that is to be accessed in a random or non sequential manner. CArray class supports arrays that are like C arrays, but can dynamically shrink and grow as necessary. Array indexes always start at position 0. Array indexes always start at position 0. You can decide whether to fix the upper bound or enable the array to expand when you add elements past the current bound. You can decide whether to fix the upper bound or enable the array to expand when you add elements past the current bound. Memory is allocated contiguously to the upper bound, even if some elements are null. Memory is allocated contiguously to the upper bound, even if some elements are null. Add Adds an element to the end of the array; grows the array if necessary. Append Appends another array to the array; grows the array if necessary Copy Copies another array to the array; grows the array if necessary. ElementAt Returns a temporary reference to the element pointer within the array. FreeExtra Frees all unused memory above the current upper bound. GetAt Frees all unused memory above the current upper bound. GetCount Gets the number of elements in this array. GetData Allows access to elements in the array. Can be NULL. GetSize Gets the number of elements in this array. GetUpperBound Returns the largest valid index. InsertAt Inserts an element (or all the elements in another array) at a specified index. IsEmpty Determines whether the array is empty. RemoveAll Removes all the elements from this array. RemoveAt Removes an element at a specific index. SetAt Sets the value for a given index; array not allowed to grow. SetAtGrow Sets the value for a given index; grows the array if necessary. SetSize Sets the number of elements to be contained in this array. Following are the different operations on CArray objects − To create a collection of CArray values or objects, you must first decide the type of values of the collection. You can use one of the existing primitive data types such as int, CString, double etc. as shown below; CArray<CString, CString>strArray; To add an item you can use CArray::Add() function. It adds an item at the end of the array. In the OnInitDialog(), CArray object is created and three names are added as shown in the following code. CArray<CString, CString>strArray; //Add names to CArray strArray.Add(L"Ali"); strArray.Add(L"Ahmed"); strArray.Add(L"Mark"); To retrieve any item, you can use the CArray::GetAt() function. This function takes one integer parameter as an index of the array. Step 1 − Let us look at a simple example, which will retrieve all the names. //Retrive names from CArray for (int i = 0; i < strArray.GetSize(); i++) { m_strText.Append(strArray.GetAt(i) + L"\n"); } Step 2 − Here is the complete implementation of CMFCCArrayDlg::OnInitDialog() BOOL CMFCCArrayDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CArray<CString, CString>strArray; //Add names to CArray strArray.Add(L"Ali"); strArray.Add(L"Ahmed"); strArray.Add(L"Mark"); //Retrive names from CArray for (int i = 0; i < strArray.GetSize(); i++) { m_strText.Append(strArray.GetAt(i) + L"\n"); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } Step 3 − When the above code is compiled and executed, you will see the following output. To add item in the middle of array you can use the CArray::.InsertAt() function. It takes two paramerters — First, the index and Second, the value. Let us insert a new item at index 1 as shown in the following code. BOOL CMFCCArrayDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CArray<CString, CString>strArray; //Add names to CArray strArray.Add(L"Ali"); strArray.Add(L"Ahmed"); strArray.Add(L"Mark"); strArray.InsertAt(1, L"Allan"); //Retrive names from CArray for (int i = 0; i < strArray.GetSize(); i++) { m_strText.Append(strArray.GetAt(i) + L"\n"); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } When the above code is compiled and executed, you will see the following output. You can now see the name Allan dded as the second index. To update item in the middle of array you can use the CArray::.SetAt() function. It takes two paramerters — First, the index and Second, the value. Let us update the third element in the array as shown in the following code. BOOL CMFCCArrayDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CArray<CString, CString>strArray; //Add names to CArray strArray.Add(L"Ali"); strArray.Add(L"Ahmed"); strArray.Add(L"Mark"); strArray.InsertAt(1, L"Allan"); strArray.SetAt(2, L"Salman"); //Retrive names from CArray for (int i = 0; i < strArray.GetSize(); i++) { m_strText.Append(strArray.GetAt(i) + L"\n"); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } When the above code is compiled and executed, you will see the following output. You can now see that the value of third element is updated. To copy the entire array into another CArray object, you can use CArray::Copy() function. Step1 − Let us create another array and copy all the elements from first array as shown in the following code. BOOL CMFCCArrayDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu→AppendMenu(MF_SEPARATOR); pSysMenu→AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CArray<CString, CString>strArray; //Add names to CArray strArray.Add(L"Ali"); strArray.Add(L"Ahmed"); strArray.Add(L"Mark"); strArray.InsertAt(1, L"Allan"); strArray.SetAt(2, L"Salman"); CArray<CString, CString>strArray2; strArray2.Copy(strArray); //Retrive names from CArray for (int i = 0; i < strArray2.GetSize(); i++) { m_strText.Append(strArray2.GetAt(i) + L"\n"); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } You can now see that we have retrieved element from the 2nd array and the output is the same because we have used the copy function. To remove any particular item, you can use CArray::RemoveAt() function. To remove all the element from the list, CArray::RemoveAll() function can be used. Let us remove the second element from an array. BOOL CMFCCArrayDlg::OnInitDialog() { CDialogEx::OnInitDialog(); SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CArray<CString, CString>strArray; //Add names to CArray strArray.Add(L"Ali"); strArray.Add(L"Ahmed"); strArray.Add(L"Mark"); strArray.InsertAt(1, L"Allan"); strArray.SetAt(2, L"Salman"); CArray<CString, CString>strArray2; strArray2.Copy(strArray); strArray2.RemoveAt(1); //Retrive names from CArray for (int i = 0; i < strArray2.GetSize(); i++) { m_strText.Append(strArray2.GetAt(i) + L"\n"); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } When the above code is compiled and executed, you will see the following output. You can now see that the name Allan is no longer part of the array. A linked list is a linear data structure where each element is a separate object. Each element (we will call it a node) of a list comprises two items — the data and a reference to the next node. The last node has a reference to null. A linked list is a data structure consisting of a group of nodes which together represent a sequence. It is a way to store data with structures so that the programmer can automatically create a new place to store data whenever necessary. Some of its salient features are − Linked List is a sequence of links which contains items. Linked List is a sequence of links which contains items. Each link contains a connection to another link. Each link contains a connection to another link. Each item in the list is called a node. Each item in the list is called a node. If the list contains at least one node, then a new node is positioned as the last element in the list. If the list contains at least one node, then a new node is positioned as the last element in the list. If the list has only one node, that node represents the first and the last item. If the list has only one node, that node represents the first and the last item. There are two types of link list − Singly Linked Lists are a type of data structure. In a singly linked list, each node in the list stores the contents of the node and a pointer or reference to the next node in the list. A doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes. MFC provides a class CList which is a template linked list implementation and works perfectly. CList lists behave like doubly-linked lists. A variable of type POSITION is a key for the list. You can use a POSITION variable as an iterator to traverse a list sequentially and as a bookmark to hold a place. AddHead Adds an element (or all the elements in another list) to the head of the list (makes a new head). AddTail Adds an element (or all the elements in another list) to the tail of the list (makes a new tail). Find Gets the position of an element specified by pointer value. FindIndex Gets the position of an element specified by a zero-based index. GetAt Gets the element at a given position. GetCount Returns the number of elements in this list. GetHead Returns the head element of the list (cannot be empty). GetHeadPosition Returns the position of the head element of the list. GetNext Gets the next element for iterating. GetPrev Gets the previous element for iterating. GetSize Returns the number of elements in this list. GetTail Returns the tail element of the list (cannot be empty). GetTailPosition Returns the position of the tail element of the list. InsertAfter Inserts a new element after a given position. InsertBefore Inserts a new element before a given position. IsEmpty Tests for the empty list condition (no elements). RemoveAll Removes all the elements from this list. RemoveAt Removes an element from this list, specified by position. RemoveHead Removes the element from the head of the list. RemoveTail Removes the element from the tail of the list. SetAt Sets the element at a given position. Following are the different operations on CList objects − To create a collection of CList values or objects, you must first decide the type of values of the collection. You can use one of the existing primitive data types such as int, CString, double etc. as shown below in the following code. CList<double, double>m_list; To add an item, you can use CList::AddTail() function. It adds an item at the end of the list. To add an element at the start of the list, you can use the CList::AddHead() function. In the OnInitDialog() CList, object is created and four values are added as shown in the following code. CList<double, double>m_list; //Add items to the list m_list.AddTail(100.75); m_list.AddTail(85.26); m_list.AddTail(95.78); m_list.AddTail(90.1); A variable of type POSITION is a key for the list. You can use a POSITION variable as an iterator to traverse a list sequentially. Step 1 − To retrieve the element from the list, we can use the following code which will retrieve all the values. //iterate the list POSITION pos = m_list.GetHeadPosition(); while (pos) { double nData = m_list.GetNext(pos); CString strVal; strVal.Format(L"%.2f\n", nData); m_strText.Append(strVal); } Step 2 − Here is the complete CMFCCListDemoDlg::OnInitDialog() function. BOOL CMFCCListDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CList<double, double>m_list; //Add items to the list m_list.AddTail(100.75); m_list.AddTail(85.26); m_list.AddTail(95.78); m_list.AddTail(90.1); //iterate the list POSITION pos = m_list.GetHeadPosition(); while (pos) { double nData = m_list.GetNext(pos); CString strVal; strVal.Format(L"%.f\n", nData); m_strText.Append(strVal); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } Step 3 − When the above code is compiled and executed, you will see the following output. To add item in the middle of the list, you can use the CList::.InsertAfter() and CList::.InsertBefore() functions. It takes two paramerters — First, the position (where it can be added) and Second, the value. Step 1 − Let us insert a new item as shown in the followng code. BOOL CMFCCListDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CList<double, double>m_list; //Add items to the list m_list.AddTail(100.75); m_list.AddTail(85.26); m_list.AddTail(95.78); m_list.AddTail(90.1); POSITION position = m_list.Find(85.26); m_list.InsertBefore(position, 200.0); m_list.InsertAfter(position, 300.0); //iterate the list POSITION pos = m_list.GetHeadPosition(); while (pos) { double nData = m_list.GetNext(pos); CString strVal; strVal.Format(L"%.2f\n", nData); m_strText.Append(strVal); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } Step 2 − You can now see see that we first retrieved the position of value 85.26 and then inserted one element before and one element after that value. Step 3 − When the above code is compiled and executed, you will see the following output. To update item at the middle of array, you can use the CArray::.SetAt() function. It takes two paramerters — First, the position and Second, the value. Let us update the 300.00 to 400 in the list as shown in the following code. BOOL CMFCCListDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CList<double, double>m_list; //Add items to the list m_list.AddTail(100.75); m_list.AddTail(85.26); m_list.AddTail(95.78); m_list.AddTail(90.1); POSITION position = m_list.Find(85.26); m_list.InsertBefore(position, 200.0); m_list.InsertAfter(position, 300.0); position = m_list.Find(300.00); m_list.SetAt(position, 400.00); //iterate the list POSITION pos = m_list.GetHeadPosition(); while (pos) { double nData = m_list.GetNext(pos); CString strVal; strVal.Format(L"%.2f\n", nData); m_strText.Append(strVal); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } When the above code is compiled and executed, you will see the following output. You can now see that the value of 300.00 is updated to 400.00. To remove any particular item, you can use CList::RemoveAt() function. To remove all the element from the list, CList::RemoveAll() function can be used. Let us remove the element, which has 95.78 as its value. BOOL CMFCCListDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CList<double, double>m_list; //Add items to the list m_list.AddTail(100.75); m_list.AddTail(85.26); m_list.AddTail(95.78); m_list.AddTail(90.1); POSITION position = m_list.Find(85.26); m_list.InsertBefore(position, 200.0); m_list.InsertAfter(position, 300.0); position = m_list.Find(300.00); m_list.SetAt(position, 400.00); position = m_list.Find(95.78); m_list.RemoveAt(position); //iterate the list POSITION pos = m_list.GetHeadPosition(); while (pos) { double nData = m_list.GetNext(pos); CString strVal; strVal.Format(L"%.2f\n", nData); m_strText.Append(strVal); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } When the above code is compiled and executed, you will see the following output. You can now see that the value of 95.78 is no longer part of the list. A database is a collection of information that is organized so that it can easily be accessed, managed, and updated. The MFC database classes based on ODBC are designed to provide access to any database for which an ODBC driver is available. Because the classes use ODBC, your application can access data in many different data formats and different local/remote configurations. You do not have to write special-case code to handle different database management systems (DBMSs). As long as your users have an appropriate ODBC driver for the data they want to access, they can use your program to manipulate data in tables stored there. A data source is a specific instance of data hosted by some database management system (DBMS). Examples include Microsoft SQL Server, Microsoft Access, etc. MFC provides a class CDatabase which represents a connection to a data source, through which you can operate on the data source. You can have one or more CDatabase objects active at a time in your application. BeginTrans Starts a "transaction" — a series of reversible calls to the AddNew, Edit, Delete, and Update member functions of class CRecordset — on the connected data source. The data source must support transactions for BeginTrans to have any effect. BindParameters Allows you to bind parameters before calling ExecuteSQL. Cancel Cancels an asynchronous operation or a process from a second thread. CanTransact Returns nonzero if the data source supports transactions. CanUpdate Returns nonzero if the CDatabase object is updatable (not read-only). Close Closes the data source connection. CommitTrans Completes a transaction begun by BeginTrans. Commands in the transaction that alter the data source are carried out. ExecuteSQL Executes a SQL statement. No data records are returned. GetBookmarkPersistence Identifies the operations through which bookmarks persist on recordset objects. GetConnect Returns the ODBC connection string used to connect the CDatabase object to a data source. GetCursorCommitBehavior Identifies the effect of committing a transaction on an open recordset object. GetCursorRollbackBehavior Identifies the effect of rolling back a transaction on an open recordset object. GetDatabaseName Returns the name of the database currently in use. IsOpen Returns nonzero if the CDatabase object is currently connected to a data source. OnSetOptions Called by the framework to set standard connection options. The default implementation sets the query timeout value. You can establish these options ahead of time by calling SetQueryTimeout. Open Establishes a connection to a data source (through an ODBC driver). OpenEx Establishes a connection to a data source (through an ODBC driver). Rollback Reverses changes made during the current transaction. The data source returns to its previous state, as defined at the BeginTrans call, unaltered. SetLoginTimeout Sets the number of seconds after which a data source connection attempt will time out. SetQueryTimeout Sets the number of seconds after which database query operations will time out. Affects all subsequent recordset Open, AddNew, Edit, and Delete calls. Let us look into a simple example by creating a new MFC dialog based application. Step 1 − Change the caption of TODO line to Retrieve Data from Database and drag one button and one List control as shown in the following snapshot. Step 2 − Add click event handler for button and control variable m_ListControl for List Control. Step 3 − We have simple database which contains one Employees table with some records as shown in the following snapshot. Step 4 − We need to include the following headers file so that we can use CDatabase class. #include "odbcinst.h" #include "afxdb.h" The SQL INSERT INTO Statement is used to add new rows of data to a table in the database. Step 1 − To add new records, we will use the ExecuteSQL() function of CDatabase class as shown in the following code. CDatabase database; CString SqlString; CString strID, strName, strAge; CString sDriver = L"MICROSOFT ACCESS DRIVER (*.mdb)"; CString sDsn; CString sFile = L"D:\\Test.mdb"; // You must change above path if it's different int iRec = 0; // Build ODBC connection string sDsn.Format(L"ODBC;DRIVER={%s};DSN='';DBQ=%s", sDriver, sFile); TRY { // Open the database database.Open(NULL,false,false,sDsn); SqlString = "INSERT INTO Employees (ID,Name,age) VALUES (5,'Sanjay',69)"; database.ExecuteSQL(SqlString); // Close the database database.Close(); }CATCH(CDBException, e) { // If a database exception occured, show error msg AfxMessageBox(L"Database error: " + e→m_strError); } END_CATCH; Step 2 − When the above code is compiled and executed, you will see that a new record is added in your database. To retrieve the above table in MFC application, we implement the database related operations in the button event handler as shown in the following steps. Step 1 − To use CDatabase, construct a CDatabase object and call its Open() function. This will open the connection. Step 2 − Construct CRecordset objects for operating on the connected data source, pass the recordset constructor a pointer to your CDatabase object. Step 3 − After using the connection, call the Close function and destroy the CDatabase object. void CMFCDatabaseDemoDlg::OnBnClickedButtonRead() { // TODO: Add your control notification handler code here CDatabase database; CString SqlString; CString strID, strName, strAge; CString sDriver = "MICROSOFT ACCESS DRIVER (*.mdb)"; CString sFile = L"D:\\Test.mdb"; // You must change above path if it's different int iRec = 0; // Build ODBC connection string sDsn.Format("ODBC;DRIVER={%s};DSN='';DBQ=%s",sDriver,sFile); TRY { // Open the database database.Open(NULL,false,false,sDsn); // Allocate the recordset CRecordset recset( &database ); // Build the SQL statement SqlString = "SELECT ID, Name, Age " "FROM Employees"; // Execute the query recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly); // Reset List control if there is any data ResetListControl(); // populate Grids ListView_SetExtendedListViewStyle(m_ListControl,LVS_EX_GRIDLINES); // Column width and heading m_ListControl.InsertColumn(0,"Emp ID",LVCFMT_LEFT,-1,0); m_ListControl.InsertColumn(1,"Name",LVCFMT_LEFT,-1,1); m_ListControl.InsertColumn(2, "Age", LVCFMT_LEFT, -1, 1); m_ListControl.SetColumnWidth(0, 120); m_ListControl.SetColumnWidth(1, 200); m_ListControl.SetColumnWidth(2, 200); // Loop through each record while( !recset.IsEOF() ) { // Copy each column into a variable recset.GetFieldValue("ID",strID); recset.GetFieldValue("Name",strName); recset.GetFieldValue("Age", strAge); // Insert values into the list control iRec = m_ListControl.InsertItem(0,strID,0); m_ListControl.SetItemText(0,1,strName); m_ListControl.SetItemText(0, 2, strAge); // goto next record recset.MoveNext(); } // Close the database database.Close(); }CATCH(CDBException, e) { // If a database exception occured, show error msg AfxMessageBox("Database error: "+e→m_strError); } END_CATCH; } // Reset List control void CMFCDatabaseDemoDlg::ResetListControl() { m_ListControl.DeleteAllItems(); int iNbrOfColumns; CHeaderCtrl* pHeader = (CHeaderCtrl*)m_ListControl.GetDlgItem(0); if (pHeader) { iNbrOfColumns = pHeader→GetItemCount(); } for (int i = iNbrOfColumns; i >= 0; i--) { m_ListControl.DeleteColumn(i); } } Step 4 − Here is the header file. // MFCDatabaseDemoDlg.h : header file // #pragma once #include "afxcmn.h" // CMFCDatabaseDemoDlg dialog class CMFCDatabaseDemoDlg : public CDialogEx { // Construction public: CMFCDatabaseDemoDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data #ifdef AFX_DESIGN_TIME enum { IDD = IDD_MFCDATABASEDEMO_DIALOG }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support void ResetListControl(); // Implementation protected: HICON m_hIcon; // Generated message map functions virtual BOOL OnInitDialog(); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: CListCtrl m_ListControl; afx_msg void OnBnClickedButtonRead(); }; Step 5 − When the above code is compiled and executed, you will see the following output. Step 6 − Press the Read button to execute the database operations. It will retrieve the Employees table. The SQL UPDATE Query is used to modify the existing records in a table. You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows would be affected. Step 1 − Let us look into a simple example by updating the Age where ID is equal to 5. SqlString = L"UPDATE Employees SET Age = 59 WHERE ID = 5;"; database.ExecuteSQL(SqlString); Step 2 − Here is the complete code of button click event. void CMFCDatabaseDemoDlg::OnBnClickedButtonRead() { // TODO: Add your control notification handler code here CDatabase database; CString SqlString; CString strID, strName, strAge; CString sDriver = L"MICROSOFT ACCESS DRIVER (*.mdb)"; CString sDsn; CString sFile = L"C:\\Users\\Muhammad.Waqas\\Downloads\\Compressed\\ReadDB_demo\\Test.mdb"; // You must change above path if it's different int iRec = 0; // Build ODBC connection string sDsn.Format(L"ODBC;DRIVER={%s};DSN='';DBQ=%s", sDriver, sFile); TRY { // Open the database database.Open(NULL,false,false,sDsn); // Allocate the recordset CRecordset recset(&database); SqlString = L"UPDATE Employees SET Age = 59 WHERE ID = 5;"; database.ExecuteSQL(SqlString); SqlString = "SELECT ID, Name, Age FROM Employees"; // Build the SQL statement SqlString = "SELECT ID, Name, Age FROM Employees"; // Execute the query recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly); // Reset List control if there is any data ResetListControl(); // populate Grids ListView_SetExtendedListViewStyle(m_listCtrl,LVS_EX_GRIDLINES); // Column width and heading m_listCtrl.InsertColumn(0,L"Emp ID",LVCFMT_LEFT,-1,0); m_listCtrl.InsertColumn(1,L"Name",LVCFMT_LEFT,-1,1); m_listCtrl.InsertColumn(2, L"Age", LVCFMT_LEFT, -1, 1); m_listCtrl.SetColumnWidth(0, 120); m_listCtrl.SetColumnWidth(1, 200); m_listCtrl.SetColumnWidth(2, 200); // Loop through each record while (!recset.IsEOF()) { // Copy each column into a variable recset.GetFieldValue(L"ID",strID); recset.GetFieldValue(L"Name",strName); recset.GetFieldValue(L"Age", strAge); // Insert values into the list control iRec = m_listCtrl.InsertItem(0,strID,0); m_listCtrl.SetItemText(0,1,strName); m_listCtrl.SetItemText(0, 2, strAge); // goto next record recset.MoveNext(); } // Close the database database.Close(); }CATCH(CDBException, e) { // If a database exception occured, show error msg AfxMessageBox(L"Database error: " + e→m_strError); } END_CATCH; } Step 3 − When the above code is compiled and executed, you will see the following output. Step 4 − Press the Read button to execute the database operations. It will retrieve the following Employees table. Step 5 − You can now see that age is updated from 69 to 59. The SQL DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete selected rows, otherwise all the records would be deleted. Step 1 − Let us look into a simple example by deleting the record where ID is equal to 3. SqlString = L"DELETE FROM Employees WHERE ID = 3;"; database.ExecuteSQL(SqlString); Step 2 − Here is the complete code of button click event. void CMFCDatabaseDemoDlg::OnBnClickedButtonRead() { // TODO: Add your control notification handler code here CDatabase database; CString SqlString; CString strID, strName, strAge; CString sDriver = L"MICROSOFT ACCESS DRIVER (*.mdb)"; CString sDsn; CString sFile = L"C:\\Users\\Muhammad.Waqas\\Downloads\\Compressed\\ReadDB_demo\\Test.mdb"; // You must change above path if it's different int iRec = 0; // Build ODBC connection string sDsn.Format(L"ODBC;DRIVER={%s};DSN='';DBQ=%s", sDriver, sFile); TRY { // Open the database database.Open(NULL,false,false,sDsn); // Allocate the recordset CRecordset recset(&database); SqlString = L"DELETE FROM Employees WHERE ID = 3;"; database.ExecuteSQL(SqlString); SqlString = "SELECT ID, Name, Age FROM Employees"; // Build the SQL statement SqlString = "SELECT ID, Name, Age FROM Employees"; // Execute the query recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly); // Reset List control if there is any data ResetListControl(); // populate Grids ListView_SetExtendedListViewStyle(m_listCtrl,LVS_EX_GRIDLINES); // Column width and heading m_listCtrl.InsertColumn(0,L"Emp ID",LVCFMT_LEFT,-1,0); m_listCtrl.InsertColumn(1,L"Name",LVCFMT_LEFT,-1,1); m_listCtrl.InsertColumn(2, L"Age", LVCFMT_LEFT, -1, 1); m_listCtrl.SetColumnWidth(0, 120); m_listCtrl.SetColumnWidth(1, 200); m_listCtrl.SetColumnWidth(2, 200); // Loop through each record while (!recset.IsEOF()) { // Copy each column into a variable recset.GetFieldValue(L"ID",strID); recset.GetFieldValue(L"Name",strName); recset.GetFieldValue(L"Age", strAge); // Insert values into the list control iRec = m_listCtrl.InsertItem(0,strID,0); m_listCtrl.SetItemText(0,1,strName); m_listCtrl.SetItemText(0, 2, strAge); // goto next record recset.MoveNext(); } // Close the database database.Close(); }CATCH(CDBException, e) { // If a database exception occured, show error msg AfxMessageBox(L"Database error: " + e→m_strError); } END_CATCH; } Step 3 − When the above code is compiled and executed, you will see the following output. Step 4 − Press the Read button to execute the database operations. It will retrieve the Employees table. Serialization is the process of writing or reading an object to or from a persistent storage medium such as a disk file. Serialization is ideal for situations where it is desired to maintain the state of structured data (such as C++ classes or structures) during or after the execution of a program. When performing file processing, the values are typically of primitive types (char, short, int, float, or double). In the same way, we can individually save many values, one at a time. This technique doesn't include an object created from (as a variable of) a class. The MFC library has a high level of support for serialization. It starts with the CObject class that is the ancestor to most MFC classes, which is equipped with a Serialize() member function. Let us look into a simple example by creating a new MFC project. Step 1 − Remove the TODO line and design your dialog box as shown in the following snapshot. Step 2 − Add value variables for all the edit controls. For Emp ID and Age mentioned, the value type is an integer as shown in the following snapshot. Step 3 − Add the event handler for both the buttons. Step 4 − Let us now add a simple Employee class, which we need to serialize. Here is the declaration of Employee class in header file. class CEmployee : public CObject { public: int empID; CString empName; int age; CEmployee(void); ~CEmployee(void); private: public: void Serialize(CArchive& ar); DECLARE_SERIAL(CEmployee); }; Step 5 − Here is the definition of Employee class in source (*.cpp) file. IMPLEMENT_SERIAL(CEmployee, CObject, 0) CEmployee::CEmployee(void) { } CEmployee::~CEmployee(void) { } void CEmployee::Serialize(CArchive& ar) { CObject::Serialize(ar); if (ar.IsStoring()) ar << empID << empName << age; else ar >> empID >> empName >> age; } Step 6 − Here is the implementation of Save button event handler. void CMFCSerializationDlg::OnBnClickedButtonSave() { // TODO: Add your control notification handler code here UpdateData(TRUE); CEmployee employee; CFile file; file.Open(L"EmployeeInfo.hse", CFile::modeCreate | CFile::modeWrite); CArchive ar(&file, CArchive::store); employee.empID = m_id; employee.empName = m_strName; employee.age = m_age; employee.Serialize(ar); ar.Close(); } Step 7 − Here is the implementation of Open button event handler. void CMFCSerializationDlg::OnBnClickedButtonOpen() { // TODO: Add your control notification handler code here UpdateData(TRUE); CFile file; file.Open(L"EmployeeInfo.hse", CFile::modeRead); CArchive ar(&file, CArchive::load); CEmployee employee; employee.Serialize(ar); m_id = employee.empID; m_strName = employee.empName; m_age = employee.age; ar.Close(); file.Close(); UpdateData(FALSE); } Step 8 − When the above code is compiled and executed, you will see the following output. Step 9 − Enter the info in all the fields and click Save and close this program. Step 10 − It will save the data. Run the application again and click open. It will load the Employee information. The Microsoft Foundation Class (MFC) library provides support for multithreaded applications. A thread is a path of execution within a process. When you start Notepad, the operating system creates a process and begins executing the primary thread of that process. When this thread terminates, so does the process. You can create additional threads in your application if you want. All threads in MFC applications are represented by CWinThread objects. In most situations, you do not even have to explicitly create these objects; instead call the framework helper function AfxBeginThread, which creates the CWinThread object for you. Let us look into a simple example by creating a new MFC dialog based application. Step 1 − Change the Caption and ID of Static control to Click on Start Thread button and IDC_STATIC_TEXT respectively. Step 2 − Drag two buttons and add click event handlers for these buttons. Step 3 − Add control variable for static text control. Step 4 − Now add the following three global variables at the start of CMFCMultithreadingDlg.cpp file. int currValue; int maxValue; BOOL stopNow; Step 5 − Add the WM_TIMER message in CMFCMultithreadingDlg class. Here is the implementation of OnTimer() void CMFCMultithreadingDlg::OnTimer(UINT_PTR nIDEvent) { // TODO: Add your message handler code here and/or call default CString sStatusMsg; sStatusMsg.Format(L"Running: %d", currValue); m_ctrlStatus.SetWindowText(sStatusMsg); CDialogEx::OnTimer(nIDEvent); } Step 6 − Now add a sample function for using in AfxBeginThread in CMFCMultithreadingDlg class. UINT MyThreadProc(LPVOID Param) { while (!stopNow && (currValue < maxValue)) { currValue++; Sleep(50); // would do some work here } return TRUE; } Step 7 − Here is the implementation of event handler for Start Thread button, which will start the thread. void CMFCMultithreadingDlg::OnBnClickedButtonStart() { // TODO: Add your control notification handler code here currValue = 0; maxValue = 5000; stopNow = 0; m_ctrlStatus.SetWindowText(L"Starting..."); SetTimer(1234, 333, 0); // 3 times per second AfxBeginThread(MyThreadProc, 0); // <<== START THE THREAD } Step 8 − Here is the implementation of event handler for Stop Thread button, which will stop the thread. void CMFCMultithreadingDlg::OnBnClickedButtonStop() { // TODO: Add your control notification handler code here stopNow = TRUE; KillTimer(1234); m_ctrlStatus.SetWindowText(L"Stopped"); } Step 9 − Here is the complete source file. // MFCMultithreadingDlg.cpp : implementation file // #include "stdafx.h" #include "MFCMultithreading.h" #include "MFCMultithreadingDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMFCMultithreadingDlg dialog int currValue; int maxValue; BOOL stopNow; CMFCMultithreadingDlg::CMFCMultithreadingDlg(CWnd* pParent /* = NULL*/) : CDialogEx(IDD_MFCMULTITHREADING_DIALOG, pParent) { m_hIcon = AfxGetApp() -> LoadIcon(IDR_MAINFRAME); } void CMFCMultithreadingDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_STATIC_TEXT, m_ctrlStatus); } BEGIN_MESSAGE_MAP(CMFCMultithreadingDlg, CDialogEx) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON_START, &CMFCMultithreadingDlg::OnBnClickedButtonStart) ON_WM_TIMER() ON_BN_CLICKED(IDC_BUTTON_STOP, &CMFCMultithreadingDlg::OnBnClickedButtonStop) END_MESSAGE_MAP() // CMFCMultithreadingDlg message handlers BOOL CMFCMultithreadingDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CMFCMultithreadingDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); }else { CDialogEx::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMFCMultithreadingDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } UINT /*CThreadDlg::*/MyThreadProc(LPVOID Param) //Sample function for using in AfxBeginThread { while (!stopNow && (currValue < maxValue)) { currValue++; Sleep(50); // would do some work here } return TRUE; } void CMFCMultithreadingDlg::OnBnClickedButtonStart() { // TODO: Add your control notification handler code here currValue = 0; maxValue = 5000; stopNow = 0; m_ctrlStatus.SetWindowText(L"Starting..."); SetTimer(1234, 333, 0); // 3 times per second AfxBeginThread(MyThreadProc, 0); // <<== START THE THREAD } void CMFCMultithreadingDlg::OnTimer(UINT_PTR nIDEvent) { // TODO: Add your message handler code here and/or call default CString sStatusMsg; sStatusMsg.Format(L"Running: %d", currValue); m_ctrlStatus.SetWindowText(sStatusMsg); CDialogEx::OnTimer(nIDEvent); } void CMFCMultithreadingDlg::OnBnClickedButtonStop() { // TODO: Add your control notification handler code here stopNow = TRUE; KillTimer(1234); m_ctrlStatus.SetWindowText(L"Stopped"); } Step 10 − When the above code is compiled and executed, you will see the following output. Step 11 − Now click on Start Thread button. Step 12 − Click the Stop Thread button. It will stop the thread. Microsoft provides many APIs for programming both client and server applications. Many new applications are being written for the Internet, and as technologies, browser capabilities, and security options change, new types of applications will be written. Your custom application can retrieve information and provide data on the Internet. MFC provides a class CSocket for writing network communications programs with Windows Sockets. Here is a list of methods in CSocket class. Attach Attaches a SOCKET handle to a CSocket object. CancelBlockingCall Cancels a blocking call that is currently in progress. Create Creates a socket. FromHandle Returns a pointer to a CSocket object, given a SOCKET handle. IsBlocking Determines whether a blocking call is in progress. Let us look into a simple example by creating a MFS SDI application. Step 1 − Enter MFCServer in the name field and click OK. Step 2 − On Advanced Features tab, check the Windows sockets option. Step 3 − Once the project is created, add a new MFC class CServerSocket. Step 4 − Select the CSocket as base class and click Finish. Step 5 − Add more MFC class CReceivingSocket. Step 6 − CRecevingSocket will receive incoming messages from client. In CMFCServerApp, the header file includes the following files − #include "ServerSocket.h" #include "MFCServerView.h" Step 7 − Add the following two class variables in CMFCServerApp class. CServerSocket m_serverSocket; CMFCServerView m_pServerView; Step 8 − In CMFCServerApp::InitInstance() method, create the socket and specify the port and then call the Listen method as shown below. m_serverSocket.Create(6666); m_serverSocket.Listen(); Step 9 − Include the following header file in CMFCServerView header file. #include "MFCServerDoc.h" Step 10 − Override the OnAccept function from Socket class. Step 11 − Select CServerSocket in class view and the highlighted icon in Properties window. Now, Add OnAccept. Here is the implementation of OnAccept function. void CServerSocket::OnAccept(int nErrorCode) { // TODO: Add your specialized code here and/or call the base class AfxMessageBox(L"Connection accepted"); CSocket::OnAccept(nErrorCode); } Step 12 − Add OnReceive() function. void CServerSocket::OnReceive(int nErrorCode) { // TODO: Add your specialized code here and/or call the base class AfxMessageBox(L"Data Received"); CSocket::OnReceive(nErrorCode); } Step 13 − Add OnReceive() function in CReceivingSocket class. Right-click on the CMFCServerView class in solution explorer and select Add → AddFunction. Step 14 − Enter the above mentioned information and click finish. Step 15 − Add the following CStringArray variable in CMFCServerView header file. CStringArray m_msgArray; Step 16 − Here is the implementation of AddMsg() function. void CMFCServerView::AddMsg(CString message) { m_msgArray.Add(message); Invalidate(); } Step 17 − Update the constructor as shown in the following code. CMFCServerView::CMFCServerView() { ((CMFCServerApp*)AfxGetApp()) -> m_pServerView = this; } Step 18 − Here is the implementation of OnDraw() function, which display messages. void CMFCServerView::OnDraw(CDC* pDC) { int y = 100; for (int i = 0; m_msgArray.GetSize(); i++) { pDC->TextOut(100, y, m_msgArray.GetAt(i)); y += 50; } CMFCServerDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } Step 19 − The server side is now complete. It will receive message from the client. Step 1 − Let us create a new MFC dialog based application for client side application. Step 2 − On Advanced Features tab, check the Windows sockets option as shown above. Step 3 − Once the project is created, design your dialog box as shown in the following snapshot. Step 4 − Add event handlers for Connect and Send buttons. Step 5 − Add value variables for all the three edit controls. For port edit control, select the variable type UINT. Step 6 − Add MFC class for connecting and sending messages. Step 7 − Include the header file of CClientSocket class in the header file CMFCClientDemoApp class and add the class variable. Similarly, add the class variable in CMFCClientDemoDlg header file as well. CClientSocket m_clientSocket; Step 8 − Here is the implementation of Connect button event handler. void CMFCClientDemoDlg::OnBnClickedButtonConnect() { // TODO: Add your control notification handler code here UpdateData(TRUE); m_clientSocket.Create(); if (m_clientSocket.Connect(m_ipAddress, m_port)) { AfxMessageBox(L"Connection Successfull"); }else { AfxMessageBox(L"Connection Failed"); } DWORD error = GetLastError(); } Step 9 − Here is the implementation of Send button event handler. void CMFCClientDemoDlg::OnBnClickedButtonSend() { // TODO: Add your control notification handler code here UpdateData(TRUE); if (m_clientSocket.Send(m_message.GetBuffer(m_message.GetLength()), m_message.GetLength())) { }else { AfxMessageBox(L"Failed to send message"); } } Step 10 − First run the Server application and then the client application. Enter the local host ip and port and click Connect. Step 11 − You will now see the message on Server side as shown in the following snapshot. Windows provides a variety of drawing tools to use in device contexts. It provides pens to draw lines, brushes to fill interiors, and fonts to draw text. MFC provides graphic-object classes equivalent to the drawing tools in Windows. A device context is a Windows data structure containing information about the drawing attributes of a device such as a display or a printer. All drawing calls are made through a device-context object, which encapsulates the Windows APIs for drawing lines, shapes, and text. Device contexts allow device-independent drawing in Windows. Device contexts can be used to draw to the screen, to the printer, or to a metafile. CDC is the most fundamental class to draw in MFC. The CDC object provides member functions to perform the basic drawing steps, as well as members for working with a display context associated with the client area of a window. AbortDoc Terminates the current print job, erasing everything the application has written to the device since the last call of the StartDoc member function. AbortPath Closes and discards any paths in the device context. AddMetaFileComment Copies the comment from a buffer into a specified enhanced-format metafile. AlphaBlend Displays bitmaps that have transparent or semitransparent pixels. AngleArc Draws a line segment and an arc, and moves the current position to the ending point of the arc. Arc Draws an elliptical arc. ArcTo Draws an elliptical arc. This function is similar to Arc, except that the current position is updated. Attach Attaches a Windows device context to this CDC object. BeginPath Opens a path bracket in the device context. BitBlt Copies a bitmap from a specified device context. Chord Draws a chord (a closed figure bounded by the intersection of an ellipse and a line segment). CloseFigure Closes an open figure in a path. CreateCompatibleDC Creates a memory-device context that is compatible with another device context. You can use it to prepare images in memory. CreateDC Creates a device context for a specific device. CreateIC Creates an information context for a specific device. This provides a fast way to get information about the device without creating a device context. DeleteDC Deletes the Windows device context associated with this CDC object. DeleteTempMap Called by the CWinApp idle-time handler to delete any temporary CDC object created by FromHandle. Also detaches the device context. Detach Detaches the Windows device context from this CDC object. DPtoHIMETRIC Converts device units into HIMETRIC units. DPtoLP Converts device units into logical units. Draw3dRect Draws a three-dimensional rectangle. DrawDragRect Erases and redraws a rectangle as it is dragged. DrawEdge Draws the edges of a rectangle. DrawEscape Accesses drawing capabilities of a video display that are not directly available through the graphics device interface (GDI). DrawFocusRect Draws a rectangle in the style used to indicate focus. DrawFrameControl Draw a frame control. DrawIcon Draws an icon. DrawState Displays an image and applies a visual effect to indicate a state. DrawText Draws formatted text in the specified rectangle. DrawTextEx Draws formatted text in the specified rectangle using additional formats. Ellipse Draws an ellipse. EndDoc Ends a print job started by the StartDoc member function. EndPage Informs the device driver that a page is ending. EndPath Closes a path bracket and selects the path defined by the bracket into the device context. EnumObjects Enumerates the pens and brushes available in a device context. Escape Allows applications to access facilities that are not directly available from a particular device through GDI. Also allows access to Windows escape functions. Escape calls made by an application are translated and sent to the device driver. ExcludeClipRect Creates a new clipping region that consists of the existing clipping region minus the specified rectangle. ExcludeUpdateRgn Prevents drawing within invalid areas of a window by excluding an updated region in the window from a clipping region. ExtFloodFill Fills an area with the current brush. Provides more flexibility than the FloodFill member function. ExtTextOut Writes a character string within a rectangular region using the currently selected font. FillPath Closes any open figures in the current path and fills the path's interior by using the current brush and polygonfilling mode. FillRect Fills a given rectangle by using a specific brush. FillRgn Fills a specific region with the specified brush. FillSolidRect Fills a rectangle with a solid color. FlattenPath Transforms any curves in the path selected into the current device context, and turns each curve into a sequence of lines. FloodFill Fills an area with the current brush. FrameRect Draws a border around a rectangle. FrameRgn Draws a border around a specific region using a brush. FromHandle Returns a pointer to a CDC object when given a handle to a device context. If a CDC object is not attached to the handle, a temporary CDC object is created and attached. GetArcDirection Returns the current arc direction for the device context. GetAspectRatioFilter Retrieves the setting for the current aspect-ratio filter. GetBkColor Retrieves the current background color. GetBkMode Retrieves the background mode. GetBoundsRect Returns the current accumulated bounding rectangle for the specified device context. GetBrushOrg Retrieves the origin of the current brush. GetCharABCWidths Retrieves the widths, in logical units, of consecutive characters in a given range from the current font. GetCharABCWidthsI Retrieves the widths, in logical units, of consecutive glyph indices in a specified range from the current TrueType font. GetCharacterPlacement Retrieves various types of information on a character string. GetCharWidth Retrieves the fractional widths of consecutive characters in a given range from the current font. GetCharWidthI Retrieves the widths, in logical coordinates, of consecutive glyph indices in a specified range from the current font. GetClipBox Retrieves the dimensions of the tightest bounding rectangle around the current clipping boundary. GetColorAdjustment Retrieves the color adjustment values for the device context. GetCurrentBitmap Returns a pointer to the currently selected CBitmap object. GetCurrentBrush Returns a pointer to the currently selected CBrush object. GetCurrentFont Returns a pointer to the currently selected CFont object. GetCurrentPalette Returns a pointer to the currently selected CPalette object. GetCurrentPen Returns a pointer to the currently selected CPen object. GetCurrentPosition Retrieves the current position of the pen (in logical coordinates). GetDCBrushColor Retrieves the current brush color. GetDCPenColor Retrieves the current pen color. GetDeviceCaps Retrieves a specified kind of device-specific information about a given display device's capabilities. GetFontData Retrieves font metric information from a scalable font file. The information to retrieve is identified by specifying an offset into the font file and the length of the information to return. GetFontLanguageInfo Returns information about the currently selected font for the specified display context. GetGlyphOutline Retrieves the outline curve or bitmap for an outline character in the current font. GetGraphicsMode Retrieves the current graphics mode for the specified device context. GetHalftoneBrush Retrieves a halftone brush. GetKerningPairs Retrieves the character kerning pairs for the font that is currently selected in the specified device context. GetLayout Retrieves the layout of a device context (DC). The layout can be either left to right (default) or right to left (mirrored). GetMapMode Retrieves the current mapping mode. GetMiterLimit Returns the miter limit for the device context. GetNearestColor Retrieves the closest logical color to a specified logical color that the given device can represent. GetOutlineTextMetrics Retrieves font metric information for TrueType fonts. GetOutputCharWidth Retrieves the widths of individual characters in a consecutive group of characters from the current font using the output device context. GetOutputTabbedTextExtent Computes the width and height of a character string on the output device context. GetOutputTextExtent Computes the width and height of a line of text on the output device context using the current font to determine the dimensions. GetOutputTextMetrics Retrieves the metrics for the current font from the output device context. GetPath Retrieves the coordinates defining the endpoints of lines and the control points of curves found in the path that is selected into the device context. GetPixel Retrieves the RGB color value of the pixel at the specified point. GetPolyFillMode Retrieves the current polygon-filling mode. GetROP2 Retrieves the current drawing mode. GetSafeHdc Returns m_hDC, the output device context. GetStretchBltMode Retrieves the current bitmap-stretching mode. GetTabbedTextExtent Computes the width and height of a character string on the attribute device context. GetTextAlign Retrieves the text-alignment flags. GetTextCharacterExtra Retrieves the current setting for the amount of intercharacter spacing. GetTextColor Retrieves the current text color. GetTextExtent Computes the width and height of a line of text on the attribute device context using the current font to determine the dimensions. GetTextExtentExPointI Retrieves the number of characters in a specified string that will fit within a specified space and fills an array with the text extent for each of those characters. GetTextExtentPointI Retrieves the width and height of the specified array of glyph indices. GetTextFace Copies the typeface name of the current font into a buffer as a null-terminated string. GetTextMetrics Retrieves the metrics for the current font from the attribute device context. GetViewportExt Retrieves the x- and y-extents of the viewport. GetViewportOrg Retrieves the x- and y-coordinates of the viewport origin. GetWindow Returns the window associated with the display device context. GetWindowExt Retrieves the x- and y-extents of the associated window. GetWindowOrg Retrieves the x- and y-coordinates of the origin of the associated window. GetWorldTransform Retrieves the current world-space to page-space transformation. GradientFill Fills rectangle and triangle structures with a gradating color. GrayString Draws dimmed (grayed) text at the given location. HIMETRICtoDP Converts HIMETRIC units into device units. HIMETRICtoLP Converts HIMETRIC units into logical units. IntersectClipRect Creates a new clipping region by forming the intersection of the current region and a rectangle. InvertRect Inverts the contents of a rectangle. InvertRgn Inverts the colors in a region. IsPrinting Determines whether the device context is being used for printing. LineTo Draws a line from the current position up to, but not including, a point. LPtoDP Converts logical units into device units. LPtoHIMETRIC Converts logical units into HIMETRIC units. MaskBlt Combines the color data for the source and destination bitmaps using the given mask and raster operation. ModifyWorldTransform Changes the world transformation for a device context using the specified mode. MoveTo Moves the current position. OffsetClipRgn Moves the clipping region of the given device. OffsetViewportOrg Modifies the viewport origin relative to the coordinates of the current viewport origin. OffsetWindowOrg Modifies the window origin relative to the coordinates of the current window origin. PaintRgn Fills a region with the selected brush. PatBlt Creates a bit pattern. Pie Draws a pie-shaped wedge. PlayMetaFile Plays the contents of the specified metafile on the given device. The enhanced version of PlayMetaFile displays the picture stored in the given enhanced-format metafile. The metafile can be played any number of times. PlgBlt Performs a bit-block transfer of the bits of color data from the specified rectangle in the source device context to the specified parallelogram in the given device context. PolyBezier Draws one or more Bzier splines. The current position is neither used nor updated. PolyBezierTo Draws one or more Bzier splines, and moves the current position to the ending point of the last Bzier spline. PolyDraw Draws a set of line segments and Bzier splines. This function updates the current position. Polygon Draws a polygon consisting of two or more points (vertices) connected by lines. Polyline Draws a set of line segments connecting the specified points. PolylineTo Draws one or more straight lines and moves the current position to the ending point of the last line. PolyPolygon Creates two or more polygons that are filled using the current polygon-filling mode. The polygons may be disjoint or they may overlap. PolyPolyline Draws multiple series of connected line segments. The current position is neither used nor updated by this function. PtVisible Specifies whether the given point is within the clipping region. RealizePalette Maps palette entries in the current logical palette to the system palette. Rectangle Draws a rectangle using the current pen and fills it using the current brush. RectVisible Determines whether any part of the given rectangle lies within the clipping region. ReleaseAttribDC Releases m_hAttribDC, the attribute device context. ReleaseOutputDC Releases m_hDC, the output device context. ResetDC Updates the m_hAttribDC device context. RestoreDC Restores the device context to a previous state saved with SaveDC. RoundRect Draws a rectangle with rounded corners using the current pen and filled using the current brush. SaveDC Saves the current state of the device context. ScaleViewportExt Modifies the viewport extent relative to the current values. ScaleWindowExt Modifies the window extents relative to the current values. ScrollDC Scrolls a rectangle of bits horizontally and vertically. SelectClipPath Selects the current path as a clipping region for the device context, combining the new region with any existing clipping region by using the specified mode. SelectClipRgn Combines the given region with the current clipping region by using the specified mode. SelectObject Selects a GDI drawing object such as a pen. SelectPalette Selects the logical palette. SelectStockObject Selects one of the predefined stock pens, brushes, or fonts provided by Windows. SetAbortProc Sets a programmer-supplied callback function that Windows calls if a print job must be aborted. SetArcDirection Sets the drawing direction to be used for arc and rectangle functions. SetAttribDC Sets m_hAttribDC, the attribute device context. SetBkColor Sets the current background color. SetBkMode Sets the background mode. SetBoundsRect Controls the accumulation of bounding-rectangle information for the specified device context. SetBrushOrg Specifies the origin for the next brush selected into a device context. SetColorAdjustment Sets the color adjustment values for the device context using the specified values. SetDCBrushColor Sets the current brush color. SetDCPenColor Sets the current pen color. SetGraphicsMode Sets the current graphics mode for the specified device context. SetLayout Changes the layout of a device context (DC). SetMapMode Sets the current mapping mode. SetMapperFlags Alters the algorithm that the font mapper uses when it maps logical fonts to physical fonts. SetMiterLimit Sets the limit for the length of miter joins for the device context. SetOutputDC Sets m_hDC, the output device context. SetPixel Sets the pixel at the specified point to the closest approximation of the specified color. SetPixelV Sets the pixel at the specified coordinates to the closest approximation of the specified color. SetPixelV is faster than SetPixel because it does not need to return the color value of the point actually painted. SetPolyFillMode Sets the polygon-filling mode. SetROP2 Sets the current drawing mode. SetStretchBltMode Sets the bitmap-stretching mode. SetTextAlign Sets the text-alignment flags. SetTextCharacterExtra Sets the amount of intercharacter spacing. SetTextColor Sets the text color. SetTextJustification Adds space to the break characters in a string. SetViewportExt Sets the x- and y-extents of the viewport. SetViewportOrg Sets the viewport origin. SetWindowExt Sets the x- and y-extents of the associated window. SetWindowOrg Sets the window origin of the device context. SetWorldTransform Sets the current world-space to page-space transformation. StartDoc Informs the device driver that a new print job is starting. StartPage Informs the device driver that a new page is starting. StretchBlt Moves a bitmap from a source rectangle and device into a destination rectangle, stretching or compressing the bitmap if necessary to fit the dimensions of the destination rectangle. StrokeAndFillPath Closes any open figures in a path, strikes the outline of the path by using the current pen, and fills its interior by using the current brush. StrokePath Renders the specified path by using the current pen. TabbedTextOut Writes a character string at a specified location, expanding tabs to the values specified in an array of tab-stop positions. TextOut Writes a character string at a specified location using the currently selected font. TransparentBlt Transfers a bit-block of color data from the specified source device context into a destination device context, rendering a specified color transparent in the transfer. UpdateColors Updates the client area of the device context by matching the current colors in the client area to the system palette on a pixel-by-pixel basis. WidenPath Redefines the current path as the area that would be painted if the path were stroked using the pen currently selected into the device context. Step 1 − Let us look into a simple example by creating a new MFC based single document project with MFCGDIDemo name. Step 2 − Once the project is created, go the Solution Explorer and double click on the MFCGDIDemoView.cpp file under the Source Files folder. Step 3 − Draw the line as shown below in CMFCGDIDemoView::OnDraw() method. void CMFCGDIDemoView::OnDraw(CDC* pDC) { pDC->MoveTo(95, 125); pDC->LineTo(230, 125); CMFCGDIDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } Step 4 − Run this application. You will see the following output. Step 5 − The CDC::MoveTo() method is used to set the starting position of a line. When using LineTo(), the program starts from the MoveTo() point to the LineTo() end. After LineTo() when you do not call MoveTo(), and call again LineTo() with other point value, the program will draw a line from the previous LineTo() to the new LineTo() point. Step 6 − To draw different lines, you can use this property as shown in the following code. void CMFCGDIDemoView::OnDraw(CDC* pDC) { pDC->MoveTo(95, 125); pDC->LineTo(230, 125); pDC->LineTo(230, 225); pDC->LineTo(95, 325); CMFCGDIDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } Step 7 − Run this application. You will see the following output. A polyline is a series of connected lines. The lines are stored in an array of POINT or CPoint values. To draw a polyline, you use the CDC::Polyline() method. To draw a polyline, at least two points are required. If you define more than two points, each line after the first would be drawn from the previous point to the next point until all points have been included. Step 1 − Let us look into a simple example. void CMFCGDIDemoView::OnDraw(CDC* pDC) { CPoint Pt[7]; Pt[0] = CPoint(20, 150); Pt[1] = CPoint(180, 150); Pt[2] = CPoint(180, 20); pDC−Polyline(Pt, 3); CMFCGDIDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } Step 2 − When you run this application, you will see the following output. A rectangle is a geometric figure made of four sides that compose four right angles. Like the line, to draw a rectangle, you must define where it starts and where it ends. To draw a rectangle, you can use the CDC::Rectangle() method. Step 1 − Let us look into a simple example. void CMFCGDIDemoView::OnDraw(CDC* pDC) { pDC->Rectangle(15, 15, 250, 160); CMFCGDIDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } Step 2 − When you run this application, you will see the following output. A square is a geometric figure made of four sides that compose four right angles, but each side must be equal in length. Let us look into a simple example. void CMFCGDIDemoView::OnDraw(CDC* pDC) { pDC->Rectangle(15, 15, 250, 250); CMFCGDIDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } When you run this application, you will see the following output. A pie is a fraction of an ellipse delimited by two lines that span from the center of the ellipse to one side each. To draw a pie, you can use the CDC::Pie() method as shown below − BOOL Pie(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4); The (x1, y1) point determines the upper-left corner of the rectangle in which the ellipse that represents the pie fits. The (x2, y2) point is the bottom-right corner of the rectangle. The (x1, y1) point determines the upper-left corner of the rectangle in which the ellipse that represents the pie fits. The (x2, y2) point is the bottom-right corner of the rectangle. The (x3, y3) point specifies the starting corner of the pie in a default counterclockwise direction. The (x3, y3) point specifies the starting corner of the pie in a default counterclockwise direction. The (x4, y4) point species the end point of the pie. The (x4, y4) point species the end point of the pie. Let us look into a simple example. void CMFCGDIDemoView::OnDraw(CDC* pDC) { pDC->Pie(40, 20, 226, 144, 155, 32, 202, 115); CMFCGDIDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } Step 2 − When you run this application, you will see the following output. An arc is a portion or segment of an ellipse, meaning an arc is a non-complete ellipse. To draw an arc, you can use the CDC::Arc() method. BOOL Arc(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4); The CDC class is equipped with the SetArcDirection() method. Here is the syntax − int SetArcDirection(int nArcDirection) AD_CLOCKWISE The figure is drawn clockwise AD_COUNTERCLOCKWISE The figure is drawn counterclockwise Step 1 − Let us look into a simple example. void CMFCGDIDemoView::OnDraw(CDC* pDC) { pDC->SetArcDirection(AD_COUNTERCLOCKWISE); pDC->Arc(20, 20, 226, 144, 202, 115, 105, 32); CMFCGDIDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } Step 2 − When you run this application, you will see the following output. The arcs we have drawn so far are considered open figures because they are made of a line that has a beginning and an end (unlike a circle or a rectangle that do not). A chord is an arc whose two ends are connected by a straight line. To draw a chord, you can use the CDC::Chord() method. BOOL Chord(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4); Let us look into a simple example. void CMFCGDIDemoView::OnDraw(CDC* pDC) { pDC->SetArcDirection(AD_CLOCKWISE); pDC->Chord(20, 20, 226, 144, 202, 115, 105, 32); CMFCGDIDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } When you run the above application, you will see the following output. The arc direction in this example is set clockwise. The color is one the most fundamental objects that enhances the aesthetic appearance of an object. The color is a non-spatial object that is added to an object to modify some of its visual aspects. The MFC library, combined with the Win32 API, provides various actions you can use to take advantage of the various aspects of colors. The RGB macro behaves like a function and allows you to pass three numeric values separated by a comma. Each value must be between 0 and 255 as shown in the following code. void CMFCGDIDemoView::OnDraw(CDC* pDC) { COLORREF color = RGB(239, 15, 225); } Let us look into a simple example. void CMFCGDIDemoView::OnDraw(CDC* pDC) { COLORREF color = RGB(239, 15, 225); pDC->SetTextColor(color); pDC->TextOut(100, 80, L"MFC GDI Tutorial", 16); CMFCGDIDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } When you run this application, you will see the following output. CFont encapsulates a Windows graphics device interface (GDI) font and provides member functions for manipulating the font. To use a CFont object, construct a CFont object and attach a Windows font to it, and then use the object's member functions to manipulate the font. CreateFont Initializes a CFont with the specified characteristics. CreateFontIndirect Initializes a CFont object with the characteristics given in a LOGFONT structure. CreatePointFont Initializes a CFont with the specified height, measured in tenths of a point, and typeface. CreatePointFontIndirect Same as CreateFontIndirect except that the font height is measured in tenths of a point rather than logical units. FromHandle Returns a pointer to a CFont object when given a Windows HFONT. GetLogFont Fills a LOGFONT with information about the logical font attached to the CFont object. Let us look into a simple example. void CMFCGDIDemoView::OnDraw(CDC* pDC) { CFont font; font.CreatePointFont(920, L"Garamond"); CFont *pFont = pDC->SelectObject(&font); COLORREF color = RGB(239, 15, 225); pDC->SetTextColor(color); pDC->TextOut(100, 80, L"MFC GDI Tutorial", 16); pDC->SelectObject(pFont); font.DeleteObject(); CMFCGDIDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } When you run the above application, you will see the following output. A pen is a tool used to draw lines and curves on a device context. In the graphics programming, a pen is also used to draw the borders of a geometric closed shape such as a rectangle or a polygon. Microsoft Windows considers two types of pens — cosmetic and geometric. A pen is referred to as cosmetic when it can be used to draw only simple lines of a fixed width, less than or equal to 1 pixel. A pen is geometric when it can assume different widths and various ends. MFC provides a class CPen which encapsulates a Windows graphics device interface (GDI) pen. CreatePen Creates a logical cosmetic or geometric pen with the specified style, width, and brush attributes, and attaches it to the CPen object. CreatePenIndirect Creates a pen with the style, width, and color given in a LOGPEN structure, and attaches it to the CPen object. FromHandle Returns a pointer to a CPen object when given a Windows HPEN. GetExtLogPen Gets an EXTLOGPEN underlying structure. GetLogPen Gets a LOGPEN underlying structure. PS_SOLID A continuous solid line. PS_DASH A continuous line with dashed interruptions. PS_DOT A line with a dot interruption at every other pixel. PS_DASHDOT A combination of alternating dashed and dotted points. PS_DASHDOTDOT A combination of dash and double dotted interruptions. PS_NULL No visible line. PS_INSIDEFRAME A line drawn just inside of the border of a closed shape. Let us look into a simple example. void CMFCGDIDemoView::OnDraw(CDC* pDC) { CPen pen; pen.CreatePen(PS_DASHDOTDOT, 1, RGB(160, 75, 90)); pDC->SelectObject(&pen); pDC->Rectangle(25, 35, 250, 125); CMFCGDIDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } When you run the above application, you will see the following output. A brush is a drawing tool used to fill out closed shaped or the interior of lines. A brush behaves like picking up a bucket of paint and pouring it somewhere. MFC provides a class CBrush which encapsulates a Windows graphics device interface (GDI) brush. CreateBrushIndirect Initializes a brush with the style, color, and pattern specified in a LOGBRUSH structure. CreateDIBPatternBrush Initializes a brush with a pattern specified by a device-independent bitmap (DIB). CreateHatchBrush Initializes a brush with the specified hatched pattern and color. CreatePatternBrush Initializes a brush with a pattern specified by a bitmap. CreateSolidBrush Initializes a brush with the specified solid color. CreateSysColorBrush Creates a brush that is the default system color. FromHandle Returns a pointer to a CBrush object when given a handle to a Windows HBRUSH object. GetLogBrush Gets a LOGBRUSH structure. Let us look into a simple example. void CMFCGDIDemoView::OnDraw(CDC* pDC) { CBrush brush(RGB(100, 150, 200)); CBrush *pBrush = pDC->SelectObject(&brush); pDC->Rectangle(25, 35, 250, 125); pDC->SelectObject(pBrush); CMFCGDIDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } When you run this application, you will see the following output. A library is a group of functions, classes, or other resources that can be made available to programs that need already implemented entities without the need to know how these functions, classes, or resources were created or how they function. A library makes it easy for a programmer to use functions, classes, and resources etc. created by another person or company and trust that this external source is reliable and efficient. Some unique features related to libraries are − A library is created and functions like a normal regular program, using functions or other resources and communicating with other programs. A library is created and functions like a normal regular program, using functions or other resources and communicating with other programs. To implement its functionality, a library contains functions that other programs would need to complete their functionality. To implement its functionality, a library contains functions that other programs would need to complete their functionality. At the same time, a library may use some functions that other programs would not need. At the same time, a library may use some functions that other programs would not need. The program that uses the library, are also called the clients of the library. The program that uses the library, are also called the clients of the library. There are two types of functions you will create or include in your libraries − An internal function is one used only by the library itself and clients of the library will not need access to these functions. An internal function is one used only by the library itself and clients of the library will not need access to these functions. External functions are those that can be accessed by the clients of the library. External functions are those that can be accessed by the clients of the library. There are two broad categories of libraries you will deal with in your programs − Static libraries Dynamic libraries A static library is a file that contains functions, classes, or resources that an external program can use to complement its functionality. To use a library, the programmer has to create a link to it. The project can be a console application, a Win32 or an MFC application. The library file has the lib extension. Step 1 − Let us look into a simple example of static library by creating a new Win32 Project. Step 2 − On Application Wizard dialog box, choose the Static Library option. Step 3 − Click Finish to continue. Step 4 − Right-click on the project in solution explorer and add a header file from Add → New Item...menu option. Step 5 − Enter Calculator.h in the Name field and click Add. Add the following code in the header file − #pragma once #ifndef _CALCULATOR_H_ #define _CALCULATOR_H_ double Min(const double *Numbers, const int Count); double Max(const double *Numbers, const int Count); double Sum(const double *Numbers, const int Count); double Average(const double *Numbers, const int Count); long GreatestCommonDivisor(long Nbr1, long Nbr2); #endif // _CALCULATOR_H_ Step 6 − Add a source (*.cpp) file in the project. Step 7 − Enter Calculator.cpp in the Name field and click Add. Step 8 − Add the following code in the *.cpp file − #include "StdAfx.h" #include "Calculator.h" double Min(const double *Nbr, const int Total) { double Minimum = Nbr[0]; for (int i = 0; i < Total; i++) if (Minimum > Nbr[i]) Minimum = Nbr[i]; return Minimum; } double Max(const double *Nbr, const int Total) { double Maximum = Nbr[0]; for (int i = 0; i < Total; i++) if (Maximum < Nbr[i]) Maximum = Nbr[i]; return Maximum; } double Sum(const double *Nbr, const int Total) { double S = 0; for (int i = 0; i < Total; i++) S += Nbr[i]; return S; } double Average(const double *Nbr, const int Total) { double avg, S = 0; for (int i = 0; i < Total; i++) S += Nbr[i]; avg = S / Total; return avg; } long GreatestCommonDivisor(long Nbr1, long Nbr2) { while (true) { Nbr1 = Nbr1 % Nbr2; if (Nbr1 == 0) return Nbr2; Nbr2 = Nbr2 % Nbr1; if (Nbr2 == 0) return Nbr1; } } Step 9 − Build this library from the main menu, by clicking Build → Build MFCLib. Step 10 − When library is built successfully, it will display the above message. Step 11 − To use these functions from the library, let us add another MFC dialog application based from File → New → Project. Step 12 − Go to the MFCLib\Debug folder and copy the header file and *.lib files to the MFCLibTest project as shown in the following snapshot. Step 13 − To add the library to the current project, on the main menu, click Project → Add Existing Item and select MFCLib.lib. Step 14 − Design your dialog box as shown in the following snapshot. Step 15 − Add value variable for both edit controls of value type double. Step 16 − Add value variable for Static text control, which is at the end of the dialog box. Step 17 − Add the event handler for Calculate button. To add functionality from the library, we need to include the header file in CMFCLibTestDlg.cpp file. #include "stdafx.h" #include "MFCLibTest.h" #include "MFCLibTestDlg.h" #include "afxdialogex.h" #include "Calculator.h" Step 18 − Here is the implementation of button event handler. void CMFCLibTestDlg::OnBnClickedButtonCal() { // TODO: Add your control notification handler code here UpdateData(TRUE); CString strTemp; double numbers[2]; numbers[0] = m_Num1; numbers[1] = m_Num2; strTemp.Format(L"%.2f", Max(numbers,2)); m_strText.Append(L"Max is:\t" + strTemp); strTemp.Format(L"%.2f", Min(numbers, 2)); m_strText.Append(L"\nMin is:\t" + strTemp); strTemp.Format(L"%.2f", Sum(numbers, 2)); m_strText.Append(L"\nSum is:\t" + strTemp); strTemp.Format(L"%.2f", Average(numbers, 2)); m_strText.Append(L"\nAverage is:\t" + strTemp); strTemp.Format(L"%d", GreatestCommonDivisor(m_Num1, m_Num2)); m_strText.Append(L"\nGDC is:\t" + strTemp); UpdateData(FALSE); } Step 19 − When the above code is compiled and executed, you will see the following output. Step 20 − Enter two values in the edit field and click Calculate. You will now see the result after calculating from the library. A Win32 DLL is a library that can be made available to programs that run on a Microsoft Windows computer. As a normal library, it is made of functions and/or other resources grouped in a file. The DLL abbreviation stands for Dynamic Link Library. This means that, as opposed to a static library, a DLL allows the programmer to decide on when and how other applications will be linked to this type of library. For example, a DLL allows difference applications to use its library as they see fit and as necessary. In fact, applications created on different programming environments can use functions or resources stored in one particular DLL. For this reason, an application dynamically links to the library. Step 1 − Let us look into a simple example by creating a new Win32 Project. Step 2 − In the Application Type section, click the DLL radio button. Step 3 − Click Finish to continue. Step 4 − Add the following functions in MFCDynamicLib.cpp file and expose its definitions by using − extern "C" _declspec(dllexport) Step 5 − Use the _declspec(dllexport) modifier for each function that will be accessed outside the DLL. // MFCDynamicLib.cpp : Defines the exported functions for the DLL application.// #include "stdafx.h" extern "C" _declspec(dllexport) double Min(const double *Numbers, const int Count); extern "C" _declspec(dllexport) double Max(const double *Numbers, const int Count); extern "C" _declspec(dllexport) double Sum(const double *Numbers, const int Count); extern "C" _declspec(dllexport) double Average(const double *Numbers, const int Count); extern "C" _declspec(dllexport) long GreatestCommonDivisor(long Nbr1, long Nbr2); double Min(const double *Nbr, const int Total) { double Minimum = Nbr[0]; for (int i = 0; i < Total; i++) if (Minimum > Nbr[i]) Minimum = Nbr[i]; return Minimum; } double Max(const double *Nbr, const int Total) { double Maximum = Nbr[0]; for (int i = 0; i < Total; i++) if (Maximum < Nbr[i]) Maximum = Nbr[i]; return Maximum; } double Sum(const double *Nbr, const int Total) { double S = 0; for (int i = 0; i < Total; i++) S += Nbr[i]; return S; } double Average(const double *Nbr, const int Total){ double avg, S = 0; for (int i = 0; i < Total; i++) S += Nbr[i]; avg = S / Total; return avg; } long GreatestCommonDivisor(long Nbr1, long Nbr2) { while (true) { Nbr1 = Nbr1 % Nbr2; if (Nbr1 == 0) return Nbr2; Nbr2 = Nbr2 % Nbr1; if (Nbr2 == 0) return Nbr1; } } Step 6 − To create the DLL, on the main menu, click Build > Build MFCDynamicLib from the main menu. Step 7 − Once the DLL is successfully created, you will see amessage display in output window. Step 8 − Open Windows Explorer and then the Debug folder of the current project. Step 9 − Notice that a file with dll extension and another file with lib extension has been created. Step 10 − To test this file with dll extension, we need to create a new MFC dialog based application from File → New → Project. Step 11 − Go to the MFCDynamicLib\Debug folder and copy the *.dll and *.lib files to the MFCLibTest project as shown in the following snapshot. Step 12 − To add the DLL to the current project, on the main menu, click Project → Add Existing Item and then, select MFCDynamicLib.lib file. Step 13 − Design your dialog box as shown in the following snapshot. Step 14 − Add value variable for both edit controls of value type double. Step 15 − Add value variable for Static text control, which is at the end of the dialog box. Step 16 − Add the event handler for Calculate button. Step 17 − In the project that is using the DLL, each function that will be accessed must be declared using the _declspec(dllimport) modifier. Step 18 − Add the following function declaration in MFCLibTestDlg.cpp file. extern "C" _declspec(dllimport) double Min(const double *Numbers, const int Count); extern "C" _declspec(dllimport) double Max(const double *Numbers, const int Count); extern "C" _declspec(dllimport) double Sum(const double *Numbers, const int Count); extern "C" _declspec(dllimport) double Average(const double *Numbers, const int Count); extern "C" _declspec(dllimport) long GreatestCommonDivisor(long Nbr1, long Nbr2); Step 19 − Here is the implementation of button event handler. void CMFCLibTestDlg::OnBnClickedButtonCal() { // TODO: Add your control notification handler code here UpdateData(TRUE); CString strTemp; double numbers[2]; numbers[0] = m_Num1; numbers[1] = m_Num2; strTemp.Format(L"%.2f", Max(numbers,2)); m_strText.Append(L"Max is:\t" + strTemp); strTemp.Format(L"%.2f", Min(numbers, 2)); m_strText.Append(L"\nMin is:\t" + strTemp); strTemp.Format(L"%.2f", Sum(numbers, 2)); m_strText.Append(L"\nSum is:\t" + strTemp); strTemp.Format(L"%.2f", Average(numbers, 2)); m_strText.Append(L"\nAverage is:\t" + strTemp); strTemp.Format(L"%d", GreatestCommonDivisor(m_Num1, m_Num2)); m_strText.Append(L"\nGDC is:\t" + strTemp); UpdateData(FALSE); } Step 20 − When the above code is compiled and executed, you will see the following output. Step 21 − Enter two values in the edit field and click Calculate. You will now see the result after calculating from the DLL.
[ { "code": null, "e": 2494, "s": 2201, "text": "The Microsoft Foundation Class (MFC) library provides a set of functions, constants, data types, and classes to simplify creating applications for the Microsoft Windows operating systems. In this tutorial, you will learn all about how to start and create windows based applications using MFC." }, { "code": null, "e": 2540, "s": 2494, "text": "We have assumed that you know the following −" }, { "code": null, "e": 2580, "s": 2540, "text": "A little about programming for Windows." }, { "code": null, "e": 2614, "s": 2580, "text": "The basics of programming in C++." }, { "code": null, "e": 2674, "s": 2614, "text": "Understand the fundamentals of object-oriented programming." }, { "code": null, "e": 2857, "s": 2674, "text": "The Microsoft Foundation Class Library (MFC) is an \"application framework\" for programming in Microsoft Windows. MFC provides much of the code, which are required for the following −" }, { "code": null, "e": 2875, "s": 2857, "text": "Managing Windows." }, { "code": null, "e": 2899, "s": 2875, "text": "Menus and dialog boxes." }, { "code": null, "e": 2930, "s": 2899, "text": "Performing basic input/output." }, { "code": null, "e": 2972, "s": 2930, "text": "Storing collections of data objects, etc." }, { "code": null, "e": 3133, "s": 2972, "text": "You can easily extend or override the basic functionality the MFC framework in you C++ applications by adding your application-specific code into MFC framework." }, { "code": null, "e": 3228, "s": 3133, "text": "The MFC framework provides a set of reusable classes designed to simplify Windows programming." }, { "code": null, "e": 3323, "s": 3228, "text": "The MFC framework provides a set of reusable classes designed to simplify Windows programming." }, { "code": null, "e": 3447, "s": 3323, "text": "MFC provides classes for many basic objects, such as strings, files, and collections that are used in everyday programming." }, { "code": null, "e": 3571, "s": 3447, "text": "MFC provides classes for many basic objects, such as strings, files, and collections that are used in everyday programming." }, { "code": null, "e": 3689, "s": 3571, "text": "It also provides classes for common Windows APIs and data structures, such as windows, controls, and device contexts." }, { "code": null, "e": 3807, "s": 3689, "text": "It also provides classes for common Windows APIs and data structures, such as windows, controls, and device contexts." }, { "code": null, "e": 3928, "s": 3807, "text": "The framework also provides a solid foundation for more advanced features, such as ActiveX and document view processing." }, { "code": null, "e": 4049, "s": 3928, "text": "The framework also provides a solid foundation for more advanced features, such as ActiveX and document view processing." }, { "code": null, "e": 4176, "s": 4049, "text": "In addition, MFC provides an application framework, including the classes that make up the application architecture hierarchy." }, { "code": null, "e": 4303, "s": 4176, "text": "In addition, MFC provides an application framework, including the classes that make up the application architecture hierarchy." }, { "code": null, "e": 4457, "s": 4303, "text": "The MFC framework is a powerful approach that lets you build upon the work of expert programmers for Windows. MFC framework has the following advantages." }, { "code": null, "e": 4487, "s": 4457, "text": "It shortens development time." }, { "code": null, "e": 4517, "s": 4487, "text": "It shortens development time." }, { "code": null, "e": 4546, "s": 4517, "text": "It makes code more portable." }, { "code": null, "e": 4575, "s": 4546, "text": "It makes code more portable." }, { "code": null, "e": 4665, "s": 4575, "text": "It also provides tremendous support without reducing programming freedom and flexibility." }, { "code": null, "e": 4755, "s": 4665, "text": "It also provides tremendous support without reducing programming freedom and flexibility." }, { "code": null, "e": 4839, "s": 4755, "text": "It gives easy access to \"hard to program\" user-interface elements and technologies." }, { "code": null, "e": 4923, "s": 4839, "text": "It gives easy access to \"hard to program\" user-interface elements and technologies." }, { "code": null, "e": 5081, "s": 4923, "text": "MFC simplifies database programming through Data Access Objects (DAO) and Open Database Connectivity (ODBC), and network programming through Windows Sockets." }, { "code": null, "e": 5239, "s": 5081, "text": "MFC simplifies database programming through Data Access Objects (DAO) and Open Database Connectivity (ODBC), and network programming through Windows Sockets." }, { "code": null, "e": 5564, "s": 5239, "text": "Microsoft Visual C++ is a programming environment used to create applications for the Microsoft Windows operating systems. To use MFC framework in your C++ application, you must have installed either Microsoft Visual C++ or Microsoft Visual Studio. Microsoft Visual Studio also contains the Microsoft Visual C++ environment." }, { "code": null, "e": 5753, "s": 5564, "text": "Microsoft provides a free version of visual studio which also contains SQL Server and it can be downloaded from https://www.visualstudio.com/en-us/downloads/downloadvisual- studio-vs.aspx." }, { "code": null, "e": 5791, "s": 5753, "text": "Following are the installation steps." }, { "code": null, "e": 5897, "s": 5791, "text": "Step 1 − Once Visual Studio is downloaded, run the installer. The following dialog box will be displayed." }, { "code": null, "e": 5955, "s": 5897, "text": "Step 2 − Click Install to start the installation process." }, { "code": null, "e": 6049, "s": 5955, "text": "Step 3 − Once Visual Studio is installed successfully, you will see the following dialog box." }, { "code": null, "e": 6119, "s": 6049, "text": "Step 4 − Close this dialog box and restart your computer if required." }, { "code": null, "e": 6285, "s": 6119, "text": "Step 5 − Open Visual studio from the Start menu, which will open the following dialog box. It will take some time for preparation, while starting for the first time." }, { "code": null, "e": 6347, "s": 6285, "text": "Step 6 − Next, you will see the main window of Visual Studio." }, { "code": null, "e": 6401, "s": 6347, "text": "Step 7 − You are now ready to start your application." }, { "code": null, "e": 6791, "s": 6401, "text": "In this chapter, we will be covering the different types of VC++ projects. Visual Studio includes several kinds of Visual C++ project templates. These templates help to create the basic program structure, menus, toolbars, icons, references, and include statements that are appropriate for the kind of project you want to create. Following are some of the salient features of the templates." }, { "code": null, "e": 6905, "s": 6791, "text": "It provides wizards for many of these project templates and helps you customize your projects as you create them." }, { "code": null, "e": 7019, "s": 6905, "text": "It provides wizards for many of these project templates and helps you customize your projects as you create them." }, { "code": null, "e": 7087, "s": 7019, "text": "Once the project is created, you can build and run the application." }, { "code": null, "e": 7155, "s": 7087, "text": "Once the project is created, you can build and run the application." }, { "code": null, "e": 7273, "s": 7155, "text": "You don't have to use a template to create a project, but in most cases it's more efficient to use project templates." }, { "code": null, "e": 7391, "s": 7273, "text": "You don't have to use a template to create a project, but in most cases it's more efficient to use project templates." }, { "code": null, "e": 7494, "s": 7391, "text": "It's easier to modify the provided project files and structure than it is to create them from scratch." }, { "code": null, "e": 7597, "s": 7494, "text": "It's easier to modify the provided project files and structure than it is to create them from scratch." }, { "code": null, "e": 7650, "s": 7597, "text": "In MFC, you can use the following project templates." }, { "code": null, "e": 7666, "s": 7650, "text": "MFC Application" }, { "code": null, "e": 7872, "s": 7666, "text": "An MFC application is an executable application for Windows that is based on the Microsoft Foundation Class (MFC) Library. The easiest way to create an MFC application is to use the MFC Application Wizard." }, { "code": null, "e": 7892, "s": 7872, "text": "MFC ActiveX Control" }, { "code": null, "e": 8118, "s": 7892, "text": "ActiveX control programs are modular programs designed to give a specific type of functionality to a parent application. For example, you can create a control such as a button for use in a dialog, or toolbar or on a Web page." }, { "code": null, "e": 8126, "s": 8118, "text": "MFC DLL" }, { "code": null, "e": 8330, "s": 8126, "text": "An MFC DLL is a binary file that acts as a shared library of functions that can be used simultaneously by multiple applications. The easiest way to create an MFC DLL project is to use the MFC DLL Wizard." }, { "code": null, "e": 8418, "s": 8330, "text": "Following are some General templates which can also be used to create MFC application −" }, { "code": null, "e": 8432, "s": 8418, "text": "Empty Project" }, { "code": null, "e": 8601, "s": 8432, "text": "Projects are the logical containers for everything that's needed to build your application. You can then add more new or existing projects to the solution if necessary." }, { "code": null, "e": 8615, "s": 8601, "text": "Custom Wizard" }, { "code": null, "e": 8779, "s": 8615, "text": "The Visual C++ Custom Wizard is the tool to use when you need to create a new custom wizard. The easiest way to create a custom wizard is to use the Custom Wizard." }, { "code": null, "e": 8962, "s": 8779, "text": "In this chapter, we will look at a working MFC example. To create an MFC application, you can use wizards to customize your projects. You can also create an application from scratch." }, { "code": null, "e": 9058, "s": 8962, "text": "Following are the steps to create a project using project templates available in Visual Studio." }, { "code": null, "e": 9142, "s": 9058, "text": "Step 1 − Open the Visual studio and click on the File → New → Project menu option." }, { "code": null, "e": 9209, "s": 9142, "text": "Step 2 − You can now see that the New Project dialog box is open." }, { "code": null, "e": 9275, "s": 9209, "text": "Step 3 − From the left pane, select Templates → Visual C++ → MFC " }, { "code": null, "e": 9329, "s": 9275, "text": "Step 4 − In the middle pane, select MFC Application." }, { "code": null, "e": 9450, "s": 9329, "text": "Step 5 − Enter the project name ‘MFCDemo’ in the Name field and click OK to continue. You will see the following dialog." }, { "code": null, "e": 9471, "s": 9450, "text": "Step 6 − Click Next." }, { "code": null, "e": 9561, "s": 9471, "text": "Step 7 − Select the options which are shown in the dialog box given above and click Next." }, { "code": null, "e": 9615, "s": 9561, "text": "Step 8 − Uncheck all options and click Finish button." }, { "code": null, "e": 9709, "s": 9615, "text": "You can now see that the MFC wizard creates this Dialog Box and the project files by default." }, { "code": null, "e": 9775, "s": 9709, "text": "Step 9 − Run this application, you will see the following output." }, { "code": null, "e": 9898, "s": 9775, "text": "You can also create an MFC application from scratch. To create an MFC application, you need to follow the following Steps." }, { "code": null, "e": 9981, "s": 9898, "text": "Step 1 − Open the Visual studio and click on the File → New → Project menu option." }, { "code": null, "e": 10034, "s": 9981, "text": "Step 2 − You can now see the New Project dialog box." }, { "code": null, "e": 10104, "s": 10034, "text": "Step 3 − From the left pane, select Templates → Visual C++ → General." }, { "code": null, "e": 10146, "s": 10104, "text": "Step 4 − In the middle pane, select Empty" }, { "code": null, "e": 10286, "s": 10146, "text": "Step 5 − Enter project name ‘MFCDemoFromScratch’ in the Name field and click OK to continue. You will see that an empty project is created." }, { "code": null, "e": 10372, "s": 10286, "text": "Step 6 − To make it an MFC project, right-click on the project and select Properties." }, { "code": null, "e": 10444, "s": 10372, "text": "Step 7 − In the left section, click Configuration Properties → General." }, { "code": null, "e": 10535, "s": 10444, "text": "Step 8 − Select the Use MFC in Shared DLL option in Project Defaults section and click OK." }, { "code": null, "e": 10662, "s": 10535, "text": "Step 9 − As it is an empty project now; we need to add a C++ file. So, right-click on the project and select Add → New Item..." }, { "code": null, "e": 10774, "s": 10662, "text": "Step 10 − Select C++ File (.cpp) in the middle pane and enter file name in the Name field and click Add button." }, { "code": null, "e": 10855, "s": 10774, "text": "Step 11 − You can now see the main.cpp file added under the Source Files folder." }, { "code": null, "e": 10909, "s": 10855, "text": "Step 12 − Let us add the following code in this file." }, { "code": null, "e": 11140, "s": 10909, "text": "#include <iostream> \nusing namespace std; \n\nvoid main() { \n cout << \"***************************************\\n\"; \n cout << \"MFC Application Tutorial\"; \n cout << \"\\n***************************************\"; \n getchar(); \n}" }, { "code": null, "e": 11227, "s": 11140, "text": "Step 13 − When you run this application, you will see the following output on console." }, { "code": null, "e": 11335, "s": 11227, "text": "*************************************** \nMFC Application Tutorial \n***************************************\n" }, { "code": null, "e": 11545, "s": 11335, "text": "In this chapter, we will be covering the fundamentals of Windows. To create a program, also called an application, you derive a class from the MFC's CWinApp. CWinApp stands for Class for a Windows Application." }, { "code": null, "e": 11612, "s": 11545, "text": "Let us look into a simple example by creating a new Win32 project." }, { "code": null, "e": 11695, "s": 11612, "text": "Step 1 − Open the Visual studio and click on the File → New → Project menu option." }, { "code": null, "e": 11748, "s": 11695, "text": "Step 2 − You can now see the New Project dialog box." }, { "code": null, "e": 11816, "s": 11748, "text": "Step 3 − From the left pane, select Templates → Visual C++ → Win32." }, { "code": null, "e": 11867, "s": 11816, "text": "Step 4 − In the middle pane, select Win32 Project." }, { "code": null, "e": 11998, "s": 11867, "text": "Step 5 − Enter the project name ‘MFCWindowDemo’ in the Name field and click OK to continue. You will see the following dialog box." }, { "code": null, "e": 12019, "s": 11998, "text": "Step 6 − Click Next." }, { "code": null, "e": 12104, "s": 12019, "text": "Step 7 − Select the options as shown in the dialog box given above and click Finish." }, { "code": null, "e": 12142, "s": 12104, "text": "Step 8 − An empty project is created." }, { "code": null, "e": 12228, "s": 12142, "text": "Step 9 − To make it an MFC project, right-click on the project and select Properties." }, { "code": null, "e": 12301, "s": 12228, "text": "Step 10 − In the left section, click Configuration Properties → General." }, { "code": null, "e": 12393, "s": 12301, "text": "Step 11 − Select the Use MFC in Shared DLL option in Project Defaults section and click OK." }, { "code": null, "e": 12426, "s": 12393, "text": "Step 12 − Add a new source file." }, { "code": null, "e": 12494, "s": 12426, "text": "Step 13 − Right-click on your Project and select Add → New Item..." }, { "code": null, "e": 12553, "s": 12494, "text": "Step 14 − In the Templates section, click C++ File (.cpp)." }, { "code": null, "e": 12602, "s": 12553, "text": "Step 15 − Set the Name as Example and click Add." }, { "code": null, "e": 12642, "s": 12602, "text": "Any application has two main sections −" }, { "code": null, "e": 12648, "s": 12642, "text": "Class" }, { "code": null, "e": 12664, "s": 12648, "text": "Frame or Window" }, { "code": null, "e": 12715, "s": 12664, "text": "Let us create a window using the following steps −" }, { "code": null, "e": 12800, "s": 12715, "text": "Step 1 − To create an application, we need to derive a class from the MFC's CWinApp." }, { "code": null, "e": 12895, "s": 12800, "text": "#include\nclass CExample : public CWinApp {\n BOOL InitInstance() {\n return TRUE;\n }\n};" }, { "code": null, "e": 12972, "s": 12895, "text": "Step 2 − We also need a frame/window to show the content of our application." }, { "code": null, "e": 13192, "s": 12972, "text": "Step 3 − For this, we need to add another class and derive it from the MFC's CFrameWnd class and implement its constructor and a call the Create() method, which will create a frame/window as shown in the following code." }, { "code": null, "e": 13324, "s": 13192, "text": "class CMyFrame : public CFrameWnd {\n public:\n CMyFrame() {\n Create(NULL, _T(\"MFC Application Tutorial\"));\n }\n};" }, { "code": null, "e": 13531, "s": 13324, "text": "Step 4 − As you can see that Create() method needs two parameters, the name of the class, which should be passed as NULL, and the name of the window, which is the string that will be shown on the title bar." }, { "code": null, "e": 13862, "s": 13531, "text": "After creating a window, to let the application use it, you can use a pointer to show the class used to create the window. In this case, the pointer would be CFrameWnd. To use the frame window, assign its pointer to the CWinThread::m_pMainWnd member variable. This is done in the InitInstance() implementation of your application." }, { "code": null, "e": 13935, "s": 13862, "text": "Step 1 − Here is the implementation of InitInstance() in CExample class." }, { "code": null, "e": 14161, "s": 13935, "text": "class CExample : public CWinApp {\n BOOL InitInstance() {\n CMyFrame *Frame = new CMyFrame(); m_pMainWnd = Frame;\n \n Frame->ShowWindow(SW_NORMAL);\n Frame->UpdateWindow();\n \n return TRUE;\n }\n};" }, { "code": null, "e": 14232, "s": 14161, "text": "Step 2 − Following is the complete implementation of Example.cpp file." }, { "code": null, "e": 14635, "s": 14232, "text": "#include <afxwin.h>\n\nclass CMyFrame : public CFrameWnd {\n public:\n CMyFrame() {\n Create(NULL, _T(\"MFC Application Tutorial\"));\n }\n};\n\nclass CExample : public CWinApp {\n BOOL InitInstance() {\n CMyFrame *Frame = new CMyFrame();\n m_pMainWnd = Frame;\n \n Frame->ShowWindow(SW_NORMAL);\n Frame->UpdateWindow();\n \n return TRUE;\n }\n};\n\nCExample theApp;" }, { "code": null, "e": 14712, "s": 14635, "text": "Step 3 − When we run the above application, the following window is created." }, { "code": null, "e": 14867, "s": 14712, "text": "Windows styles are characteristics that control features such as window appearance, borders, minimized or maximized state, or other resizing states, etc. " }, { "code": null, "e": 14877, "s": 14867, "text": "WS_BORDER" }, { "code": null, "e": 14913, "s": 14877, "text": "Creates a window that has a border." }, { "code": null, "e": 14924, "s": 14913, "text": "WS_CAPTION" }, { "code": null, "e": 15036, "s": 14924, "text": "Creates a window that has a title bar (implies the WS_BORDER style). Cannot be used with the WS_DLGFRAME style." }, { "code": null, "e": 15045, "s": 15036, "text": "WS_CHILD" }, { "code": null, "e": 15109, "s": 15045, "text": "Creates a child window. Cannot be used with the WS_POPUP style." }, { "code": null, "e": 15124, "s": 15109, "text": "WS_CHILDWINDOW" }, { "code": null, "e": 15152, "s": 15124, "text": "Same as the WS_CHILD style." }, { "code": null, "e": 15168, "s": 15152, "text": "WS_CLIPCHILDREN" }, { "code": null, "e": 15292, "s": 15168, "text": "Excludes the area occupied by child windows when you draw within the parent window. Used when you create the parent window." }, { "code": null, "e": 15308, "s": 15292, "text": "WS_CLIPSIBLINGS" }, { "code": null, "e": 15770, "s": 15308, "text": "Clips child windows relative to each other; that is, when a particular child window receives a paint message, the WS_CLIPSIBLINGS style clips all other overlapped child windows out of the region of the child window to be updated. (If WS_CLIPSIBLINGS is not given and child windows overlap, when you draw within the client area of a child window, it is possible to draw within the client area of a neighboring child window.) For use with the WS_CHILD style only." }, { "code": null, "e": 15782, "s": 15770, "text": "WS_DISABLED" }, { "code": null, "e": 15827, "s": 15782, "text": "Creates a window that is initially disabled." }, { "code": null, "e": 15839, "s": 15827, "text": "WS_DLGFRAME" }, { "code": null, "e": 15891, "s": 15839, "text": "Creates a window with a double border but no title." }, { "code": null, "e": 15900, "s": 15891, "text": "WS_GROUP" }, { "code": null, "e": 16241, "s": 15900, "text": "Specifies the first control of a group of controls in which the user can move from one control to the next with the arrow keys. All controls defined with the WS_GROUP style FALSE after the first control belong to the same group. The next control with the WS_GROUP style starts the next group (that is, one group ends where the next begins)." }, { "code": null, "e": 16252, "s": 16241, "text": "WS_HSCROLL" }, { "code": null, "e": 16303, "s": 16252, "text": "Creates a window that has a horizontal scroll bar." }, { "code": null, "e": 16313, "s": 16303, "text": "WS_ICONIC" }, { "code": null, "e": 16390, "s": 16313, "text": "Creates a window that is initially minimized. Same as the WS_MINIMIZE style." }, { "code": null, "e": 16402, "s": 16390, "text": "WS_MAXIMIZE" }, { "code": null, "e": 16436, "s": 16402, "text": "Creates a window of maximum size." }, { "code": null, "e": 16451, "s": 16436, "text": "WS_MAXIMIZEBOX" }, { "code": null, "e": 16496, "s": 16451, "text": "Creates a window that has a Maximize button." }, { "code": null, "e": 16508, "s": 16496, "text": "WS_MINIMIZE" }, { "code": null, "e": 16597, "s": 16508, "text": "Creates a window that is initially minimized. For use with the WS_OVERLAPPED style only." }, { "code": null, "e": 16612, "s": 16597, "text": "WS_MINIMIZEBOX" }, { "code": null, "e": 16657, "s": 16612, "text": "Creates a window that has a Minimize button." }, { "code": null, "e": 16671, "s": 16657, "text": "WS_OVERLAPPED" }, { "code": null, "e": 16758, "s": 16671, "text": "Creates an overlapped window. An overlapped window usually has a caption and a border." }, { "code": null, "e": 16779, "s": 16758, "text": "WS_OVERLAPPED WINDOW" }, { "code": null, "e": 16914, "s": 16779, "text": "Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles." }, { "code": null, "e": 16923, "s": 16914, "text": "WS_POPUP" }, { "code": null, "e": 16988, "s": 16923, "text": "Creates a pop-up window. Cannot be used with the WS_CHILD style." }, { "code": null, "e": 17003, "s": 16988, "text": "WS_POPUPWINDOW" }, { "code": null, "e": 17182, "s": 17003, "text": "Creates a pop-up window with the WS_BORDER, WS_POPUP, and WS_SYSMENU styles. The WS_CAPTION style must be combined with the WS_POPUPWINDOW style to make the Control menu visible." }, { "code": null, "e": 17193, "s": 17182, "text": "WS_SIZEBOX" }, { "code": null, "e": 17269, "s": 17193, "text": "Creates a window that has a sizing border. Same as the WS_THICKFRAME style." }, { "code": null, "e": 17280, "s": 17269, "text": "WS_SYSMENU" }, { "code": null, "e": 17382, "s": 17280, "text": "Creates a window that has a Control-menu box in its title bar. Used only for windows with title bars." }, { "code": null, "e": 17393, "s": 17382, "text": "WS_TABSTOP" }, { "code": null, "e": 17569, "s": 17393, "text": "Specifies one of any number of controls through which the user can move by using the TAB key. The TAB key moves the user to the next control specified by the WS_TABSTOP style." }, { "code": null, "e": 17583, "s": 17569, "text": "WS_THICKFRAME" }, { "code": null, "e": 17656, "s": 17583, "text": "Creates a window with a thick frame that can be used to size the window." }, { "code": null, "e": 17665, "s": 17656, "text": "WS_TILED" }, { "code": null, "e": 17779, "s": 17665, "text": "Creates an overlapped window. An overlapped window has a title bar and a border. Same as the WS_OVERLAPPED style." }, { "code": null, "e": 17794, "s": 17779, "text": "WS_TILEDWINDOW" }, { "code": null, "e": 17968, "s": 17794, "text": "Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. Same as the WS_OVERLAPPEDWINDOW style." }, { "code": null, "e": 17979, "s": 17968, "text": "WS_VISIBLE" }, { "code": null, "e": 18023, "s": 17979, "text": "Creates a window that is initially visible." }, { "code": null, "e": 18034, "s": 18023, "text": "WS_VSCROLL" }, { "code": null, "e": 18083, "s": 18034, "text": "Creates a window that has a vertical scroll bar." }, { "code": null, "e": 18337, "s": 18083, "text": "Step 1 − Let us look into a simple example in which we will add some styling. After creating a window, to display it to the user, we can apply the WS_VISIBLE style to it and additionally, we will also add WS_OVERLAPPED style. Here is an implementation −" }, { "code": null, "e": 18497, "s": 18337, "text": "class CMyFrame : public CFrameWnd {\n public:\n CMyFrame() {\n Create(NULL, _T(\"MFC Application Tutorial\"), WS_VISIBLE | WS_OVERLAPPED);\n }\n};" }, { "code": null, "e": 18570, "s": 18497, "text": "Step 2 − When you run this application, the following window is created." }, { "code": null, "e": 18656, "s": 18570, "text": "You can now see that the minimize, maximize, and close options do not appear anymore." }, { "code": null, "e": 18980, "s": 18656, "text": "To locate things displayed on the monitor, the computer uses a coordinate system similar to the Cartesian's, but the origin is located on the top left corner of the screen. Using this coordinate system, any point can be located by its distance from the top left corner of the screen of the horizontal and the vertical axes." }, { "code": null, "e": 19053, "s": 18980, "text": "The Win32 library provides a structure called POINT defined as follows −" }, { "code": null, "e": 19110, "s": 19053, "text": "typedef struct tagPOINT {\n LONG x;\n LONG y;\n} POINT;" }, { "code": null, "e": 19199, "s": 19110, "text": "The ‘x’ member variable is the distance from the left border of the screen to the point." }, { "code": null, "e": 19288, "s": 19199, "text": "The ‘x’ member variable is the distance from the left border of the screen to the point." }, { "code": null, "e": 19377, "s": 19288, "text": "The ‘y’ variable represents the distance from the top border of the screen to the point." }, { "code": null, "e": 19466, "s": 19377, "text": "The ‘y’ variable represents the distance from the top border of the screen to the point." }, { "code": null, "e": 19575, "s": 19466, "text": "Besides the Win32's POINT structure, the Microsoft Foundation Class (MFC) library provides the CPoint class." }, { "code": null, "e": 19684, "s": 19575, "text": "Besides the Win32's POINT structure, the Microsoft Foundation Class (MFC) library provides the CPoint class." }, { "code": null, "e": 19844, "s": 19684, "text": "This provides the same functionality as the POINT structure. As a C++ class, it adds more functionality needed to locate a point. It provides two constructors." }, { "code": null, "e": 20004, "s": 19844, "text": "This provides the same functionality as the POINT structure. As a C++ class, it adds more functionality needed to locate a point. It provides two constructors." }, { "code": null, "e": 20036, "s": 20004, "text": "CPoint();\nCPoint(int X, int Y);" }, { "code": null, "e": 20170, "s": 20036, "text": "While a point is used to locate an object on the screen, each window has a size. The size provides two measures related to an object." }, { "code": null, "e": 20194, "s": 20170, "text": "The width of an object." }, { "code": null, "e": 20219, "s": 20194, "text": "The height of an object." }, { "code": null, "e": 20282, "s": 20219, "text": "The Win32 library uses the SIZE structure defined as follows −" }, { "code": null, "e": 20337, "s": 20282, "text": "typedef struct tagSIZE {\n int cx;\n int cy;\n} SIZE;" }, { "code": null, "e": 20585, "s": 20337, "text": "Besides the Win32's SIZE structure, the MFC provides the CSize class. This class has the same functionality as SIZE but adds features of a C++ class. It provides five constructors that allow you to create a size variable in any way of your choice." }, { "code": null, "e": 20689, "s": 20585, "text": "CSize();\nCSize(int initCX, int initCY);\nCSize(SIZE initSize);\nCSize(POINT initPt);\nCSize(DWORD dwSize);" }, { "code": null, "e": 21043, "s": 20689, "text": "When a Window displays, it can be identified on the screen by its location with regards to the borders of the monitor. A Window can also be identified by its width and height. These characteristics are specified or controlled by the rect argument of the Create() method. This argument is a rectangle that can be created through the Win32 RECT structure." }, { "code": null, "e": 21140, "s": 21043, "text": "typedef struct _RECT {\n LONG left;\n LONG top;\n LONG right;\n LONG bottom;\n} RECT, *PRECT;" }, { "code": null, "e": 21249, "s": 21140, "text": "Besides the Win32's RECT structure, the MFC provides the CRect class which has the following constructors − " }, { "code": null, "e": 21419, "s": 21249, "text": "CRect();\nCRect(int l, int t, int r, int b);\nCRect(const RECT& srcRect);\nCRect(LPCRECT lpSrcRect);\nCRect(POINT point, SIZE size);\nCRect(POINT topLeft, POINT bottomRight);" }, { "code": null, "e": 21518, "s": 21419, "text": "Let us look into a simple example in which we will specify the location and the size of the window" }, { "code": null, "e": 21701, "s": 21518, "text": "class CMyFrame : public CFrameWnd {\n public:\n CMyFrame() {\n Create(NULL, _T(\"MFC Application Tutorial\"), WS_SYSMENU, CRect(90, 120, \n 550, 480));\n }\n};" }, { "code": null, "e": 21917, "s": 21701, "text": "When you run this application, the following window is created on the top left corner of your screen as specified in CRect constructor in the first two parameters. The last two parameters are the size of the Window." }, { "code": null, "e": 22270, "s": 21917, "text": "In the real world, many applications are made of different Windows. When an application uses various Windows, most of the objects depend on a particular one. It could be the first Window that was created or another window that you designated. Such a Window is referred to as the Parent Window. All the other windows depend on it directly or indirectly." }, { "code": null, "e": 22364, "s": 22270, "text": "If the Window you are creating is dependent of another, you can specify that it has a parent." }, { "code": null, "e": 22458, "s": 22364, "text": "If the Window you are creating is dependent of another, you can specify that it has a parent." }, { "code": null, "e": 22535, "s": 22458, "text": "This is done with the pParentWnd argument of the CFrameWnd::Create() method." }, { "code": null, "e": 22612, "s": 22535, "text": "This is done with the pParentWnd argument of the CFrameWnd::Create() method." }, { "code": null, "e": 22687, "s": 22612, "text": "If the Window does not have a parent, pass the argument with a NULL value." }, { "code": null, "e": 22762, "s": 22687, "text": "If the Window does not have a parent, pass the argument with a NULL value." }, { "code": null, "e": 22936, "s": 22762, "text": "Let us look into an example which has only one Window, and there is no parent Window available, so we will pass the argument with NULL value as shown in the following code −" }, { "code": null, "e": 23125, "s": 22936, "text": "class CMyFrame : public CFrameWnd {\n public:\n CMyFrame() {\n Create(NULL, _T(\"MFC Application Tutorial\"), WS_SYSMENU, \n CRect(90, 120, 550, 480), NULL);\n }\n};" }, { "code": null, "e": 23186, "s": 23125, "text": "When you run the above application, you see the same output." }, { "code": null, "e": 23498, "s": 23186, "text": "In this chapter, we will be covering the Dialog boxes. Applications for Windows frequently communicate with the user through dialog boxes. CDialog class provides an interface for managing dialog boxes. The Visual C++ dialog editor makes it easy to design dialog boxes and create their dialog-template resources." }, { "code": null, "e": 23607, "s": 23498, "text": "Creating a dialog object is a two-phase operation −\n\nConstruct the dialog object.\nCreate the dialog window.\n" }, { "code": null, "e": 23659, "s": 23607, "text": "Creating a dialog object is a two-phase operation −" }, { "code": null, "e": 23688, "s": 23659, "text": "Construct the dialog object." }, { "code": null, "e": 23717, "s": 23688, "text": "Construct the dialog object." }, { "code": null, "e": 23743, "s": 23717, "text": "Create the dialog window." }, { "code": null, "e": 23769, "s": 23743, "text": "Create the dialog window." }, { "code": null, "e": 23836, "s": 23769, "text": "Let us look into a simple example by creating a new Win32 project." }, { "code": null, "e": 23919, "s": 23836, "text": "Step 1 − Open the Visual studio and click on the File → New → Project menu option." }, { "code": null, "e": 23972, "s": 23919, "text": "Step 2 − You can now see the New Project dialog box." }, { "code": null, "e": 24040, "s": 23972, "text": "Step 3 − From the left pane, select Templates → Visual C++ → Win32." }, { "code": null, "e": 24091, "s": 24040, "text": "Step 4 − In the middle pane, select Win32 Project." }, { "code": null, "e": 24214, "s": 24091, "text": "Step 5 − Enter project name ‘MFCDialogDemo’ in the Name field and click OK to continue. You will see the following dialog." }, { "code": null, "e": 24235, "s": 24214, "text": "Step 6 − Click Next." }, { "code": null, "e": 24317, "s": 24235, "text": "Step 7 − Select the options shown in the dialog box given above and click Finish." }, { "code": null, "e": 24355, "s": 24317, "text": "Step 8 − An empty project is created." }, { "code": null, "e": 24440, "s": 24355, "text": "Step 9 − To make it a MFC project, right-click on the project and select Properties." }, { "code": null, "e": 24513, "s": 24440, "text": "Step 10 − In the left section, click Configuration Properties → General." }, { "code": null, "e": 24605, "s": 24513, "text": "Step 11 − Select the Use MFC in Shared DLL option in Project Defaults section and click OK." }, { "code": null, "e": 24638, "s": 24605, "text": "Step 12 − Add a new source file." }, { "code": null, "e": 24703, "s": 24638, "text": "Step 13 − Right-click on your Project and select Add → New Item." }, { "code": null, "e": 24761, "s": 24703, "text": "Step 14 − In the Templates section, click C++ File (.cpp)" }, { "code": null, "e": 24810, "s": 24761, "text": "Step 15 − Set the Name as Example and click Add." }, { "code": null, "e": 24907, "s": 24810, "text": "Step 16 − To create an application, we need to add a class and derive it from the MFC's CWinApp." }, { "code": null, "e": 25003, "s": 24907, "text": "#include <afxwin.h>\n\nclass CExample : public CWinApp {\n public:\n BOOL InitInstance();\n};" }, { "code": null, "e": 25125, "s": 25003, "text": "Step 1 − To create a dialog box, right-click on the Resource Files folder in solution explorer and select Add → Resource." }, { "code": null, "e": 25195, "s": 25125, "text": "Step 2 − In the Add Resource dialog box, select Dialog and click New." }, { "code": null, "e": 25289, "s": 25195, "text": "Step 3 − A dialog box requires some preparation before actually programmatically creating it." }, { "code": null, "e": 25378, "s": 25289, "text": "Step 4 − A dialog box can first be manually created as a text file (in a resource file)." }, { "code": null, "e": 25459, "s": 25378, "text": "Step 5 − You can now see the MFCDialogDemo.rc file created under Resource Files." }, { "code": null, "e": 25600, "s": 25459, "text": "Step 6 − The resource file is open in designer. The same can be opened as a text file. Rightclick on the resource file and select Open With." }, { "code": null, "e": 25668, "s": 25600, "text": "Step 7 − Select the Source Code (Text) editor and click Add button." }, { "code": null, "e": 25754, "s": 25668, "text": "Step 8 − Go back to the designer and right-click on the dialog and select Properties." }, { "code": null, "e": 25807, "s": 25754, "text": "Step 9 − You need to choose out of the many options." }, { "code": null, "e": 25979, "s": 25807, "text": "Step 10 − Like most other controls, a dialog box must be identified. The identifier (ID) of a dialog box usually starts with IDD_, Let us change the ID to IDD_EXAMPLE_DLG." }, { "code": null, "e": 26192, "s": 25979, "text": "A dialog box must be “physically” located on an application. Because a dialog box is usually created as a parent to other controls, its location depends on its relationship to its parent window or to the desktop." }, { "code": null, "e": 26268, "s": 26192, "text": "If you look and the Properties window, you see two fields, X Pos and Y Pos." }, { "code": null, "e": 26360, "s": 26268, "text": "X is the distance from the left border of the monitor to the left border of the dialog box." }, { "code": null, "e": 26452, "s": 26360, "text": "X is the distance from the left border of the monitor to the left border of the dialog box." }, { "code": null, "e": 26542, "s": 26452, "text": "Y is the distance from the top border of the monitor to the top border of the dialog box." }, { "code": null, "e": 26632, "s": 26542, "text": "Y is the distance from the top border of the monitor to the top border of the dialog box." }, { "code": null, "e": 26710, "s": 26632, "text": "By default, these fields are set to zero. You can also change as shown above." }, { "code": null, "e": 26866, "s": 26710, "text": "If you specify these two dimensions as 0, the left and top borders of the dialog box would be set so the object appears in the center-middle of the screen." }, { "code": null, "e": 27011, "s": 26866, "text": "The dimensions of a dialog box refer to its width and its height. You can resize the width and height with the help of mouse in designer window." }, { "code": null, "e": 27074, "s": 27011, "text": "You can see the changes in width and height on the Status Bar." }, { "code": null, "e": 27294, "s": 27074, "text": "The base class used for displaying dialog boxes on the screen is CDialog class. To create a dialog box, we need to derive a class from CDialog. The CDialog class itself provides three constructors which are as follows −" }, { "code": null, "e": 27417, "s": 27294, "text": "CDialog();\nCDialog(UINT nIDTemplate, CWnd* pParentWnd = NULL);\nCDialog(LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL);" }, { "code": null, "e": 27570, "s": 27417, "text": "Let us create another class CExampleDlg and derive it from CDialog. We will implement its default constructor destructor as shown in the following code." }, { "code": null, "e": 27799, "s": 27570, "text": "class CExampleDlg : public CDialog {\n public:\n enum { IDD = IDD_EXAMPLE_DLG };\n \n CExampleDlg();\n ~CExampleDlg();\n};\n\nCExampleDlg::CExampleDlg():CDialog(CExampleDlg::IDD) {\n\n}\n\nCExampleDlg::~CExampleDlg() {\n\n}" }, { "code": null, "e": 27901, "s": 27799, "text": "We need to instantiate this dialog on CExample::InitInstance() method as shown in the following code." }, { "code": null, "e": 28001, "s": 27901, "text": "BOOL CExample::InitInstance() {\n CExampleDlg myDlg;\n m_pMainWnd = &myDlg;\n \n return TRUE;\n}" }, { "code": null, "e": 28146, "s": 28001, "text": "There are two types of dialog boxes − modeless and modal. Modal and modeless dialog boxes differ by the process used to create and display them." }, { "code": null, "e": 28240, "s": 28146, "text": "For a modeless dialog box, you must provide your own public constructor in your dialog class." }, { "code": null, "e": 28334, "s": 28240, "text": "For a modeless dialog box, you must provide your own public constructor in your dialog class." }, { "code": null, "e": 28482, "s": 28334, "text": "To create a modeless dialog box, call your public constructor and then call the dialog object's Create member function to load the dialog resource." }, { "code": null, "e": 28630, "s": 28482, "text": "To create a modeless dialog box, call your public constructor and then call the dialog object's Create member function to load the dialog resource." }, { "code": null, "e": 28783, "s": 28630, "text": "You can call Create either during or after the constructor call. If the dialog resource has the property WS_VISIBLE, the dialog box appears immediately." }, { "code": null, "e": 28936, "s": 28783, "text": "You can call Create either during or after the constructor call. If the dialog resource has the property WS_VISIBLE, the dialog box appears immediately." }, { "code": null, "e": 28990, "s": 28936, "text": "If not, you must call its ShowWindow member function." }, { "code": null, "e": 29044, "s": 28990, "text": "If not, you must call its ShowWindow member function." }, { "code": null, "e": 29138, "s": 29044, "text": "To create a modal dialog box, call either of the two public constructors declared in CDialog." }, { "code": null, "e": 29232, "s": 29138, "text": "To create a modal dialog box, call either of the two public constructors declared in CDialog." }, { "code": null, "e": 29381, "s": 29232, "text": "Next, call the dialog object's DoModal member function to display the dialog box and manage interaction with it until the user chooses OK or Cancel." }, { "code": null, "e": 29530, "s": 29381, "text": "Next, call the dialog object's DoModal member function to display the dialog box and manage interaction with it until the user chooses OK or Cancel." }, { "code": null, "e": 29652, "s": 29530, "text": "This management by DoModal is what makes the dialog box modal. For modal dialog boxes, DoModal loads the dialog resource." }, { "code": null, "e": 29774, "s": 29652, "text": "This management by DoModal is what makes the dialog box modal. For modal dialog boxes, DoModal loads the dialog resource." }, { "code": null, "e": 29913, "s": 29774, "text": "Step 1 − To display the dialog box as modal, in the CExample::InitInstance() event call the DoModal() method using your dialog variable − " }, { "code": null, "e": 30029, "s": 29913, "text": "BOOL CExample::InitInstance() {\n CExampleDlg myDlg;\n m_pMainWnd = &myDlg;\n myDlg.DoModal();\n return TRUE;\n}" }, { "code": null, "e": 30095, "s": 30029, "text": "Step 2 − Here is the complete implementation of Example.cpp file." }, { "code": null, "e": 30578, "s": 30095, "text": "#include <afxwin.h>\n#include \"resource.h\"\n\nclass CExample : public CWinApp {\n public:\n BOOL InitInstance();\n};\n \nclass CExampleDlg : public CDialog {\n public:\n enum { IDD = IDD_EXAMPLE_DLG };\n \n CExampleDlg();\n ~CExampleDlg();\n};\n\nCExampleDlg::CExampleDlg():CDialog(CExampleDlg::IDD) {\n\n}\n\nCExampleDlg::~CExampleDlg() {\n\n}\n\nBOOL CExample::InitInstance() {\n CExampleDlg myDlg;\n m_pMainWnd = &myDlg;\n myDlg.DoModal();\n return TRUE;\n}\nCExample MyApp;" }, { "code": null, "e": 30672, "s": 30578, "text": "Step 3 − When the above code is compiled and executed, you will see the following dialog box." }, { "code": null, "e": 30887, "s": 30672, "text": "Microsoft Visual Studio provides an easier way to create an application that is mainly based on a dialog box. Here are the steps to create a dialog base project using project templates available in Visual Studio − " }, { "code": null, "e": 31010, "s": 30887, "text": "Step 1 − Open the Visual studio and click on the File → New → Project menu option. You can see the New Project dialog box." }, { "code": null, "e": 31076, "s": 31010, "text": "Step 2 − From the left pane, select Templates → Visual C++ → MFC." }, { "code": null, "e": 31129, "s": 31076, "text": "Step 3 − In the middle pane, select MFC Application." }, { "code": null, "e": 31255, "s": 31129, "text": "Step 4 − Enter project name ‘MFCModalDemo’ in the Name field and click OK to continue. You will see the following dialog box." }, { "code": null, "e": 31276, "s": 31255, "text": "Step 5 − Click Next." }, { "code": null, "e": 31350, "s": 31276, "text": "Step 6 − Select the options shown in the above dialog box and click Next." }, { "code": null, "e": 31473, "s": 31350, "text": "Step 7 − Check all the options that you choose to have on your dialog box like Maximize and Minimize Boxes and click Next." }, { "code": null, "e": 31494, "s": 31473, "text": "Step 8 − Click Next." }, { "code": null, "e": 31596, "s": 31494, "text": "Step 9 − It will generate these two classes. You can change the name of the classes and click Finish." }, { "code": null, "e": 31700, "s": 31596, "text": "Step 10 − You can now see that the MFC wizard creates this Dialog Box and the project files by default." }, { "code": null, "e": 31776, "s": 31700, "text": "Step 11 − When you run this application, you will see the following output." }, { "code": null, "e": 32221, "s": 31776, "text": "A resource is a text file that allows the compiler to manage objects such as pictures, sounds, mouse cursors, dialog boxes, etc. Microsoft Visual Studio makes creating a resource file particularly easy by providing the necessary tools in the same environment used to program. This means, you usually do not have to use an external application to create or configure a resource file. Following are some important features related to resources." }, { "code": null, "e": 32292, "s": 32221, "text": "Resources are interface elements that provide information to the user." }, { "code": null, "e": 32363, "s": 32292, "text": "Resources are interface elements that provide information to the user." }, { "code": null, "e": 32420, "s": 32363, "text": "Bitmaps, icons, toolbars, and cursors are all resources." }, { "code": null, "e": 32477, "s": 32420, "text": "Bitmaps, icons, toolbars, and cursors are all resources." }, { "code": null, "e": 32594, "s": 32477, "text": "Some resources can be manipulated to perform an action such as selecting from a menu or entering data in dialog box." }, { "code": null, "e": 32711, "s": 32594, "text": "Some resources can be manipulated to perform an action such as selecting from a menu or entering data in dialog box." }, { "code": null, "e": 32867, "s": 32711, "text": "An application can use various resources that behave independently of each other, these resources are grouped into a text file that has the *.rc extension." }, { "code": null, "e": 33023, "s": 32867, "text": "An application can use various resources that behave independently of each other, these resources are grouped into a text file that has the *.rc extension." }, { "code": null, "e": 33113, "s": 33023, "text": "Most resources are created by selecting the desired one from the Add Resource dialog box." }, { "code": null, "e": 33203, "s": 33113, "text": "Most resources are created by selecting the desired one from the Add Resource dialog box." }, { "code": null, "e": 33435, "s": 33203, "text": "The Add Resource dialog box provides an extensive list of resources which can be used as per requirements, but if you need something which is not available then you can add it manually to the *.rc file before executing the program." }, { "code": null, "e": 33667, "s": 33435, "text": "The Add Resource dialog box provides an extensive list of resources which can be used as per requirements, but if you need something which is not available then you can add it manually to the *.rc file before executing the program." }, { "code": null, "e": 33854, "s": 33667, "text": "An identifier is a symbol which is a constant integer whose name usually starts with ID. It consists of two parts − a text string (symbol name) mapped to an integer value (symbol value)." }, { "code": null, "e": 34027, "s": 33854, "text": "Symbols provide a descriptive way of referring to resources and user-interface objects, both in your source code and while you're working with them in the resource editors." }, { "code": null, "e": 34200, "s": 34027, "text": "Symbols provide a descriptive way of referring to resources and user-interface objects, both in your source code and while you're working with them in the resource editors." }, { "code": null, "e": 34365, "s": 34200, "text": "When you create a new resource or resource object, the resource editors provide a default name for the resource, for example, IDC_DIALOG1, and assign a value to it." }, { "code": null, "e": 34530, "s": 34365, "text": "When you create a new resource or resource object, the resource editors provide a default name for the resource, for example, IDC_DIALOG1, and assign a value to it." }, { "code": null, "e": 34595, "s": 34530, "text": "The name-plus-value definition is stored in the Resource.h file." }, { "code": null, "e": 34660, "s": 34595, "text": "The name-plus-value definition is stored in the Resource.h file." }, { "code": null, "e": 34804, "s": 34660, "text": "Step 1 − Let us look into our CMFCDialogDemo example from the last chapter in which we have created a dialog box and its ID is IDD_EXAMPLE_DLG." }, { "code": null, "e": 35009, "s": 34804, "text": "Step 2 − Go to the Solution Explorer, you will see the resource.h file under Header Files. Continue by opening this file in editor and you will see the dialog box identifier and its integer value as well." }, { "code": null, "e": 35120, "s": 35009, "text": "An icon is a small picture used on a window which represents an application. It is used in two main scenarios." }, { "code": null, "e": 35211, "s": 35120, "text": "On a Window's frame, it is displayed on the left side of the Window name on the title bar." }, { "code": null, "e": 35302, "s": 35211, "text": "On a Window's frame, it is displayed on the left side of the Window name on the title bar." }, { "code": null, "e": 35387, "s": 35302, "text": "In Windows Explorer, on the Desktop, in My Computer, or in the Control Panel window." }, { "code": null, "e": 35472, "s": 35387, "text": "In Windows Explorer, on the Desktop, in My Computer, or in the Control Panel window." }, { "code": null, "e": 35624, "s": 35472, "text": "If you look at our MFCModalDemo example, you will see that Visual studio was using a default icon for the title bar as shown in the following snapshot." }, { "code": null, "e": 35690, "s": 35624, "text": "You can create your own icon by following the steps given below −" }, { "code": null, "e": 35798, "s": 35690, "text": "Step 1 − Right-click on your project and select Add → Resources, you will see the Add Resources dialog box." }, { "code": null, "e": 35877, "s": 35798, "text": "Step 2 − Select Icon and click New button and you will see the following icon." }, { "code": null, "e": 36062, "s": 35877, "text": "Step 3 − In Solution Explorer, go to Resource View and expand MFCModalDemo > Icon. You will see two icons. The IDR_MAINFRAME is the default one and IDI_ICON1 is the newly created icon." }, { "code": null, "e": 36132, "s": 36062, "text": "Step 4 − Right-click on the newly Created icon and select Properties." }, { "code": null, "e": 36216, "s": 36132, "text": "Step 5 − IDI_ICON1 is the ID of this icon, now Let us change this ID to IDR_MYICON." }, { "code": null, "e": 36323, "s": 36216, "text": "Step 6 − You can now change this icon in the designer as per your requirements. We will use the same icon." }, { "code": null, "e": 36348, "s": 36323, "text": "Step 7 − Save this icon." }, { "code": null, "e": 36466, "s": 36348, "text": "Step 8 − Go to the CMFCModalDemoDlg constructor in CMFCModalDemoDlg.cpp file which will look like the following code." }, { "code": null, "e": 36634, "s": 36466, "text": "CMFCModalDemoDlg::CMFCModalDemoDlg(CWnd* pParent /* = NULL*/)\n : CDialogEx(IDD_MFCMODALDEMO_DIALOG, pParent) {\n m_hIcon = AfxGetApp() -> LoadIcon(IDR_MAINFRAME);\n}" }, { "code": null, "e": 36775, "s": 36634, "text": "Step 9 − You can now see that the default icon is loaded in the constructor. Let us change it to IDR_ MYICON as shown in the following code." }, { "code": null, "e": 36941, "s": 36775, "text": "CMFCModalDemoDlg::CMFCModalDemoDlg(CWnd* pParent /* = NULL*/)\n : CDialogEx(IDD_MFCMODALDEMO_DIALOG, pParent) {\n m_hIcon = AfxGetApp() -> LoadIcon(IDR_ MYICON);\n}" }, { "code": null, "e": 37055, "s": 36941, "text": "Step 10 − When the above code is compiled and executed, you will see the new icon is displayed on the dialog box." }, { "code": null, "e": 37328, "s": 37055, "text": "Menus allow you to arrange commands in a logical and easy-to-find fashion. With the Menu editor, you can create and edit menus by working directly with a menu bar that closely resembles the one in your finished application. To create a menu, follow the steps given below −" }, { "code": null, "e": 37436, "s": 37328, "text": "Step 1 − Right-click on your project and select Add → Resources. You will see the Add Resources dialog box." }, { "code": null, "e": 37542, "s": 37436, "text": "Step 2 − Select Menu and click New. You will see the rectangle that contains \"Type Here\" on the menu bar." }, { "code": null, "e": 37633, "s": 37542, "text": "Step 3 − Write some menu options like File, Edit, etc. as shown in the following snapshot." }, { "code": null, "e": 37796, "s": 37633, "text": "Step 4 − If you expand the Menu folder in Resource View, you will see the Menu identifier IDR_MENU1. Right-click on this identifier and change it to IDM_MAINMENU." }, { "code": null, "e": 37827, "s": 37796, "text": "Step 5 − Save all the changes." }, { "code": null, "e": 37977, "s": 37827, "text": "Step 6 − We need to attach this menu to our dialog box. Expand your Dialog folder in Solution Explorer and double click on the dialog box identifier." }, { "code": null, "e": 38094, "s": 37977, "text": "Step 7 − You will see the menu field in the Properties. Select the Menu identifier from the dropdown as shown above." }, { "code": null, "e": 38200, "s": 38094, "text": "Step 8 − Run this application and you will see the following dialog box which also contains menu options." }, { "code": null, "e": 38332, "s": 38200, "text": "A toolbar is a Windows control that allows the user to perform some actions on a form by clicking a button instead of using a menu." }, { "code": null, "e": 38464, "s": 38332, "text": "A toolbar provides a convenient group of buttons that simplifies the user's job by bringing the most accessible actions as buttons." }, { "code": null, "e": 38596, "s": 38464, "text": "A toolbar provides a convenient group of buttons that simplifies the user's job by bringing the most accessible actions as buttons." }, { "code": null, "e": 38656, "s": 38596, "text": "A toolbar can bring such common actions closer to the user." }, { "code": null, "e": 38716, "s": 38656, "text": "A toolbar can bring such common actions closer to the user." }, { "code": null, "e": 38762, "s": 38716, "text": "Toolbars usually display under the main menu." }, { "code": null, "e": 38808, "s": 38762, "text": "Toolbars usually display under the main menu." }, { "code": null, "e": 38911, "s": 38808, "text": "They can be equipped with buttons but sometimes their buttons or some of their buttons have a caption." }, { "code": null, "e": 39014, "s": 38911, "text": "They can be equipped with buttons but sometimes their buttons or some of their buttons have a caption." }, { "code": null, "e": 39074, "s": 39014, "text": "Toolbars can also be equipped with other types of controls." }, { "code": null, "e": 39134, "s": 39074, "text": "Toolbars can also be equipped with other types of controls." }, { "code": null, "e": 39180, "s": 39134, "text": "To create a toolbar, following are the steps." }, { "code": null, "e": 39288, "s": 39180, "text": "Step 1 − Right-click on your project and select Add → Resources. You will see the Add Resources dialog box." }, { "code": null, "e": 39362, "s": 39288, "text": "Step 2 − Select Toolbar and click New. You will see the following screen." }, { "code": null, "e": 39473, "s": 39362, "text": "Step 3 − Design your toolbar in the designer as shown in the following screenshot and specify the IDs as well." }, { "code": null, "e": 39533, "s": 39473, "text": "Step 4 − Add these two variables in CMFCModalDemoDlg class." }, { "code": null, "e": 39573, "s": 39533, "text": " CToolBar m_wndToolBar;\n BOOL butD;" }, { "code": null, "e": 39672, "s": 39573, "text": "Step 5 − Following is the complete implementation of CMFCModalDemoDlg in CMFCModalDemoDlg.h file −" }, { "code": null, "e": 40342, "s": 39672, "text": "class CMFCModalDemoDlg : public CDialogEx {\n // Construction\n public:\n CMFCModalDemoDlg(CWnd* pParent = NULL); // standard constructor\n // Dialog Data\n #ifdef AFX_DESIGN_TIME\n enum { IDD = IDD_MFCMODALDEMO_DIALOG };\n #endif\n\n protected:\n virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support\n \n // Implementation\n protected:\n HICON m_hIcon;\n CToolBar m_wndToolBar;\n BOOL butD;\n \n // Generated message map functions\n virtual BOOL OnInitDialog();\n afx_msg void OnPaint();\n afx_msg HCURSOR OnQueryDragIcon();\n DECLARE_MESSAGE_MAP()\n\t\n public:\n afx_msg void OnBnClickedOk();\n};" }, { "code": null, "e": 40423, "s": 40342, "text": "Step 6 − Update CMFCModalDemoDlg::OnInitDialog() as shown in the following code." }, { "code": null, "e": 43174, "s": 40423, "text": "BOOL CMFCModalDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n \n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n \n if (!m_wndToolBar.Create(this)\n || !m_wndToolBar.LoadToolBar(IDR_TOOLBAR1))\n //if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD |\n // WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS |\n // CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||\n // !m_wndToolBar.LoadToolBar(IDR_TOOLBAR1)) {\n TRACE0(\"Failed to Create Dialog Toolbar\\n\");\n EndDialog(IDCANCEL);\n }\n butD = TRUE;\n CRect rcClientOld; // Old Client Rect\n CRect rcClientNew; // New Client Rect with Tollbar Added\n\t\t\n // Retrive the Old Client WindowSize\n // Called to reposition and resize control bars in the client area of a window\n // The reposQuery FLAG does not really traw the Toolbar. It only does the calculations.\n // And puts the new ClientRect values in rcClientNew so we can do the rest of the Math.\n \n GetClientRect(rcClientOld);\n RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0, reposQuery, rcClientNew);\n // All of the Child Windows (Controls) now need to be moved so the Tollbar does not cover them up.\n // Offest to move all child controls after adding Tollbar \n CPoint ptOffset(rcClientNew.left - rcClientOld.left, rcClientNew.top - rcClientOld.top); \n\t\t \n CRect rcChild;\n CWnd* pwndChild = GetWindow(GW_CHILD); //Handle to the Dialog Controls\n \n while (pwndChild) // Cycle through all child controls {\n pwndChild -> GetWindowRect(rcChild); // Get the child control RECT\n ScreenToClient(rcChild);\n \n // Changes the Child Rect by the values of the claculated offset\n rcChild.OffsetRect(ptOffset);\n pwndChild -> MoveWindow(rcChild, FALSE); // Move the Child Control\n pwndChild = pwndChild -> GetNextWindow();\n }\n \n CRect rcWindow;\n // Get the RECT of the Dialog\n GetWindowRect(rcWindow);\n \n // Increase width to new Client Width\n rcWindow.right += rcClientOld.Width() - rcClientNew.Width();\n \n // Increase height to new Client Height\n rcWindow.bottom += rcClientOld.Height() - rcClientNew.Height();\n // Redraw Window\n MoveWindow(rcWindow, FALSE);\n \n // Now we REALLY Redraw the Toolbar\n RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0);\n \n // TODO: Add extra initialization here\n\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 43276, "s": 43174, "text": "Step 7 − Run this application. You will see the following dialog box which also contains the toolbar." }, { "code": null, "e": 43541, "s": 43276, "text": "An access key is a letter that allows the user to perform a menu action faster by using the keyboard instead of the mouse. This is usually faster because the user would not need to position the mouse anywhere, which reduces the time it takes to perform the action." }, { "code": null, "e": 43627, "s": 43541, "text": "Step 1 − To create an access key, type an ampersand \"&\" on the left of the menu item." }, { "code": null, "e": 43782, "s": 43627, "text": "Step 2 − Repeat this step for all menu options. Run this application and press Alt. You will see that the first letter of all menu options are underlined." }, { "code": null, "e": 44057, "s": 43782, "text": "A shortcut key is a key or a combination of keys used by advanced users to perform an action that would otherwise be done on a menu item. Most shortcuts are a combination of the Ctrl key simultaneously pressed with a letter key. For example, Ctrl + N, Ctrl + O, or Ctrl + D." }, { "code": null, "e": 44192, "s": 44057, "text": "To create a shortcut, on the right side of the string that makes up a menu caption, rightclick on the menu item and select properties." }, { "code": null, "e": 44335, "s": 44192, "text": "In the Caption field type \\t followed by the desired combination as shown below for the New menu option. Repeat the step for all menu options." }, { "code": null, "e": 44657, "s": 44335, "text": "An Accelerator Table is a list of items where each item of the table combines an identifier, a shortcut key, and a constant number that specifies the kind of accelerator key. Just like the other resources, an accelerator table can be created manually in a .rc file. Following are the steps to create an accelerator table." }, { "code": null, "e": 44749, "s": 44657, "text": "Step 1 − To create an accelerator table, right-click on *.rc file in the solution explorer." }, { "code": null, "e": 44792, "s": 44749, "text": "Step 2 − Select Accelerator and click New." }, { "code": null, "e": 44860, "s": 44792, "text": "Step 3 − Click the arrow of the ID combo box and select menu Items." }, { "code": null, "e": 44909, "s": 44860, "text": "Step 4 − Select Ctrl from the Modifier dropdown." }, { "code": null, "e": 44988, "s": 44909, "text": "Step 5 − Click the Key box and type the respective Keys for both menu options." }, { "code": null, "e": 45081, "s": 44988, "text": "We will also add New menu item event handler to testing. Right-click on the New menu option." }, { "code": null, "e": 45211, "s": 45081, "text": "Step 6 − You can specify a class, message type and handler name. For now, let us leave it as it is and click Add and Edit button." }, { "code": null, "e": 45246, "s": 45211, "text": "Step 7 − Select Add Event Handler." }, { "code": null, "e": 45333, "s": 45246, "text": "Step 8 − You will now see the event added at the end of the CMFCModalDemoDlg.cpp file." }, { "code": null, "e": 45461, "s": 45333, "text": "void CMFCModalDemoDlg::OnFileNew() {\n // TODO: Add your command handler code here\n MessageBox(L\"File > New menu option\");\n}" }, { "code": null, "e": 45549, "s": 45461, "text": "Step 9 − Now Let us add a message box that will display the simple menu option message." }, { "code": null, "e": 45680, "s": 45549, "text": "To start accelerator table in working add the HACCEL variable and ProcessMessageFilter as shown in the following CMFCModalDemoApp." }, { "code": null, "e": 45980, "s": 45680, "text": "class CMFCModalDemoApp : public CWinApp {\n public:\n CMFCModalDemoApp();\n \n // Overrides\n public:\n virtual BOOL InitInstance();\n HACCEL m_hAccelTable;\n \n // Implementation\n\n DECLARE_MESSAGE_MAP()\n virtual BOOL ProcessMessageFilter(int code, LPMSG lpMsg);\n};" }, { "code": null, "e": 46071, "s": 45980, "text": "Step 10 − Load Accelerator and the following call in the CMFCModalDemoApp::InitInstance()." }, { "code": null, "e": 46167, "s": 46071, "text": "m_hAccelTable = LoadAccelerators(AfxGetInstanceHandle(),\n MAKEINTRESOURCE(IDR_ACCELERATOR1));" }, { "code": null, "e": 46229, "s": 46167, "text": "Step 11 − Here is the implementation of ProcessMessageFilter." }, { "code": null, "e": 46507, "s": 46229, "text": "BOOL CMFCModalDemoApp::ProcessMessageFilter(int code, LPMSG lpMsg) {\n if (code >= 0 && m_pMainWnd && m_hAccelTable) {\n if (::TranslateAccelerator(m_pMainWnd -> m_hWnd, m_hAccelTable, lpMsg))\n return TRUE;\n }\n return CWinApp::ProcessMessageFilter(code, lpMsg);\n}" }, { "code": null, "e": 46598, "s": 46507, "text": "Step 12 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 46707, "s": 46598, "text": "Step 13 − Press Alt button followed by F key and then N key or Ctrl + N. You will see the following message." }, { "code": null, "e": 47047, "s": 46707, "text": "A property sheet, also known as a tab dialog box, is a dialog box that contains property pages. Each property page is based on a dialog template resource and contains controls. It is enclosed on a page with a tab on top. The tab names the page and indicates its purpose. Users click a tab in the property sheet to select a set of controls." }, { "code": null, "e": 47147, "s": 47047, "text": "To create property pages, let us look into a simple example by creating a dialog based MFC project." }, { "code": null, "e": 47212, "s": 47147, "text": "Once the project is created, we need to add some property pages." }, { "code": null, "e": 47395, "s": 47212, "text": "Visual Studio makes it easy to create resources for property pages by displaying the Add Resource dialog box, expanding the Dialog node and selecting one of the IDD_PROPPAGE_X items." }, { "code": null, "e": 47481, "s": 47395, "text": "Step 1 − Right-click on your project in solution explorer and select Add → Resources." }, { "code": null, "e": 47535, "s": 47481, "text": "Step 2 − Select the IDD_PROPPAGE_LARGE and click NEW." }, { "code": null, "e": 47662, "s": 47535, "text": "Step 3 − Let us change ID and Caption of this property page to IDD_PROPPAGE_1 and Property Page 1 respectively as shown above." }, { "code": null, "e": 47724, "s": 47662, "text": "Step 4 − Right-click on the property page in designer window." }, { "code": null, "e": 47762, "s": 47724, "text": "Step 5 − Select the Add Class option." }, { "code": null, "e": 47848, "s": 47762, "text": "Step 6 − Enter the class name and select CPropertyPage from base class dropdown list." }, { "code": null, "e": 47883, "s": 47848, "text": "Step 7 − Click Finish to continue." }, { "code": null, "e": 48010, "s": 47883, "text": "Step 8 − Add one more property page with ID IDD_PROPPAGE_2 and Caption Property Page 2 by following the above mentioned steps." }, { "code": null, "e": 48121, "s": 48010, "text": "Step 9 − You can now see two property pages created. To implement its functionality, we need a property sheet." }, { "code": null, "e": 48199, "s": 48121, "text": "The Property Sheet groups the property pages together and keeps it as entity." }, { "code": null, "e": 48258, "s": 48199, "text": "To create a property sheet, follow the steps given below −" }, { "code": null, "e": 48332, "s": 48258, "text": "Step 1 − Right-click on your project and select Add > Class menu options." }, { "code": null, "e": 48434, "s": 48332, "text": "Step 2 − Select Visual C++ → MFC from the left pane and MFC Class in the template pane and click Add." }, { "code": null, "e": 48521, "s": 48434, "text": "Step 3 − Enter the class name and select CPropertySheet from base class dropdown list." }, { "code": null, "e": 48556, "s": 48521, "text": "Step 4 − Click finish to continue." }, { "code": null, "e": 48653, "s": 48556, "text": "Step 5 − To launch this property sheet, we need the following changes in our main project class." }, { "code": null, "e": 48722, "s": 48653, "text": "Step 6 − Add the following references in CMFCPropSheetDemo.cpp file." }, { "code": null, "e": 48789, "s": 48722, "text": "#include \"MySheet.h\"\n#include \"PropPage1.h\"\n#include \"PropPage2.h\"" }, { "code": null, "e": 48885, "s": 48789, "text": "Step 7 − Modify the CMFCPropSheetDemoApp::InitInstance() method as shown in the following code." }, { "code": null, "e": 49077, "s": 48885, "text": "CMySheet mySheet(L\"Property Sheet Demo\");\nCPropPage1 page1;\nCPropPage2 page2;\n\nmySheet.AddPage(&page1);\nmySheet.AddPage(&page2);\n\nm_pMainWnd = &mySheet;\nINT_PTR nResponse = mySheet.DoModal();" }, { "code": null, "e": 49153, "s": 49077, "text": "Step 8 − Here is the complete implementation of CMFCPropSheetDemo.cpp file." }, { "code": null, "e": 52430, "s": 49153, "text": "\n// MFCPropSheetDemo.cpp : Defines the class behaviors for the application.\n//\n#include \"stdafx.h\"\n#include \"MFCPropSheetDemo.h\"\n#include \"MFCPropSheetDemoDlg.h\"\n#include \"MySheet.h\"\n#include \"PropPage1.h\"\n#include \"PropPage2.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n\n\n// CMFCPropSheetDemoApp\nBEGIN_MESSAGE_MAP(CMFCPropSheetDemoApp, CWinApp)\n ON_COMMAND(ID_HELP, &CWinApp::OnHelp)\nEND_MESSAGE_MAP()\n\n\n// CMFCPropSheetDemoApp construction\n\nCMFCPropSheetDemoApp::CMFCPropSheetDemoApp() {\n\n // support Restart Manager\n m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART;\n // TODO: add construction code here,\n // Place all significant initialization in InitInstance\n}\n\n\n// The one and only CMFCPropSheetDemoApp object\n\nCMFCPropSheetDemoApp theApp;\n\n\n// CMFCPropSheetDemoApp initialization\n\nBOOL CMFCPropSheetDemoApp::InitInstance() {\n \n // InitCommonControlsEx() is required on Windows XP if an application\n // manifest specifies use of ComCtl32.dll version 6 or later to enable\n // visual styles. Otherwise, any window creation will fail.\n INITCOMMONCONTROLSEX InitCtrls;\n InitCtrls.dwSize = sizeof(InitCtrls);\n // Set this to include all the common control classes you want to use\n // in your application.\n InitCtrls.dwICC = ICC_WIN95_CLASSES;\n InitCommonControlsEx(&InitCtrls);\n \n CWinApp::InitInstance();\n \n \n AfxEnableControlContainer();\n \n // Create the shell manager, in case the dialog contains\n // any shell tree view or shell list view controls.\n CShellManager *pShellManager = new CShellManager;\n\n // Activate \"Windows Native\" visual manager for enabling themes in MFC controls\n CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));\n // Standard initialization\n // If you are not using these features and wish to reduce the size\n // of your final executable, you should remove from the following\n // the specific initialization routines you do not need\n // Change the registry key under which our settings are stored\n // TODO: You should modify this string to be something appropriate\n // such as the name of your company or organization\n SetRegistryKey(_T(\"Local AppWizard-Generated Applications\"));\n \n CMySheet mySheet(L\"Property Sheet Demo\");\n CPropPage1 page1;\n CPropPage2 page2;\n \n mySheet.AddPage(&page1);\n mySheet.AddPage(&page2);\n \n m_pMainWnd = &mySheet;\n INT_PTR nResponse = mySheet.DoModal();\n if (nResponse == IDOK) {\n // TODO: Place code here to handle when the dialog is\n // dismissed with OK\n }else if (nResponse == IDCANCEL) {\n // TODO: Place code here to handle when the dialog is\n // dismissed with Cancel\n }else if (nResponse == -1) { \n TRACE(traceAppMsg, 0, \"Warning: dialog creation failed, \n so application is terminating unexpectedly.\\n\");\n TRACE(traceAppMsg, 0, \"Warning: if you are using MFC controls on the dialog, \n you cannot #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS.\\n\");\n }\n\n // Delete the shell manager created above.\n if (pShellManager != NULL) {\n delete pShellManager;\n }\n\n // Since the dialog has been closed, return FALSE so that we exit the\n // application, rather than start the application's message pump.\n return FALSE;\n}" }, { "code": null, "e": 52569, "s": 52430, "text": "Step 9 − When the above code is compiled and executed, you will see the following dialog box. This dialog box contains two property pages." }, { "code": null, "e": 52786, "s": 52569, "text": "Layout of controls is very important and critical for application usability. It is used to arrange a group of GUI elements in your application. There are certain important things to consider while selecting layout − " }, { "code": null, "e": 52819, "s": 52786, "text": "Positions of the child elements." }, { "code": null, "e": 52848, "s": 52819, "text": "Sizes of the child elements." }, { "code": null, "e": 52906, "s": 52848, "text": "Let us create new Dialog based MFC Project MFCLayoutDemo." }, { "code": null, "e": 52979, "s": 52906, "text": "Step 1 − Once the project is created, you will see the following screen." }, { "code": null, "e": 53025, "s": 52979, "text": "Step 2 − Delete the TODO from the dialog box." }, { "code": null, "e": 53106, "s": 53025, "text": "Step 3 − Drag some controls from the Toolbox which you can see on the left side." }, { "code": null, "e": 53194, "s": 53106, "text": "(We will drag one Static Text and one Edit Control as shown in the following snapshot)." }, { "code": null, "e": 53250, "s": 53194, "text": "Step 4 − Change the Caption of the Static Text to Name." }, { "code": null, "e": 53376, "s": 53250, "text": "Control grid is the guiding grid dots, which can help in positioning of the controls you are adding at the time of designing." }, { "code": null, "e": 53496, "s": 53376, "text": "To enable the control grid, you need to click the Toggle Grid button in the toolbar as shown in the following snapshot." }, { "code": null, "e": 53730, "s": 53496, "text": "After you have added a control to a dialog box, it assumes either its default size or the size you drew it with. To help with the sizes of controls on the form or dialog box, Visual Studio provides a visual grid made of black points." }, { "code": null, "e": 53880, "s": 53730, "text": "To resize a control, that is, to give it a particular width or height, position the mouse on one of the handles and drag it in the desired direction." }, { "code": null, "e": 53947, "s": 53880, "text": "You can now resize the controls with the help of this dotted grid." }, { "code": null, "e": 54135, "s": 53947, "text": "The controls you position on a dialog box or a form assume their given place. Most of the time, these positions are not practical. You can move them around to any position of your choice." }, { "code": null, "e": 54167, "s": 54135, "text": "Let us add some more controls −" }, { "code": null, "e": 54278, "s": 54167, "text": "Step 1 − To move a control, click and drag it in the desired direction until it reaches the intended position." }, { "code": null, "e": 54434, "s": 54278, "text": "Step 2 − To move a group of controls, first select them. Then drag the selection to the desired location. Let us select the Static Texts and Edit Controls." }, { "code": null, "e": 54490, "s": 54434, "text": "Step 3 − Move these selected controls to the left side." }, { "code": null, "e": 54599, "s": 54490, "text": "To help with positioning the controls, Visual Studio provides the Dialog toolbar with the following buttons." }, { "code": null, "e": 54705, "s": 54599, "text": "Step 1 − Let us align the Check box and Static Text controls to the left by selecting all these controls." }, { "code": null, "e": 54749, "s": 54705, "text": "Step 2 − Select the Format → Align → Lefts." }, { "code": null, "e": 54818, "s": 54749, "text": "Step 3 − You can now see all these controls are aligned to the left." }, { "code": null, "e": 55233, "s": 54818, "text": "The controls you add to a form or a dialog box are positioned in a sequence that follows the order they were added. When you add control(s) regardless of the section or area you place the new control, it is sequentially positioned at the end of the existing controls. If you do not fix it, the user would have a hard time navigating the controls. The sequence of controls navigation is also known as the tab order." }, { "code": null, "e": 55372, "s": 55233, "text": "To change the tab, you can either use the Format → Tab Order menu option or you can also use the Ctrl + D shortcut. Let us press Ctrl + D." }, { "code": null, "e": 55570, "s": 55372, "text": "You can now see the order in which all these controls are added to this dialog box. To Change the order or sequence of controls, click on all the controls in sequence in which you want to navigate." }, { "code": null, "e": 55728, "s": 55570, "text": "In this example, we will first click on the checkbox followed by Name and Address Edit controls. Then click OK and Cancel as shown in the following snapshot." }, { "code": null, "e": 55795, "s": 55728, "text": "Let us run this application and you will see the following output." }, { "code": null, "e": 56120, "s": 55795, "text": "In MFC applications, after visually adding a control to your application, if you want to refer to it in your code, you can declare a variable based on, or associated with that control. The MFC library allows you to declare two types of variables for some of the controls used in an application a value or a control variable." }, { "code": null, "e": 56234, "s": 56120, "text": "One variable is used for the information stored in the control, which is also known as Control Variable/Instance." }, { "code": null, "e": 56348, "s": 56234, "text": "One variable is used for the information stored in the control, which is also known as Control Variable/Instance." }, { "code": null, "e": 56479, "s": 56348, "text": "The other variable is known as Control Value Variable. A user can perform some sort of actions on that control with this variable." }, { "code": null, "e": 56610, "s": 56479, "text": "The other variable is known as Control Value Variable. A user can perform some sort of actions on that control with this variable." }, { "code": null, "e": 56749, "s": 56610, "text": "A control variable is a variable based on the class that manages the control. For example, a button control is based on the CButton class." }, { "code": null, "e": 56856, "s": 56749, "text": "To see these concepts in real programming, let us create an MFC dialog based project MFCControlManagement." }, { "code": null, "e": 56943, "s": 56856, "text": "Once the project is created, you will see the following dialog box in designer window." }, { "code": null, "e": 57102, "s": 56943, "text": "Step 1 − Delete the TODO line and drag one checkbox and one Edit control as shown in the following snapshot. Change the caption of checkbox to Enable Control." }, { "code": null, "e": 57140, "s": 57102, "text": "Step 2 − Right-click on the checkbox." }, { "code": null, "e": 57170, "s": 57140, "text": "Step 3 − Select Add Variable." }, { "code": null, "e": 57227, "s": 57170, "text": "Step 4 − You can now see the Add Member Variable Wizard." }, { "code": null, "e": 57370, "s": 57227, "text": "You can select different options on this dialog box. For checkbox, the variable type is CButton. It is selected by default in this dialog box." }, { "code": null, "e": 57559, "s": 57370, "text": "Similarly, the control ID is also selected by default now we need to select Control in the Category combo box, and type m_enableDisableCheck in the Variable Name edit box and click finish." }, { "code": null, "e": 57670, "s": 57559, "text": "Step 5 − Similarly, add Control Variable of Edit control with the settings as shown in the following snapshot." }, { "code": null, "e": 57771, "s": 57670, "text": "Observe the header file of the dialog class. You can see that the new variables have been added now." }, { "code": null, "e": 57824, "s": 57771, "text": "CButton m_enableDisableCheck;\nCEdit m_myEditControl;" }, { "code": null, "e": 57945, "s": 57824, "text": "Another type of variable you can declare for a control is the value variable. Not all controls provide a value variable." }, { "code": null, "e": 58055, "s": 57945, "text": "The value variable must be able to handle the type of value stored in the control it is intended to refer to." }, { "code": null, "e": 58165, "s": 58055, "text": "The value variable must be able to handle the type of value stored in the control it is intended to refer to." }, { "code": null, "e": 58320, "s": 58165, "text": "For example, because a text based control is used to handle text, you can declare a text-based data type for it. This would usually be a CString variable." }, { "code": null, "e": 58475, "s": 58320, "text": "For example, because a text based control is used to handle text, you can declare a text-based data type for it. This would usually be a CString variable." }, { "code": null, "e": 58545, "s": 58475, "text": "Let us look into this type of variable for checkbox and edit control." }, { "code": null, "e": 58607, "s": 58545, "text": "Step 1 − Right-click on the checkbox and select Add Variable." }, { "code": null, "e": 58689, "s": 58607, "text": "Step 2 − The Variable type is BOOL. Select Value from the Category dropdown list." }, { "code": null, "e": 58724, "s": 58689, "text": "Step 3 − Click Finish to continue." }, { "code": null, "e": 58834, "s": 58724, "text": "Step 4 − Similarly, add value Variable for Edit control with the settings as shown in the following snapshot." }, { "code": null, "e": 58922, "s": 58834, "text": "Step 5 − Type CString in variable type and m_editControlVal in the variable name field." }, { "code": null, "e": 58989, "s": 58922, "text": "Step 6 − You can now see these variables added in the Header file." }, { "code": null, "e": 59040, "s": 58989, "text": "bool m_enableDisableVal;\nCString m_editControlVal;" }, { "code": null, "e": 59239, "s": 59040, "text": "After adding a control to your application, whether you visually added it or created it dynamically, you will also decide how to handle the possible actions that the user can perform on the control." }, { "code": null, "e": 59379, "s": 59239, "text": "For project dialog boxes that are already associated with a class, you can take advantage of some shortcuts when you create event handlers." }, { "code": null, "e": 59519, "s": 59379, "text": "For project dialog boxes that are already associated with a class, you can take advantage of some shortcuts when you create event handlers." }, { "code": null, "e": 59641, "s": 59519, "text": "You can quickly create a handler either for the default control notification event or for any applicable Windows message." }, { "code": null, "e": 59763, "s": 59641, "text": "You can quickly create a handler either for the default control notification event or for any applicable Windows message." }, { "code": null, "e": 59843, "s": 59763, "text": "Let us look into the same example in which we added event handler for checkbox." }, { "code": null, "e": 59929, "s": 59843, "text": "Step 1 − Right-click the control for which you want to handle the notification event." }, { "code": null, "e": 60021, "s": 59929, "text": "Step 2 − On the shortcut menu, click Add Event Handler to display the Event Handler Wizard." }, { "code": null, "e": 60123, "s": 60021, "text": "Step 3 − Select the event in the Message type box to add to the class selected in the Class list box." }, { "code": null, "e": 60226, "s": 60123, "text": "Step 4 − Accept the default name in the Function handler name box, or provide the name of your choice." }, { "code": null, "e": 60280, "s": 60226, "text": "Step 5 − Click Add and edit to add the event handler." }, { "code": null, "e": 60380, "s": 60280, "text": "Step 6 − You can now see the following event added at the end of CMFCControlManagementDlg.cpp file." }, { "code": null, "e": 60495, "s": 60380, "text": "void CMFCControlManagementDlg::OnBnClickedCheck1() {\n // TODO: Add your control notification handler code here\n}" }, { "code": null, "e": 60697, "s": 60495, "text": "So far, we have seen how to add controls to an application. We will now see how to manage these controls as per user requirement. We can use the control variable/instance in a particular event handler." }, { "code": null, "e": 60832, "s": 60697, "text": "Step 1 − Let us look into the following example. Here, we will enable/disable the edit control when the checkbox is checked/unchecked." }, { "code": null, "e": 60922, "s": 60832, "text": "Step 2 − We have now added the checkbox click event handler. Here is the implementation −" }, { "code": null, "e": 61178, "s": 60922, "text": "void CMFCControlManagementDlg::OnBnClickedCheck1() {\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n if (m_enableDisableVal)\n m_myEditControl.EnableWindow(TRUE);\n else\n m_myEditControl.EnableWindow(FALSE);\n}" }, { "code": null, "e": 61327, "s": 61178, "text": "Step 3 − When the dialog is created, we need to add the following code to CMFCControlManagementDlg::OnInitDialog(). This will manage these controls." }, { "code": null, "e": 61453, "s": 61327, "text": "UpdateData(TRUE);\nif (m_enableDisableVal)\n m_myEditControl.EnableWindow(TRUE);\nelse\n m_myEditControl.EnableWindow(FALSE);" }, { "code": null, "e": 61536, "s": 61453, "text": "Step 4 − Here is the complete implementation of CMFCControlManagementDlg.cpp file." }, { "code": null, "e": 65828, "s": 61536, "text": "// MFCControlManagementDlg.cpp : implementation file\n//\n\n#include \"stdafx.h\"\n#include \"MFCControlManagement.h\"\n#include \"MFCControlManagementDlg.h\"\n#include \"afxdialogex.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n\n\n// CAboutDlg dialog used for App About\n\nclass CAboutDlg : public CDialogEx {\n public:\n CAboutDlg();\n\t\n // Dialog Data\n #ifdef AFX_DESIGN_TIME\n enum { IDD = IDD_ABOUTBOX };\n #endif\n\n protected:\n virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support\n \n // Implementation\n protected:\n DECLARE_MESSAGE_MAP()\n};\n\nCAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) {\n\n}\nvoid CAboutDlg::DoDataExchange(CDataExchange* pDX) {\n CDialogEx::DoDataExchange(pDX);\n}\n\nBEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)\nEND_MESSAGE_MAP()\n\n// CMFCControlManagementDlg dialog\n\n\nCMFCControlManagementDlg::CMFCControlManagementDlg(CWnd* pParent /* = NULL*/)\n :CDialogEx(IDD_MFCCONTROLMANAGEMENT_DIALOG, pParent) , \n m_enableDisableVal(FALSE) , m_editControlVal(_T(\"\")) {\n m_hIcon = AfxGetApp()&rarr LoadIcon(IDR_MAINFRAME);\n}\n\nvoid CMFCControlManagementDlg::DoDataExchange(CDataExchange* pDX) {\n CDialogEx::DoDataExchange(pDX);\n DDX_Control(pDX, IDC_CHECK1, m_enableDisableCheck);\n DDX_Control(pDX, IDC_EDIT1, m_myEditControl);\n DDX_Check(pDX, IDC_CHECK1, m_enableDisableVal);\n DDX_Text(pDX, IDC_EDIT1, m_editControlVal);\n}\nBEGIN_MESSAGE_MAP(CMFCControlManagementDlg, CDialogEx)\n ON_WM_SYSCOMMAND()\n ON_WM_PAINT()\n ON_WM_QUERYDRAGICON()\n ON_BN_CLICKED(IDC_CHECK1, &CMFCControlManagementDlg::OnBnClickedCheck1)\nEND_MESSAGE_MAP()\n\n// CMFCControlManagementDlg message handlers\n\nBOOL CMFCControlManagementDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n \n // Add \"About...\" menu item to system menu.\n // IDM_ABOUTBOX must be in the system command range.\n ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);\n ASSERT(IDM_ABOUTBOX < 0xF000);\n \n CMenu* pSysMenu = GetSystemMenu(FALSE);\n if (pSysMenu != NULL) {\n BOOL bNameValid;\n CString strAboutMenu;\n bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);\n ASSERT(bNameValid);\n if (!strAboutMenu.IsEmpty()) {\n pSysMenu → AppendMenu(MF_SEPARATOR);\n pSysMenu → AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);\n }\n }\n\t\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n UpdateData(TRUE);\n if (m_enableDisableVal)\n m_myEditControl.EnableWindow(TRUE);\n else\n m_myEditControl.EnableWindow(FALSE);\n return TRUE; // return TRUE unless you set the focus to a control\n}\nvoid CMFCControlManagementDlg::OnSysCommand(UINT nID, LPARAM lParam) {\n if ((nID & 0xFFF0) == IDM_ABOUTBOX) {\n CAboutDlg dlgAbout;\n dlgAbout.DoModal();\n }else {\n CDialogEx::OnSysCommand(nID, lParam);\n }\n}\n\n// If you add a minimize button to your dialog, you will need the code below\n// to draw the icon. For MFC applications using the document/view model,\n// this is automatically done for you by the framework.\n\nvoid CMFCControlManagementDlg::OnPaint() {\n if (IsIconic()) {\n CPaintDC dc(this); // device context for painting\n \n SendMessage(WM_ICONERASEBKGND,\n reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);\n\t\t\t\n // Center icon in client rectangle\n int cxIcon = GetSystemMetrics(SM_CXICON);\n int cyIcon = GetSystemMetrics(SM_CYICON);\n CRect rect;\n GetClientRect(&rect);\n int x = (rect.Width() - cxIcon + 1) / 2;\n int y = (rect.Height() - cyIcon + 1) / 2;\n\t\t\n // Draw the icon\n dc.DrawIcon(x, y, m_hIcon);\n }else {\n CDialogEx::OnPaint();\n }\n}\n\n// The system calls this function to obtain the cursor to display while the user drags\n// the minimized window.\nHCURSOR CMFCControlManagementDlg::OnQueryDragIcon() {\n return static_cast<HCURSOR>(m_hIcon);\n}\n\nvoid CMFCControlManagementDlg::OnBnClickedCheck1() {\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n if (m_enableDisableVal)\n m_myEditControl.EnableWindow(TRUE);\n else\n m_myEditControl.EnableWindow(FALSE);\n}" }, { "code": null, "e": 65992, "s": 65828, "text": "Step 5 − When the above code is compiled and executed, you will see the following output. The checkbox is unchecked by default. This disables the edit control too." }, { "code": null, "e": 66085, "s": 65992, "text": "Step 6 − Check the Enable Control checkbox. This will automatically enable the edit control." }, { "code": null, "e": 66263, "s": 66085, "text": "Windows controls are objects that users can interact with to enter or manipulate data. They commonly appear in dialog boxes or on toolbars. There are various types of controls −" }, { "code": null, "e": 66357, "s": 66263, "text": "A text based control which is used to display text to the user or request text from the user." }, { "code": null, "e": 66451, "s": 66357, "text": "A text based control which is used to display text to the user or request text from the user." }, { "code": null, "e": 66498, "s": 66451, "text": "A list based control displays a list of items." }, { "code": null, "e": 66545, "s": 66498, "text": "A list based control displays a list of items." }, { "code": null, "e": 66613, "s": 66545, "text": "A progress based control is used to show the progress of an action." }, { "code": null, "e": 66681, "s": 66613, "text": "A progress based control is used to show the progress of an action." }, { "code": null, "e": 66802, "s": 66681, "text": "A static control can be used to show colors, a picture or something that does not regularly fit in the above categories." }, { "code": null, "e": 66923, "s": 66802, "text": "A static control can be used to show colors, a picture or something that does not regularly fit in the above categories." }, { "code": null, "e": 67138, "s": 66923, "text": "A static control is an object that displays information to the user without his or her direct intervention. It can be used to show colors, a geometric shape, or a picture such as an icon, a bitmap, or an animation." }, { "code": null, "e": 67397, "s": 67138, "text": "An animation control is a window that displays an Audio clip in AVI format. An AVI clip is a series of bitmap frames, like a movie. Animation controls can only play simple AVI clips, and they do not support sound. It is represented by the CAnimateCtrl class." }, { "code": null, "e": 67511, "s": 67397, "text": "A button is an object that the user clicks to initiate an action. Button control is represented by CButton class." }, { "code": null, "e": 67733, "s": 67511, "text": "A bitmap button displays a picture or a picture and text on its face. This is usually intended to make the button a little explicit. A bitmap button is created using the CBitmapButton class, which is derived from CButton." }, { "code": null, "e": 67993, "s": 67733, "text": "A command button is an enhanced version of the regular button. It displays a green arrow icon on the left, followed by a caption in regular size. Under the main caption, it can display another smaller caption that serves as a hint to provide more information." }, { "code": null, "e": 68252, "s": 67993, "text": "A static control displays a text string, box, rectangle, icon, cursor, bitmap, or enhanced metafile. It is represented by CStatic class. It can be used to label, box, or separateother controls. A static control normally takes no input and provides no output." }, { "code": null, "e": 68640, "s": 68252, "text": "A list box displays a list of items, such as filenames, that the user can view and select. A List box is represented by CListBox class. In a single-selection list box, the user can select only one item. In a multiple-selection list box, a range of items can be selected. When the user selects an item, it is highlighted and the list box sends a notification message to the parent window." }, { "code": null, "e": 68919, "s": 68640, "text": "A combo box consists of a list box combined with either a static control or edit control. it is represented by CComboBox class. The list-box portion of the control may be displayed at all times or may only drop down when the user selects the drop-down arrow next to the control." }, { "code": null, "e": 69108, "s": 68919, "text": "A radio button is a control that appears as a dot surrounded by a round box. In reality, a radio button is accompanied by one or more other radio buttons that appear and behave as a group." }, { "code": null, "e": 69217, "s": 69108, "text": "A checkbox is a Windows control that allows the user to set or change the value of an item as true or false." }, { "code": null, "e": 69451, "s": 69217, "text": "An Image List is a collection of same-sized images, each of which can be referred to by its zero-based index. Image lists are used to efficiently manage large sets of icons or bitmaps. Image lists are represented by CImageList class." }, { "code": null, "e": 69561, "s": 69451, "text": "An Edit Box is a rectangular child window in which the user can enter text. It is represented by CEdit class." }, { "code": null, "e": 69777, "s": 69561, "text": "A Rich Edit Control is a window in which the user can enter and edit text. The text can be assigned character and paragraph formatting, and can include embedded OLE objects. It is represented by CRichEditCtrl class." }, { "code": null, "e": 69930, "s": 69777, "text": "A group box is a static control used to set a visible or programmatic group of controls. The control is a rectangle that groups other controls together." }, { "code": null, "e": 70189, "s": 69930, "text": "A Spin Button Control (also known as an up-down control) is a pair of arrow buttons that the user can click to increment or decrement a value, such as a scroll position or a number displayed in a companion control. it is represented by CSpinButtonCtrl class." }, { "code": null, "e": 70221, "s": 70189, "text": "It manages the Updown Controls." }, { "code": null, "e": 70508, "s": 70221, "text": "A progress bar control is a window that an application can use to indicate the progress of a lengthy operation. It consists of a rectangle that is gradually filled, from left to right, with the system highlight color as an operation progresses. It is represented by CProgressCtrl class." }, { "code": null, "e": 70605, "s": 70508, "text": "A progress bars is a window that an application can use to indicate the progress of a operation." }, { "code": null, "e": 71064, "s": 70605, "text": "A timer is a non-spatial object that uses recurring lapses of time from a computer or fromyour application. To work, every lapse of period, the control sends a message to the operating system. Unlike most other controls, the MFC timer has neither a button to represent it nor a class. To create a timer, you simply call the CWnd::SetTimer() method. This function call creates a timer for your application. Like the other controls, a timer uses an identifier." }, { "code": null, "e": 71494, "s": 71064, "text": "The date and time picker control (CDateTimeCtrl) implements an intuitive and recognizable method of entering or selecting a specific date. The main interface of the control is similar in functionality to a combo box. However, if the user expands the control, a month calendar control appears (by default), allowing the user to specify a particular date. When a date is chosen, the month calendar control automatically disappears." }, { "code": null, "e": 71605, "s": 71494, "text": "If you need to display a picture for your application, Visual C++ provides a special control for that purpose." }, { "code": null, "e": 71898, "s": 71605, "text": "The Image editor has an extensive set of tools for creating and editing images, as wellas features to help you create toolbar bitmaps. In addition to bitmaps, icons, and cursors, you can edit images in GIF or JPEG format using commands on the Image menu and tools on the Image Editor Toolbar." }, { "code": null, "e": 72239, "s": 71898, "text": "A Slider Control (also known as a trackbar) is a window containing a slider and optional tick marks. When the user moves the slider, using either the mouse or the direction keys, the control sends notification messages to indicate the change. There are two types of sliders − horizontal and vertical. It is represented by CSliderCtrl class." }, { "code": null, "e": 72519, "s": 72239, "text": "A scrollbar is a graphical control element with which continuous text, pictures or anything else can be scrolled in two directions along a control by clicking an arrow. This control can assume one of two directions − horizontal or vertical. It is represented by CScrollBar class." }, { "code": null, "e": 72946, "s": 72519, "text": "A Tree View Control is a window that displays a hierarchical list of items, such as the headings in a document, the entries in an index, or the files and directories on a disk. Each item consists of a label and an optional bitmapped image, and each item can have a list of subitems associated with it. By clicking an item, the user can expand and collapse the associated list of subitems. It is represented by CTreeCtrl class." }, { "code": null, "e": 73216, "s": 72946, "text": "Encapsulates the functionality of a List View Control, which displays a collection of items each consisting of an icon (from an image list) and a label. It is represented by CListCtrl class. A list control consists of using one of four views to display a list of items." }, { "code": null, "e": 73603, "s": 73216, "text": "An application is made of various objects. Most of the time, more than one application is running on the computer and the operating system is constantly asked to perform some assignments. Because there can be so many requests presented unpredictably, the operating system leaves it up to the objects to specify what they want, when they want it, and what behavior or result they expect." }, { "code": null, "e": 73777, "s": 73603, "text": "The Microsoft Windows operating system cannot predict what kinds of requests one object would need to be taken care of and what type of assignment another object would need." }, { "code": null, "e": 73951, "s": 73777, "text": "The Microsoft Windows operating system cannot predict what kinds of requests one object would need to be taken care of and what type of assignment another object would need." }, { "code": null, "e": 74024, "s": 73951, "text": "To manage all these assignments and requests, the objects send messages." }, { "code": null, "e": 74097, "s": 74024, "text": "To manage all these assignments and requests, the objects send messages." }, { "code": null, "e": 74174, "s": 74097, "text": "Each object has the responsibility to decided what message to send and when." }, { "code": null, "e": 74251, "s": 74174, "text": "Each object has the responsibility to decided what message to send and when." }, { "code": null, "e": 74311, "s": 74251, "text": "In order to send a message, a control must create an event." }, { "code": null, "e": 74371, "s": 74311, "text": "In order to send a message, a control must create an event." }, { "code": null, "e": 74484, "s": 74371, "text": "To make a distinction between the two, a message's name usually starts with WM_ which stands for Window Message." }, { "code": null, "e": 74597, "s": 74484, "text": "To make a distinction between the two, a message's name usually starts with WM_ which stands for Window Message." }, { "code": null, "e": 74668, "s": 74597, "text": "The name of an event usually starts with On which indicates an action." }, { "code": null, "e": 74739, "s": 74668, "text": "The name of an event usually starts with On which indicates an action." }, { "code": null, "e": 74787, "s": 74739, "text": "The event is the action of sending the message." }, { "code": null, "e": 74835, "s": 74787, "text": "The event is the action of sending the message." }, { "code": null, "e": 75109, "s": 74835, "text": "Since Windows is a message-oriented operating system, a large portion of programming for the Windows environment involves message handling. Each time an event such as a keystroke or mouse click occurs, a message is sent to the application, which must then handle the event." }, { "code": null, "e": 75195, "s": 75109, "text": "For the compiler to manage messages, they should be included in the class definition." }, { "code": null, "e": 75281, "s": 75195, "text": "For the compiler to manage messages, they should be included in the class definition." }, { "code": null, "e": 75397, "s": 75281, "text": "The DECLARE_MESSAGE_MAP macro should be provided at the end of the class definition as shown in the following code." }, { "code": null, "e": 75513, "s": 75397, "text": "The DECLARE_MESSAGE_MAP macro should be provided at the end of the class definition as shown in the following code." }, { "code": null, "e": 75627, "s": 75513, "text": "class CMainFrame : public CFrameWnd {\n public:\n CMainFrame();\n protected:\n DECLARE_MESSAGE_MAP()\n};" }, { "code": null, "e": 75705, "s": 75627, "text": "The actual messages should be listed just above the DECLARE_MESSAGE_MAP line." }, { "code": null, "e": 75783, "s": 75705, "text": "The actual messages should be listed just above the DECLARE_MESSAGE_MAP line." }, { "code": null, "e": 75877, "s": 75783, "text": "To implement the messages, you need to create a table of messages that your program is using." }, { "code": null, "e": 75971, "s": 75877, "text": "To implement the messages, you need to create a table of messages that your program is using." }, { "code": null, "e": 76010, "s": 75971, "text": "This table uses two delimiting macros;" }, { "code": null, "e": 76049, "s": 76010, "text": "This table uses two delimiting macros;" }, { "code": null, "e": 76126, "s": 76049, "text": "Its starts with a BEGIN_MESSAGE_MAP and ends with an END_MESSAGE_MAP macros." }, { "code": null, "e": 76203, "s": 76126, "text": "Its starts with a BEGIN_MESSAGE_MAP and ends with an END_MESSAGE_MAP macros." }, { "code": null, "e": 76353, "s": 76203, "text": "The BEGIN_MESSAGE_MAP macro takes two arguments, the name of your class and the MFC class you derived your class from as shown in the following code." }, { "code": null, "e": 76503, "s": 76353, "text": "The BEGIN_MESSAGE_MAP macro takes two arguments, the name of your class and the MFC class you derived your class from as shown in the following code." }, { "code": null, "e": 77141, "s": 76503, "text": "#include <afxwin.h>\nclass CMainFrame : public CFrameWnd {\n public:\n CMainFrame();\n protected:\n DECLARE_MESSAGE_MAP()\n};\nCMainFrame::CMainFrame() {\n\n // Create the window's frame\n Create(NULL, L\"MFC Messages Demo\", WS_OVERLAPPEDWINDOW,\n CRect(120, 100, 700, 480), NULL);\n}\nclass CMessagesApp : public CWinApp {\n public:\n BOOL InitInstance();\n};\nBEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)\nEND_MESSAGE_MAP()\nBOOL CMessagesApp::InitInstance(){\n m_pMainWnd = new CMainFrame;\n m_pMainWnd->ShowWindow(SW_SHOW);\n m_pMainWnd->UpdateWindow();\n return TRUE;\n}\nCMessagesApp theApp;" }, { "code": null, "e": 77208, "s": 77141, "text": "Let us look into a simple example by creating a new Win32 project." }, { "code": null, "e": 77293, "s": 77208, "text": "Step 1 − To create an MFC project, right-click on the project and select Properties." }, { "code": null, "e": 77365, "s": 77293, "text": "Step 2 − In the left section, click Configuration Properties → General." }, { "code": null, "e": 77458, "s": 77365, "text": "Step 3 − Select the ‘Use MFC in Shared DLL’ option in Project Defaults section and click OK." }, { "code": null, "e": 77501, "s": 77458, "text": "Step 4 − We need to add a new source file." }, { "code": null, "e": 77565, "s": 77501, "text": "Step 5 − Right-click on your Project and select Add → New Item." }, { "code": null, "e": 77623, "s": 77565, "text": "Step 6 − In the Templates section, click C++ File (.cpp)." }, { "code": null, "e": 77655, "s": 77623, "text": "Step 7 − Click Add to Continue." }, { "code": null, "e": 77711, "s": 77655, "text": "Step 8 − Now, add the following code in the *.cpp file." }, { "code": null, "e": 78320, "s": 77711, "text": "#include <afxwin.h>\nclass CMainFrame : public CFrameWnd {\n public:\n CMainFrame();\n protected:\n DECLARE_MESSAGE_MAP()\n};\n\nCMainFrame::CMainFrame() {\n // Create the window's frame\n Create(NULL, L\"MFC Messages Demo\", WS_OVERLAPPEDWINDOW,\n CRect(120, 100, 700, 480), NULL);\n}\n\nclass CMessagesApp : public CWinApp {\n public:\n BOOL InitInstance();\n};\n\nBEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)\nEND_MESSAGE_MAP()\nBOOL CMessagesApp::InitInstance() {\n m_pMainWnd = new CMainFrame;\n m_pMainWnd->ShowWindow(SW_SHOW);\n m_pMainWnd->UpdateWindow();\n return TRUE;\n}\nCMessagesApp theApp;" }, { "code": null, "e": 78465, "s": 78320, "text": "There are different types of Windows messages like creating a window, showing a window etc. Here are some of the commonly used windows messages." }, { "code": null, "e": 78519, "s": 78465, "text": "Let us look into a simple example of window creation." }, { "code": null, "e": 78655, "s": 78519, "text": "WM_CREATE − When an object, called a window, is created, the frame that creates the objects sends a message identified as ON_WM_CREATE." }, { "code": null, "e": 78794, "s": 78655, "text": "Step 1 − To create ON_WM_CREATE, add afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); before the DECLARE_MESSAGE_MAP() as shown below." }, { "code": null, "e": 78967, "s": 78794, "text": "class CMainFrame : public CFrameWnd {\n public:\n CMainFrame();\n protected:\n afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);\n DECLARE_MESSAGE_MAP()\n};" }, { "code": null, "e": 79079, "s": 78967, "text": "Step 2 − Add the ON_WM_CREATE() after the BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) and before END_MESSAGE_MAP()" }, { "code": null, "e": 79156, "s": 79079, "text": "BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)\n ON_WM_CREATE()\nEND_MESSAGE_MAP()" }, { "code": null, "e": 79206, "s": 79156, "text": "Step 3 − Here is the Implementation of OnCreate()" }, { "code": null, "e": 79608, "s": 79206, "text": "int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) {\n // Call the base class to create the window\n if (CFrameWnd::OnCreate(lpCreateStruct) == 0) {\n\n // If the window was successfully created, let the user know\n MessageBox(L\"The window has been created!!!\");\n // Since the window was successfully created, return 0\n return 0;\n }\n // Otherwise, return -1\n return -1;\n}" }, { "code": null, "e": 79684, "s": 79608, "text": "Step 4 − Now your *.cpp file will look like as shown in the following code." }, { "code": null, "e": 80774, "s": 79684, "text": "#include <afxwin.h>\nclass CMainFrame : public CFrameWnd {\n public:\n CMainFrame();\n protected:\n afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);\n DECLARE_MESSAGE_MAP()\n};\nCMainFrame::CMainFrame() {\n\n // Create the window's frame\n Create(NULL, L\"MFC Messages Demo\", WS_OVERLAPPEDWINDOW,\n CRect(120, 100, 700, 480), NULL);\n}\nclass CMessagesApp : public CWinApp {\n public:\n BOOL InitInstance();\n};\nBEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)\n ON_WM_CREATE()\nEND_MESSAGE_MAP()\nint CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) {\n // Call the base class to create the window\n if (CFrameWnd::OnCreate(lpCreateStruct) == 0) {\n // If the window was successfully created, let the user know\n MessageBox(L\"The window has been created!!!\");\n // Since the window was successfully created, return 0\n return 0;\n }\n // Otherwise, return -1\n return -1;\n}\nBOOL CMessagesApp::InitInstance() { \n m_pMainWnd = new CMainFrame;\n m_pMainWnd -> ShowWindow(SW_SHOW);\n m_pMainWnd -> UpdateWindow();\n return TRUE;\n}\nCMessagesApp theApp;" }, { "code": null, "e": 80864, "s": 80774, "text": "Step 5 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 80925, "s": 80864, "text": "Step 6 − When you click OK, it will display the main window." }, { "code": null, "e": 81155, "s": 80925, "text": "One of the main features of a graphical application is to present Windows controls and resources that allow the user to interact with the machine. Examples of controls that we will learn are buttons, list boxes, combo boxes, etc." }, { "code": null, "e": 81403, "s": 81155, "text": "One type of resource we introduced in the previous lesson is the menu. Such controls and resources can initiate their own messages when the user clicks them. A message that emanates from a Windows control or a resource is called a command message." }, { "code": null, "e": 81458, "s": 81403, "text": "Let us look into a simple example of Command messages." }, { "code": null, "e": 81575, "s": 81458, "text": "To provide your application the ability to create a new document, the CWinApp class provides the OnFileNew() method." }, { "code": null, "e": 81711, "s": 81575, "text": "afx_msg void OnFileNew();\n\nBEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)\n ON_COMMAND(ID_FILE_NEW, CMainFrame::OnFileNew)\nEND_MESSAGE_MAP()" }, { "code": null, "e": 81743, "s": 81711, "text": "Here is the method definition −" }, { "code": null, "e": 81798, "s": 81743, "text": "void CMainFrame::OnFileNew() {\n // Create New file\n}" }, { "code": null, "e": 82161, "s": 81798, "text": "A keyboard is a hardware object attached to the computer. By default, it is used to enter recognizable symbols, letters, and other characters on a control. Each key on the keyboard displays a symbol, a letter, or a combination of those, to give an indication of what the key could be used for. The user typically presses a key, which sends a signal to a program." }, { "code": null, "e": 82266, "s": 82161, "text": "Each key has a code that the operating system can recognize. This code is known as the virtual key code." }, { "code": null, "e": 82277, "s": 82266, "text": "VK_LBUTTON" }, { "code": null, "e": 82295, "s": 82277, "text": "Left mouse button" }, { "code": null, "e": 82306, "s": 82295, "text": "VK_RBUTTON" }, { "code": null, "e": 82325, "s": 82306, "text": "Right mouse button" }, { "code": null, "e": 82335, "s": 82325, "text": "VK_CANCEL" }, { "code": null, "e": 82360, "s": 82335, "text": "Control-break processing" }, { "code": null, "e": 82371, "s": 82360, "text": "VK_MBUTTON" }, { "code": null, "e": 82412, "s": 82371, "text": "Middle mouse button (three-button mouse)" }, { "code": null, "e": 82420, "s": 82412, "text": "VK_BACK" }, { "code": null, "e": 82434, "s": 82420, "text": "BACKSPACE key" }, { "code": null, "e": 82444, "s": 82434, "text": "VK_RETURN" }, { "code": null, "e": 82454, "s": 82444, "text": "ENTER key" }, { "code": null, "e": 82461, "s": 82454, "text": "VK_TAB" }, { "code": null, "e": 82469, "s": 82461, "text": "TAB key" }, { "code": null, "e": 82478, "s": 82469, "text": "VK_CLEAR" }, { "code": null, "e": 82488, "s": 82478, "text": "CLEAR key" }, { "code": null, "e": 82497, "s": 82488, "text": "VK_SHIFT" }, { "code": null, "e": 82507, "s": 82497, "text": "SHIFT key" }, { "code": null, "e": 82518, "s": 82507, "text": "VK_CONTROL" }, { "code": null, "e": 82527, "s": 82518, "text": "CTRL key" }, { "code": null, "e": 82535, "s": 82527, "text": "VK_MENU" }, { "code": null, "e": 82543, "s": 82535, "text": "ALT key" }, { "code": null, "e": 82552, "s": 82543, "text": "VK_PAUSE" }, { "code": null, "e": 82562, "s": 82552, "text": "PAUSE key" }, { "code": null, "e": 82573, "s": 82562, "text": "VK_CAPITAL" }, { "code": null, "e": 82587, "s": 82573, "text": "CAPS LOCK key" }, { "code": null, "e": 82597, "s": 82587, "text": "VK_ESCAPE" }, { "code": null, "e": 82605, "s": 82597, "text": "ESC key" }, { "code": null, "e": 82614, "s": 82605, "text": "VK_SPACE" }, { "code": null, "e": 82623, "s": 82614, "text": "SPACEBAR" }, { "code": null, "e": 82632, "s": 82623, "text": "VK_PRIOR" }, { "code": null, "e": 82644, "s": 82632, "text": "PAGE UP key" }, { "code": null, "e": 82652, "s": 82644, "text": "VK_NEXT" }, { "code": null, "e": 82666, "s": 82652, "text": "PAGE DOWN key" }, { "code": null, "e": 82673, "s": 82666, "text": "VK_END" }, { "code": null, "e": 82681, "s": 82673, "text": "END key" }, { "code": null, "e": 82689, "s": 82681, "text": "VK_HOME" }, { "code": null, "e": 82698, "s": 82689, "text": "HOME key" }, { "code": null, "e": 82706, "s": 82698, "text": "VK_LEFT" }, { "code": null, "e": 82721, "s": 82706, "text": "LEFT ARROW key" }, { "code": null, "e": 82727, "s": 82721, "text": "VK_UP" }, { "code": null, "e": 82740, "s": 82727, "text": "UP ARROW key" }, { "code": null, "e": 82749, "s": 82740, "text": "VK_RIGHT" }, { "code": null, "e": 82765, "s": 82749, "text": "RIGHT ARROW key" }, { "code": null, "e": 82773, "s": 82765, "text": "VK_DOWN" }, { "code": null, "e": 82788, "s": 82773, "text": "DOWN ARROW key" }, { "code": null, "e": 82798, "s": 82788, "text": "VK_SELECT" }, { "code": null, "e": 82809, "s": 82798, "text": "SELECT key" }, { "code": null, "e": 82818, "s": 82809, "text": "VK_PRINT" }, { "code": null, "e": 82828, "s": 82818, "text": "PRINT key" }, { "code": null, "e": 82839, "s": 82828, "text": "VK_EXECUTE" }, { "code": null, "e": 82851, "s": 82839, "text": "EXECUTE key" }, { "code": null, "e": 82863, "s": 82851, "text": "VK_SNAPSHOT" }, { "code": null, "e": 82880, "s": 82863, "text": "PRINT SCREEN key" }, { "code": null, "e": 82890, "s": 82880, "text": "VK_INSERT" }, { "code": null, "e": 82898, "s": 82890, "text": "INS key" }, { "code": null, "e": 82908, "s": 82898, "text": "VK_DELETE" }, { "code": null, "e": 82916, "s": 82908, "text": "DEL key" }, { "code": null, "e": 82927, "s": 82916, "text": "VK_NUMPAD0" }, { "code": null, "e": 82948, "s": 82927, "text": "Numeric keypad 0 key" }, { "code": null, "e": 82959, "s": 82948, "text": "VK_NUMPAD1" }, { "code": null, "e": 82980, "s": 82959, "text": "Numeric keypad 1 key" }, { "code": null, "e": 82991, "s": 82980, "text": "VK_NUMPAD2" }, { "code": null, "e": 83012, "s": 82991, "text": "Numeric keypad 2 key" }, { "code": null, "e": 83023, "s": 83012, "text": "VK_NUMPAD3" }, { "code": null, "e": 83044, "s": 83023, "text": "Numeric keypad 3 key" }, { "code": null, "e": 83055, "s": 83044, "text": "VK_NUMPAD4" }, { "code": null, "e": 83076, "s": 83055, "text": "Numeric keypad 4 key" }, { "code": null, "e": 83087, "s": 83076, "text": "VK_NUMPAD5" }, { "code": null, "e": 83108, "s": 83087, "text": "Numeric keypad 5 key" }, { "code": null, "e": 83119, "s": 83108, "text": "VK_NUMPAD6" }, { "code": null, "e": 83140, "s": 83119, "text": "Numeric keypad 6 key" }, { "code": null, "e": 83151, "s": 83140, "text": "VK_NUMPAD7" }, { "code": null, "e": 83172, "s": 83151, "text": "Numeric keypad 7 key" }, { "code": null, "e": 83183, "s": 83172, "text": "VK_NUMPAD8" }, { "code": null, "e": 83204, "s": 83183, "text": "Numeric keypad 8 key" }, { "code": null, "e": 83215, "s": 83204, "text": "VK_NUMPAD9" }, { "code": null, "e": 83236, "s": 83215, "text": "Numeric keypad 9 key" }, { "code": null, "e": 83248, "s": 83236, "text": "VK_MULTIPLY" }, { "code": null, "e": 83261, "s": 83248, "text": "Multiply key" }, { "code": null, "e": 83268, "s": 83261, "text": "VK_ADD" }, { "code": null, "e": 83276, "s": 83268, "text": "Add key" }, { "code": null, "e": 83289, "s": 83276, "text": "VK_SEPARATOR" }, { "code": null, "e": 83303, "s": 83289, "text": "Separator key" }, { "code": null, "e": 83315, "s": 83303, "text": "VK_SUBTRACT" }, { "code": null, "e": 83328, "s": 83315, "text": "Subtract key" }, { "code": null, "e": 83339, "s": 83328, "text": "VK_DECIMAL" }, { "code": null, "e": 83351, "s": 83339, "text": "Decimal key" }, { "code": null, "e": 83361, "s": 83351, "text": "VK_DIVIDE" }, { "code": null, "e": 83372, "s": 83361, "text": "Divide key" }, { "code": null, "e": 83378, "s": 83372, "text": "VK_F1" }, { "code": null, "e": 83385, "s": 83378, "text": "F1 key" }, { "code": null, "e": 83391, "s": 83385, "text": "VK_F2" }, { "code": null, "e": 83398, "s": 83391, "text": "F2 key" }, { "code": null, "e": 83404, "s": 83398, "text": "VK_F3" }, { "code": null, "e": 83411, "s": 83404, "text": "F3 key" }, { "code": null, "e": 83417, "s": 83411, "text": "VK_F4" }, { "code": null, "e": 83424, "s": 83417, "text": "F4 key" }, { "code": null, "e": 83430, "s": 83424, "text": "VK_F5" }, { "code": null, "e": 83437, "s": 83430, "text": "F5 key" }, { "code": null, "e": 83443, "s": 83437, "text": "VK_F6" }, { "code": null, "e": 83450, "s": 83443, "text": "F6 key" }, { "code": null, "e": 83456, "s": 83450, "text": "VK_F7" }, { "code": null, "e": 83463, "s": 83456, "text": "F7 key" }, { "code": null, "e": 83469, "s": 83463, "text": "VK_F8" }, { "code": null, "e": 83476, "s": 83469, "text": "F8 key" }, { "code": null, "e": 83482, "s": 83476, "text": "VK_F9" }, { "code": null, "e": 83489, "s": 83482, "text": "F9 key" }, { "code": null, "e": 83496, "s": 83489, "text": "VK_F10" }, { "code": null, "e": 83504, "s": 83496, "text": "F10 key" }, { "code": null, "e": 83511, "s": 83504, "text": "VK_F11" }, { "code": null, "e": 83519, "s": 83511, "text": "F11 key" }, { "code": null, "e": 83526, "s": 83519, "text": "VK_F12" }, { "code": null, "e": 83534, "s": 83526, "text": "F12 key" }, { "code": null, "e": 83545, "s": 83534, "text": "VK_NUMLOCK" }, { "code": null, "e": 83558, "s": 83545, "text": "NUM LOCK key" }, { "code": null, "e": 83568, "s": 83558, "text": "VK_SCROLL" }, { "code": null, "e": 83584, "s": 83568, "text": "SCROLL LOCK key" }, { "code": null, "e": 83594, "s": 83584, "text": "VK_LSHIFT" }, { "code": null, "e": 83609, "s": 83594, "text": "Left SHIFT key" }, { "code": null, "e": 83619, "s": 83609, "text": "VK_RSHIFT" }, { "code": null, "e": 83635, "s": 83619, "text": "Right SHIFT key" }, { "code": null, "e": 83647, "s": 83635, "text": "VK_LCONTROL" }, { "code": null, "e": 83664, "s": 83647, "text": "Left CONTROL key" }, { "code": null, "e": 83676, "s": 83664, "text": "VK_RCONTROL" }, { "code": null, "e": 83694, "s": 83676, "text": "Right CONTROL key" }, { "code": null, "e": 83823, "s": 83694, "text": "Pressing a key causes a WM_KEYDOWN or WM_SYSKEYDOWN message to be placed in the thread message. This can be defined as follows −" }, { "code": null, "e": 83886, "s": 83823, "text": "afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);" }, { "code": null, "e": 83921, "s": 83886, "text": "Let us look into a simple example." }, { "code": null, "e": 83951, "s": 83921, "text": "Step 1 − Here is the message." }, { "code": null, "e": 84047, "s": 83951, "text": "BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)\n ON_WM_CREATE()\n ON_WM_KEYDOWN()\nEND_MESSAGE_MAP()" }, { "code": null, "e": 84099, "s": 84047, "text": "Step 2 − Here is the implementation of OnKeyDown()." }, { "code": null, "e": 84501, "s": 84099, "text": "void CMainFrame::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) {\n switch (nChar) {\n\n case VK_RETURN:\n MessageBox(L\"You pressed Enter\");\n break;\n case VK_F1:\n MessageBox(L\"Help is not available at the moment\");\n break;\n case VK_DELETE:\n MessageBox(L\"Can't Delete This\");\n break;\n default:\n MessageBox(L\"Whatever\");\n }\n}" }, { "code": null, "e": 84591, "s": 84501, "text": "Step 3 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 84661, "s": 84591, "text": "Step 4 − When you press Enter, it will display the following message." }, { "code": null, "e": 84770, "s": 84661, "text": "The mouse is another object that is attached to the computer allowing the user to interact with the machine." }, { "code": null, "e": 84936, "s": 84770, "text": "If the left mouse button was pressed, an ON_WM_LBUTTONDOWN message is sent. The syntax of this message is − \n\nafx_msg void OnLButtonDown(UINT nFlags, CPoint point)\n\n" }, { "code": null, "e": 85045, "s": 84936, "text": "If the left mouse button was pressed, an ON_WM_LBUTTONDOWN message is sent. The syntax of this message is − " }, { "code": null, "e": 85099, "s": 85045, "text": "afx_msg void OnLButtonDown(UINT nFlags, CPoint point)" }, { "code": null, "e": 85153, "s": 85099, "text": "afx_msg void OnLButtonDown(UINT nFlags, CPoint point)" }, { "code": null, "e": 85303, "s": 85153, "text": "If the right mouse button was pressed, an ON_WM_RBUTTONDOWN message is sent. Its syntax is −\n\nafx_msg void OnRButtonDown(UINT nFlags, CPoint point)\n\n" }, { "code": null, "e": 85396, "s": 85303, "text": "If the right mouse button was pressed, an ON_WM_RBUTTONDOWN message is sent. Its syntax is −" }, { "code": null, "e": 85450, "s": 85396, "text": "afx_msg void OnRButtonDown(UINT nFlags, CPoint point)" }, { "code": null, "e": 85504, "s": 85450, "text": "afx_msg void OnRButtonDown(UINT nFlags, CPoint point)" }, { "code": null, "e": 85659, "s": 85504, "text": "Similarly If the left mouse is being released, the ON_WM_LBUTTONUP message is sent. Its syntax is −\n\nafx_msg void OnLButtonUp(UINT nFlags, CPoint point)\n\n" }, { "code": null, "e": 85759, "s": 85659, "text": "Similarly If the left mouse is being released, the ON_WM_LBUTTONUP message is sent. Its syntax is −" }, { "code": null, "e": 85811, "s": 85759, "text": "afx_msg void OnLButtonUp(UINT nFlags, CPoint point)" }, { "code": null, "e": 85863, "s": 85811, "text": "afx_msg void OnLButtonUp(UINT nFlags, CPoint point)" }, { "code": null, "e": 86009, "s": 85863, "text": "If the right mouse is being released, the ON_WM_TBUTTONUP message is sent. Its syntax is −\n\nafx_msg void OnRButtonUp(UINT nFlags, CPoint point)\n\n" }, { "code": null, "e": 86100, "s": 86009, "text": "If the right mouse is being released, the ON_WM_TBUTTONUP message is sent. Its syntax is −" }, { "code": null, "e": 86152, "s": 86100, "text": "afx_msg void OnRButtonUp(UINT nFlags, CPoint point)" }, { "code": null, "e": 86204, "s": 86152, "text": "afx_msg void OnRButtonUp(UINT nFlags, CPoint point)" }, { "code": null, "e": 86239, "s": 86204, "text": "Let us look into a simple example." }, { "code": null, "e": 86343, "s": 86239, "text": "Step 1 − Add the following two functions in CMainFrame class definition as shown in the following code." }, { "code": null, "e": 86646, "s": 86343, "text": "class CMainFrame : public CFrameWnd {\n public:\n CMainFrame();\n protected:\n afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);\n afx_msg void OnLButtonDown(UINT nFlags, CPoint point);\n afx_msg void OnRButtonUp(UINT nFlags, CPoint point);\n DECLARE_MESSAGE_MAP()\n};" }, { "code": null, "e": 86691, "s": 86646, "text": "Step 2 − Add the following two Message Maps." }, { "code": null, "e": 86813, "s": 86691, "text": "BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)\n ON_WM_KEYDOWN()\n ON_WM_LBUTTONDOWN()\n ON_WM_RBUTTONUP()\nEND_MESSAGE_MAP()" }, { "code": null, "e": 86856, "s": 86813, "text": "Step 3 − Here is the functions definition." }, { "code": null, "e": 87134, "s": 86856, "text": "void CMainFrame::OnLButtonDown(UINT nFlags, CPoint point) { \n CString MsgCoord;\n MsgCoord.Format(L\"Left Button at P(%d, %d)\", point.x, point.y);\n MessageBox(MsgCoord);\n}\nvoid CMainFrame::OnRButtonUp(UINT nFlags, CPoint point) { \n MessageBox(L\"Right Mouse Button Up\");\n}" }, { "code": null, "e": 87209, "s": 87134, "text": "Step 4 − When you run this application, you will see the following output." }, { "code": null, "e": 87273, "s": 87209, "text": "Step 5 − When you click OK, you will see the following message." }, { "code": null, "e": 87402, "s": 87273, "text": "Step 6 − Right-click on this window. Now, when you release the right button of the mouse, it will display the following message." }, { "code": null, "e": 87527, "s": 87402, "text": "An ActiveX control container is a parent program that supplies the environment for an ActiveX (formerly OLE) control to run." }, { "code": null, "e": 87594, "s": 87527, "text": "ActiveX control is a control using Microsoft ActiveX technologies." }, { "code": null, "e": 87661, "s": 87594, "text": "ActiveX control is a control using Microsoft ActiveX technologies." }, { "code": null, "e": 87773, "s": 87661, "text": "ActiveX is not a programming language, but rather a set of rules for how applications should share information." }, { "code": null, "e": 87885, "s": 87773, "text": "ActiveX is not a programming language, but rather a set of rules for how applications should share information." }, { "code": null, "e": 87995, "s": 87885, "text": "Programmers can develop ActiveX controls in a variety of languages, including C, C++, Visual Basic, and Java." }, { "code": null, "e": 88105, "s": 87995, "text": "Programmers can develop ActiveX controls in a variety of languages, including C, C++, Visual Basic, and Java." }, { "code": null, "e": 88233, "s": 88105, "text": "You can create an application capable of containing ActiveX controls with or without MFC, but it is much easier to do with MFC." }, { "code": null, "e": 88361, "s": 88233, "text": "You can create an application capable of containing ActiveX controls with or without MFC, but it is much easier to do with MFC." }, { "code": null, "e": 88455, "s": 88361, "text": "Let us look into simple example of add ActiveX controls in your MFC dialog based application." }, { "code": null, "e": 88548, "s": 88455, "text": "Step 1 − Right-click on the dialog in the designer window and select Insert ActiveX Control." }, { "code": null, "e": 88613, "s": 88548, "text": "Step 2 − Select the Microsoft Picture Clip Control and click OK." }, { "code": null, "e": 88704, "s": 88613, "text": "Step 3 − Resize the Picture control and in the Properties window, click the Picture field." }, { "code": null, "e": 88775, "s": 88704, "text": "Step 4 − Browse the folder that contains Pictures. Select any picture." }, { "code": null, "e": 88850, "s": 88775, "text": "Step 5 − When you run this application, you will see the following output." }, { "code": null, "e": 88898, "s": 88850, "text": "Let us have a look into another simple example." }, { "code": null, "e": 88957, "s": 88898, "text": "Step 1 − Right-click on the dialog in the designer window." }, { "code": null, "e": 88997, "s": 88957, "text": "Step 2 − Select Insert ActiveX Control." }, { "code": null, "e": 89062, "s": 88997, "text": "Step 3 − Select the Microsoft ProgressBar Control 6.0, click OK." }, { "code": null, "e": 89174, "s": 89062, "text": "Step 4 − Select the progress bar and set its Orientation in the Properties Window to 1 – ccOrientationVertical." }, { "code": null, "e": 89222, "s": 89174, "text": "Step 5 − Add control variable for Progress bar." }, { "code": null, "e": 89276, "s": 89222, "text": "Step 6 − Add the following code in the OnInitDialog()" }, { "code": null, "e": 89347, "s": 89276, "text": "m_progBarCtrl.SetScrollRange(0,100,TRUE);\nm_progBarCtrl.put_Value(53);" }, { "code": null, "e": 89454, "s": 89347, "text": "Step 7 − When you run this application again, you will see the progress bar in Vertical direction as well." }, { "code": null, "e": 89530, "s": 89454, "text": "In this chapter, we will discuss the various components of the file system." }, { "code": null, "e": 89901, "s": 89530, "text": "A drive is a physical device attached to a computer so it can store information. A logical disk, logical volume or virtual disk (VD or vdisk for short) is a virtual device that provides an area of usable storage capacity on one or more physical disk drive(s) in a computer system. A drive can be a hard disk, a CD ROM, a DVD ROM, a flash (USB) drive, a memory card, etc." }, { "code": null, "e": 90000, "s": 89901, "text": "One of the primary operations you will want to perform is to get a list of drives on the computer." }, { "code": null, "e": 90082, "s": 90000, "text": "Let us look into a simple example by creating a new MFC dialog based application." }, { "code": null, "e": 90164, "s": 90082, "text": "Step 1 − Drag one button from the toolbox, change its Caption to Get Drives Info." }, { "code": null, "e": 90260, "s": 90164, "text": "Step 2 − Remove the Caption of Static control (TODO line) and change its ID to IDC_STATIC_TEXT." }, { "code": null, "e": 90325, "s": 90260, "text": "Step 3 − Right-click on the button and select Add Event Handler." }, { "code": null, "e": 90404, "s": 90325, "text": "Step 4 − Select the BN_CLICKED message type and click the Add and Edit button." }, { "code": null, "e": 90473, "s": 90404, "text": "Step 5 − Add the value variable m_strDrives for Static Text control." }, { "code": null, "e": 90652, "s": 90473, "text": "To support drives on a computer, the Win32 library provides the GetLogicalDrives() function of Microsoft Window, which will retrieve a list of all drives on the current computer." }, { "code": null, "e": 90742, "s": 90652, "text": "Step 6 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 90823, "s": 90742, "text": "Step 7 − When you click the button, you can see all the drives on your computer." }, { "code": null, "e": 91055, "s": 90823, "text": "In computing, a directory is a file system cataloging structure which contains references to other computer files, and possibly other directories. Directory is a physical location. It can handle operations not available on a drive." }, { "code": null, "e": 91136, "s": 91055, "text": "Let us look into a simple example by creating a new MFC dialog based application" }, { "code": null, "e": 91262, "s": 91136, "text": "Step 1 − Drag three buttons from the toolbox. Change their Captions to Create Directory, Delete Directory and Move Directory." }, { "code": null, "e": 91364, "s": 91262, "text": "Step 2 − Change the IDs of these buttons to IDC_BUTTON_CREATE, IDC_BUTTON_DELETE and IDC_BUTTON_MOVE." }, { "code": null, "e": 91395, "s": 91364, "text": "Step 3 − Remove the TODO line." }, { "code": null, "e": 91439, "s": 91395, "text": "Step 4 − Add event handler for each button." }, { "code": null, "e": 91535, "s": 91439, "text": "Step 5 − To create a directory, you can call the CreateDirectory() method of the Win32 library." }, { "code": null, "e": 91672, "s": 91535, "text": "Step 6 − Here is the Create button event handler implementation in which we will create one directory and then two more sub directories." }, { "code": null, "e": 92212, "s": 91672, "text": "void CMFCDirectoriesDemoDlg::OnBnClickedButtonCreate() {\n // TODO: Add your control notification handler code here\n SECURITY_ATTRIBUTES saPermissions;\n\n saPermissions.nLength = sizeof(SECURITY_ATTRIBUTES);\n saPermissions.lpSecurityDescriptor = NULL;\n saPermissions.bInheritHandle = TRUE;\n\n if (CreateDirectory(L\"D:\\\\MFCDirectoryDEMO\", &saPermissions) == TRUE)\n AfxMessageBox(L\"The directory was created.\");\n CreateDirectory(L\"D:\\\\MFCDirectoryDEMO\\\\Dir1\", NULL);\n CreateDirectory(L\"D:\\\\MFCDirectoryDEMO\\\\Dir2\", NULL);\n}" }, { "code": null, "e": 92373, "s": 92212, "text": "Step 7 − To get rid of a directory, you can call the RemoveDirectory() function of the Win32 library. Here is the implementation of delete button event handler." }, { "code": null, "e": 92611, "s": 92373, "text": "void CMFCDirectoriesDemoDlg::OnBnClickedButtonDelete() {\n // TODO: Add your control notification handler code here\n if (RemoveDirectory(L\"D:\\\\MFCDirectoryDEMO\\\\Dir1\") == TRUE)\n AfxMessageBox(L\"The directory has been deleted\");\n}" }, { "code": null, "e": 92843, "s": 92611, "text": "Step 8 − If you want to move a directory, you can also call the same MoveFile() function. Here is the implementation of move button event handler in which we will create first new directory and then move the Dir2 to that directory." }, { "code": null, "e": 93145, "s": 92843, "text": "void CMFCDirectoriesDemoDlg::OnBnClickedButtonMove() {\n // TODO: Add your control notification handler code here\n CreateDirectory(L\"D:\\\\MFCDirectory\", NULL);\n\n if (MoveFile(L\"D:\\\\MFCDirectoryDEMO\\\\Dir1\", L\"D:\\\\MFCDirectory\\\\Dir1\") == TRUE)\n AfxMessageBox(L\"The directory has been moved\");\n}" }, { "code": null, "e": 93235, "s": 93145, "text": "Step 9 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 93323, "s": 93235, "text": "Step 10 − When you click the Create Directory button, it will create these directories." }, { "code": null, "e": 93401, "s": 93323, "text": "Step 11 − When you click on Delete Directory button, it will delete the Dir1." }, { "code": null, "e": 93780, "s": 93401, "text": "Most of the file processing in an MFC application is performed in conjunction with a class named CArchive. The CArchive class serves as a relay between the application and the medium used to either store data or make it available. It allows you to save a complex network of objects in a permanent binary form (usually disk storage) that persists after those objects are deleted." }, { "code": null, "e": 93828, "s": 93780, "text": "Here is the list of methods in CArchive class −" }, { "code": null, "e": 93834, "s": 93828, "text": "Abort" }, { "code": null, "e": 93883, "s": 93834, "text": "Closes an archive without throwing an exception." }, { "code": null, "e": 93889, "s": 93883, "text": "Close" }, { "code": null, "e": 93944, "s": 93889, "text": "Flushes unwritten data and disconnects from the CFile." }, { "code": null, "e": 93950, "s": 93944, "text": "Flush" }, { "code": null, "e": 93998, "s": 93950, "text": "Flushes unwritten data from the archive buffer." }, { "code": null, "e": 94006, "s": 93998, "text": "GetFile" }, { "code": null, "e": 94054, "s": 94006, "text": "Gets the CFile object pointer for this archive." }, { "code": null, "e": 94070, "s": 94054, "text": "GetObjectSchema" }, { "code": null, "e": 94172, "s": 94070, "text": "Called from the Serialize function to determine the version of the object that is being deserialized." }, { "code": null, "e": 94186, "s": 94172, "text": "IsBufferEmpty" }, { "code": null, "e": 94275, "s": 94186, "text": "Determines whether the buffer has been emptied during a Windows Sockets receive process." }, { "code": null, "e": 94285, "s": 94275, "text": "IsLoading" }, { "code": null, "e": 94328, "s": 94285, "text": "Determines whether the archive is loading." }, { "code": null, "e": 94338, "s": 94328, "text": "IsStoring" }, { "code": null, "e": 94381, "s": 94338, "text": "Determines whether the archive is storing." }, { "code": null, "e": 94391, "s": 94381, "text": "MapObject" }, { "code": null, "e": 94506, "s": 94391, "text": "Places objects in the map that are not serialized to the file, but that are available for subobjects to reference." }, { "code": null, "e": 94511, "s": 94506, "text": "Read" }, { "code": null, "e": 94528, "s": 94511, "text": "Reads raw bytes." }, { "code": null, "e": 94538, "s": 94528, "text": "ReadClass" }, { "code": null, "e": 94597, "s": 94538, "text": "Reads a class reference previously stored with WriteClass." }, { "code": null, "e": 94608, "s": 94597, "text": "ReadObject" }, { "code": null, "e": 94658, "s": 94608, "text": "Calls an object's Serialize function for loading." }, { "code": null, "e": 94669, "s": 94658, "text": "ReadString" }, { "code": null, "e": 94698, "s": 94669, "text": "Reads a single line of text." }, { "code": null, "e": 94713, "s": 94698, "text": "SerializeClass" }, { "code": null, "e": 94816, "s": 94713, "text": "Reads or writes the class reference to the CArchive object depending on the direction of the CArchive." }, { "code": null, "e": 94830, "s": 94816, "text": "SetLoadParams" }, { "code": null, "e": 94963, "s": 94830, "text": "Sets the size to which the load array grows. Must be called before any object is loaded or before MapObject or ReadObject is called." }, { "code": null, "e": 94979, "s": 94963, "text": "SetObjectSchema" }, { "code": null, "e": 95032, "s": 94979, "text": "Sets the object schema stored in the archive object." }, { "code": null, "e": 95047, "s": 95032, "text": "SetStoreParams" }, { "code": null, "e": 95168, "s": 95047, "text": "Sets the hash table size and the block size of the map used to identify unique objects during the serialization process." }, { "code": null, "e": 95174, "s": 95168, "text": "Write" }, { "code": null, "e": 95192, "s": 95174, "text": "Writes raw bytes." }, { "code": null, "e": 95203, "s": 95192, "text": "WriteClass" }, { "code": null, "e": 95260, "s": 95203, "text": "Writes a reference to the CRuntimeClass to the CArchive." }, { "code": null, "e": 95272, "s": 95260, "text": "WriteObject" }, { "code": null, "e": 95322, "s": 95272, "text": "Calls an object's Serialize function for storing." }, { "code": null, "e": 95334, "s": 95322, "text": "WriteString" }, { "code": null, "e": 95364, "s": 95334, "text": "Writes a single line of text." }, { "code": null, "e": 95426, "s": 95364, "text": "Here is the list of operators used to store and retrieve data" }, { "code": null, "e": 95438, "s": 95426, "text": "operator <<" }, { "code": null, "e": 95489, "s": 95438, "text": "Stores objects and primitive types to the archive." }, { "code": null, "e": 95501, "s": 95489, "text": "operator >>" }, { "code": null, "e": 95553, "s": 95501, "text": "Loads objects and primitive types from the archive." }, { "code": null, "e": 95635, "s": 95553, "text": "Let us look into a simple example by creating a new MFC dialog based application." }, { "code": null, "e": 95718, "s": 95635, "text": "Step 1 − Drag one edit control and two buttons as shown in the following snapshot." }, { "code": null, "e": 95806, "s": 95718, "text": "Step 2 − Add control variable m_editCtrl and value variable m_strEdit for edit control." }, { "code": null, "e": 95866, "s": 95806, "text": "Step 3 − Add click event handler for Open and Save buttons." }, { "code": null, "e": 95921, "s": 95866, "text": "Step 4 − Here is the implementation of event handlers." }, { "code": null, "e": 96728, "s": 95921, "text": "void CMFCFileProcessingDlg::OnBnClickedButtonOpen() {\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n \n CFile file;\n \n file.Open(L\"ArchiveText.rpr\", CFile::modeRead);\n if(file) {\n CArchive ar(&file, CArchive::load);\n \n ar >> m_strEdit;\n \n ar.Close();\n file.Close();\n }\n UpdateData(FALSE);\n}\n\nvoid CMFCFileProcessingDlg::OnBnClickedButtonSave() {\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n\n if (m_strEdit.GetLength() == 0) {\n AfxMessageBox(L\"You must enter the name of the text.\");\n return;\n }\n CFile file;\n \n file.Open(L\"ArchiveText.rpr\", CFile::modeCreate | CFile::modeWrite);\n CArchive ar(&file, CArchive::store);\n ar << m_strEdit;\n \n ar.Close();\n file.Close();\n}" }, { "code": null, "e": 96818, "s": 96728, "text": "Step 5 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 96899, "s": 96818, "text": "Step 6 − Write something and click Save. It will save the data in binary format." }, { "code": null, "e": 97006, "s": 96899, "text": "Step 7 − Remove the test from edit control. As you click Open, observe that the same text is loaded again." }, { "code": null, "e": 97261, "s": 97006, "text": "The MFC library provides its own version of file processing. This is done through a class named CStdioFile. The CStdioFile class is derived from CFile. It can handle the reading and writing of Unicode text files as well as ordinary multi-byte text files." }, { "code": null, "e": 97338, "s": 97261, "text": "Here is the list of constructors, which can initialize a CStdioFile object −" }, { "code": null, "e": 97555, "s": 97338, "text": "CStdioFile();\nCStdioFile(CAtlTransactionManager* pTM);\nCStdioFile(FILE* pOpenStream);\nCStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags);\nCStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags, CAtlTransactionManager* pTM);" }, { "code": null, "e": 97599, "s": 97555, "text": "Here is the list of methods in CStdioFile −" }, { "code": null, "e": 97604, "s": 97599, "text": "Open" }, { "code": null, "e": 97706, "s": 97604, "text": "Overloaded. Open is designed for use with the default CStdioFile constructor (Overrides CFile::Open)." }, { "code": null, "e": 97717, "s": 97706, "text": "ReadString" }, { "code": null, "e": 97746, "s": 97717, "text": "Reads a single line of text." }, { "code": null, "e": 97751, "s": 97746, "text": "Seek" }, { "code": null, "e": 97787, "s": 97751, "text": "Positions the current file pointer." }, { "code": null, "e": 97799, "s": 97787, "text": "WriteString" }, { "code": null, "e": 97829, "s": 97799, "text": "Writes a single line of text." }, { "code": null, "e": 97917, "s": 97829, "text": "Let us look into a simple example again by creating a new MFC dialog based application." }, { "code": null, "e": 98000, "s": 97917, "text": "Step 1 − Drag one edit control and two buttons as shown in the following snapshot." }, { "code": null, "e": 98060, "s": 98000, "text": "Step 2 − Add value variable m_strEditCtrl for edit control." }, { "code": null, "e": 98120, "s": 98060, "text": "Step 3 − Add click event handler for Open and Save buttons." }, { "code": null, "e": 98175, "s": 98120, "text": "Step 4 − Here is the implementation of event handlers." }, { "code": null, "e": 98930, "s": 98175, "text": "void CMFCStandardIODlg::OnBnClickedButtonOpen() {\n \n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n\n CStdioFile file;\n file.Open(L\"D:\\\\MFCDirectoryDEMO\\\\test.txt\", CFile::modeRead | CFile::typeText);\n \n file.ReadString(m_strEditCtrl);\n file.Close();\n UpdateData(FALSE);\n}\n\nvoid CMFCStandardIODlg::OnBnClickedButtonSave() {\n \n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n CStdioFile file;\n if (m_strEditCtrl.GetLength() == 0) {\n\n AfxMessageBox(L\"You must specify the text.\");\n return;\n }\n file.Open(L\"D:\\\\MFCDirectoryDEMO\\\\test.txt\", CFile::modeCreate |\n CFile::modeWrite | CFile::typeText);\n file.WriteString(m_strEditCtrl);\n file.Close();\n}" }, { "code": null, "e": 99020, "s": 98930, "text": "Step 5 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 99098, "s": 99020, "text": "Step 6 − Write something and click Save. It will save the data in *.txt file." }, { "code": null, "e": 99197, "s": 99098, "text": "Step 7 − If you look at the location of the file, you will see that it contains the test.txt file." }, { "code": null, "e": 99308, "s": 99197, "text": "Step 8 − Now, close the application. Run the same application. When you click Open, the same text loads again." }, { "code": null, "e": 99405, "s": 99308, "text": "Step 9 − It starts by opening the file, reading the file, followed by updating the Edit Control." }, { "code": null, "e": 99793, "s": 99405, "text": "The Document/View architecture is the foundation used to create applications based on the Microsoft Foundation Classes library. It allows you to make distinct the different parts that compose a computer program including what the user sees as part of your application and the document a user would work on. This is done through a combination of separate classes that work as an ensemble." }, { "code": null, "e": 99956, "s": 99793, "text": "The parts that compose the Document/View architecture are a frame, one or more documents, and the view. Put together, these entities make up a usable application." }, { "code": null, "e": 100286, "s": 99956, "text": "A view is the platform the user is working on to do his or her job. To let the user do anything on an application, you must provide a view, which is an object based on the CView class. You can either directly use one of the classes derivedfrom CView or you can derive your own custom class from CView or one of its child classes." }, { "code": null, "e": 100485, "s": 100286, "text": "A document is similar to a bucket. For a computer application, a document holds the user's data. To create the document part of this architecture, you must derive an object from the CDocument class." }, { "code": null, "e": 100725, "s": 100485, "text": "As the name suggests, a frame is a combination of the building blocks, the structure, and the borders of an item. A frame gives \"physical\" presence to a window. It also defines the location of an object with regards to the Windows desktop." }, { "code": null, "e": 101099, "s": 100725, "text": "The expression Single Document Interface or SDI refers to a document that can present only one view to the user. This means that the application cannot display more than one document at a time. If you want to view another type of document of the current application, you must create another instance of the application. Notepad and WordPad are examples of SDI applications." }, { "code": null, "e": 101217, "s": 101099, "text": "Let us look into a simple example of single document interface or SDI by creating a new MFC dialog based application." }, { "code": null, "e": 101304, "s": 101217, "text": "Step 1 − Let us create a new MFC Application MFCSDIDemo with below mentioned settings." }, { "code": null, "e": 101399, "s": 101304, "text": "Step 2 − Select Single document from the Application type and MFC standard from Project Style." }, { "code": null, "e": 101434, "s": 101399, "text": "Step 3 − Click Finish to Continue." }, { "code": null, "e": 101531, "s": 101434, "text": "Step 4 − Once the project is created, run the application and you will see the following output." }, { "code": null, "e": 101933, "s": 101531, "text": "An application is referred to as a Multiple Document Interface, or MDI, if the user can open more than one document in the application without closing it. To provide this functionality, the application provides a parent frame that acts as the main frame of the computer program. Inside this frame, the application allows creating views with individual frames, making each view distinct from the other." }, { "code": null, "e": 102053, "s": 101933, "text": "Let us look into a simple example of multiple document interface or MDI by creating a new MFC dialog based application." }, { "code": null, "e": 102140, "s": 102053, "text": "Step 1 − Let us create a new MFC Application MFCMDIDemo with below mentioned settings." }, { "code": null, "e": 102237, "s": 102140, "text": "Step 2 − Select Multiple document from the Application type and MFC standard from Project Style." }, { "code": null, "e": 102272, "s": 102237, "text": "Step 3 − Click Finish to Continue." }, { "code": null, "e": 102369, "s": 102272, "text": "Step 4 − Once the project is created, run the application and you will see the following output." }, { "code": null, "e": 102492, "s": 102369, "text": "Step 5 − When you click on File → New menu option, it will create another child window as shown in the following snapshot." }, { "code": null, "e": 102683, "s": 102492, "text": "Step 6 − In Multiple Document Interface (MDI) applications, there is one main frame per application. In this case, a CMDIFrameWnd, and one CMDIChildWnd derived child frame for each document." }, { "code": null, "e": 102847, "s": 102683, "text": "Strings are objects that represent sequences of characters. The C-style character string originated within the C language and continues to be supported within C++." }, { "code": null, "e": 102955, "s": 102847, "text": "This string is actually a one-dimensional array of characters which is terminated by a null character '\\0'." }, { "code": null, "e": 103063, "s": 102955, "text": "This string is actually a one-dimensional array of characters which is terminated by a null character '\\0'." }, { "code": null, "e": 103157, "s": 103063, "text": "A null-terminated string contains the characters that comprise the string followed by a null." }, { "code": null, "e": 103251, "s": 103157, "text": "A null-terminated string contains the characters that comprise the string followed by a null." }, { "code": null, "e": 103298, "s": 103251, "text": "Here is the simple example of character array." }, { "code": null, "e": 103379, "s": 103298, "text": "char word[12] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\\0' };" }, { "code": null, "e": 103421, "s": 103379, "text": "Following is another way to represent it." }, { "code": null, "e": 103451, "s": 103421, "text": "char word[] = \"Hello, World\";" }, { "code": null, "e": 103596, "s": 103451, "text": "Microsoft Foundation Class (MFC) library provides a class to manipulate string called CString. Following are some important features of CString." }, { "code": null, "e": 103632, "s": 103596, "text": "CString does not have a base class." }, { "code": null, "e": 103668, "s": 103632, "text": "CString does not have a base class." }, { "code": null, "e": 103739, "s": 103668, "text": "A CString object consists of a variable-length sequence of characters." }, { "code": null, "e": 103810, "s": 103739, "text": "A CString object consists of a variable-length sequence of characters." }, { "code": null, "e": 103892, "s": 103810, "text": "CString provides functions and operators using a syntax similar to that of Basic." }, { "code": null, "e": 103974, "s": 103892, "text": "CString provides functions and operators using a syntax similar to that of Basic." }, { "code": null, "e": 104125, "s": 103974, "text": "Concatenation and comparison operators, together with simplified memory management, make CString objects easier to use than ordinary character arrays." }, { "code": null, "e": 104276, "s": 104125, "text": "Concatenation and comparison operators, together with simplified memory management, make CString objects easier to use than ordinary character arrays." }, { "code": null, "e": 104312, "s": 104276, "text": "Here is the constructor of CString." }, { "code": null, "e": 104320, "s": 104312, "text": "CString" }, { "code": null, "e": 104363, "s": 104320, "text": "Constructs CString objects in various ways" }, { "code": null, "e": 104397, "s": 104363, "text": "Here is a list of Array Methods −" }, { "code": null, "e": 104407, "s": 104397, "text": "GetLength" }, { "code": null, "e": 104461, "s": 104407, "text": "Returns the number of characters in a CString object." }, { "code": null, "e": 104469, "s": 104461, "text": "IsEmpty" }, { "code": null, "e": 104524, "s": 104469, "text": "Tests whether a CString object contains no characters." }, { "code": null, "e": 104530, "s": 104524, "text": "Empty" }, { "code": null, "e": 104564, "s": 104530, "text": "Forces a string to have 0 length." }, { "code": null, "e": 104570, "s": 104564, "text": "GetAt" }, { "code": null, "e": 104617, "s": 104570, "text": "Returns the character at a specified position." }, { "code": null, "e": 104623, "s": 104617, "text": "SetAt" }, { "code": null, "e": 104665, "s": 104623, "text": "Sets a character at a specified position." }, { "code": null, "e": 104704, "s": 104665, "text": "Here is a list of Comparison Methods −" }, { "code": null, "e": 104712, "s": 104704, "text": "Compare" }, { "code": null, "e": 104751, "s": 104712, "text": "Compares two strings (case sensitive)." }, { "code": null, "e": 104765, "s": 104751, "text": "CompareNoCase" }, { "code": null, "e": 104806, "s": 104765, "text": "Compares two strings (case insensitive)." }, { "code": null, "e": 104845, "s": 104806, "text": "Here is a list of Extraction Methods −" }, { "code": null, "e": 104849, "s": 104845, "text": "Mid" }, { "code": null, "e": 104918, "s": 104849, "text": "Extracts the middle part of a string (like the Basic MID$ function)." }, { "code": null, "e": 104923, "s": 104918, "text": "Left" }, { "code": null, "e": 104991, "s": 104923, "text": "Extracts the left part of a string (like the Basic LEFT$ function)." }, { "code": null, "e": 104997, "s": 104991, "text": "Right" }, { "code": null, "e": 105067, "s": 104997, "text": "Extracts the right part of a string (like the Basic RIGHT$ function)." }, { "code": null, "e": 105081, "s": 105067, "text": "SpanIncluding" }, { "code": null, "e": 105160, "s": 105081, "text": "Extracts the characters from the string, which are in the given character set." }, { "code": null, "e": 105174, "s": 105160, "text": "SpanExcluding" }, { "code": null, "e": 105256, "s": 105174, "text": "Extracts the characters from the string which are not in the given character set." }, { "code": null, "e": 105294, "s": 105256, "text": "Here is a list of Conversion Methods." }, { "code": null, "e": 105304, "s": 105294, "text": "MakeUpper" }, { "code": null, "e": 105372, "s": 105304, "text": "Converts all the characters in this string to uppercase characters." }, { "code": null, "e": 105382, "s": 105372, "text": "MakeLower" }, { "code": null, "e": 105450, "s": 105382, "text": "Converts all the characters in this string to lowercase characters." }, { "code": null, "e": 105462, "s": 105450, "text": "MakeReverse" }, { "code": null, "e": 105502, "s": 105462, "text": "Reverses the characters in this string." }, { "code": null, "e": 105509, "s": 105502, "text": "Format" }, { "code": null, "e": 105544, "s": 105509, "text": "Format the string as sprintf does." }, { "code": null, "e": 105553, "s": 105544, "text": "TrimLeft" }, { "code": null, "e": 105606, "s": 105553, "text": "Trim leading white-space characters from the string." }, { "code": null, "e": 105616, "s": 105606, "text": "TrimRight" }, { "code": null, "e": 105670, "s": 105616, "text": "Trim trailing white-space characters from the string." }, { "code": null, "e": 105707, "s": 105670, "text": "Here is a list of Searching Methods." }, { "code": null, "e": 105712, "s": 105707, "text": "Find" }, { "code": null, "e": 105767, "s": 105712, "text": "Finds a character or substring inside a larger string." }, { "code": null, "e": 105779, "s": 105767, "text": "ReverseFind" }, { "code": null, "e": 105842, "s": 105779, "text": "Finds a character inside a larger string; starts from the end." }, { "code": null, "e": 105852, "s": 105842, "text": "FindOneOf" }, { "code": null, "e": 105899, "s": 105852, "text": "Finds the first matching character from a set." }, { "code": null, "e": 105940, "s": 105899, "text": "Here is a list of Buffer Access Methods." }, { "code": null, "e": 105950, "s": 105940, "text": "GetBuffer" }, { "code": null, "e": 106002, "s": 105950, "text": "Returns a pointer to the characters in the CString." }, { "code": null, "e": 106021, "s": 106002, "text": "GetBufferSetLength" }, { "code": null, "e": 106109, "s": 106021, "text": "Returns a pointer to the characters in the CString, truncating to the specified length." }, { "code": null, "e": 106123, "s": 106109, "text": "ReleaseBuffer" }, { "code": null, "e": 106177, "s": 106123, "text": "Releases control of the buffer returned by GetBuffer " }, { "code": null, "e": 106187, "s": 106177, "text": "FreeExtra" }, { "code": null, "e": 106294, "s": 106187, "text": "Removes any overhead of this string object by freeing any extra memory previously allocated to the string." }, { "code": null, "e": 106305, "s": 106294, "text": "LockBuffer" }, { "code": null, "e": 106373, "s": 106305, "text": "Disables reference counting and protects the string in the buffer. " }, { "code": null, "e": 106386, "s": 106373, "text": "UnlockBuffer" }, { "code": null, "e": 106453, "s": 106386, "text": "Enables reference counting and releases the string in the buffer. " }, { "code": null, "e": 106497, "s": 106453, "text": "Here is a list of Windows-Specific Methods." }, { "code": null, "e": 106512, "s": 106497, "text": "AllocSysString" }, { "code": null, "e": 106548, "s": 106512, "text": "Allocates a BSTR from CString data." }, { "code": null, "e": 106561, "s": 106548, "text": "SetSysString" }, { "code": null, "e": 106623, "s": 106561, "text": "Sets an existing BSTR object with data from a CString object." }, { "code": null, "e": 106634, "s": 106623, "text": "LoadString" }, { "code": null, "e": 106695, "s": 106634, "text": "Loads an existing CString object from a Windows CE resource." }, { "code": null, "e": 106755, "s": 106695, "text": "Following are the different operations on CString objects −" }, { "code": null, "e": 106854, "s": 106755, "text": "You can create a string by either using a string literal or creating an instance of CString class." }, { "code": null, "e": 107413, "s": 106854, "text": "BOOL CMFCStringDemoDlg::OnInitDialog() {\n\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n CString string1 = _T(\"This is a string1\");\n CString string2(\"This is a string2\");\n\n m_strText.Append(string1 + L\"\\n\");\n m_strText.Append(string2);\n\n UpdateData(FALSE);\n\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 107494, "s": 107413, "text": "When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 107686, "s": 107494, "text": "You can create an empty string by either using an empty string literal or by using CString::Empty() method. You can also check whether a string is empty or not using Boolean property isEmpty." }, { "code": null, "e": 108399, "s": 107686, "text": "BOOL CMFCStringDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n CString string1 = _T(\"\");\n CString string2;\n string2.Empty();\n\n if(string1.IsEmpty())\n m_strText.Append(L\"String1 is empty\\n\");\n else\n m_strText.Append(string1 + L\"\\n\");\n \n if(string2.IsEmpty())\n m_strText.Append(L\"String2 is empty\");\n else\n m_strText.Append(string2);\n UpdateData(FALSE);\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 108479, "s": 108399, "text": "When the above code is compiled and executed you will see the following output." }, { "code": null, "e": 108596, "s": 108479, "text": "To concatenate two or more strings, you can use + operator to concatenate two strings or a CString::Append() method." }, { "code": null, "e": 109312, "s": 108596, "text": "BOOL CMFCStringDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n //To concatenate two CString objects\n CString s1 = _T(\"This \"); // Cascading concatenation\n s1 += _T(\"is a \");\n CString s2 = _T(\"test\");\n CString message = s1;\n message.Append(_T(\"big \") + s2);\n // Message contains \"This is a big test\".\n\n m_strText = L\"message: \" + message;\n\n UpdateData(FALSE);\n\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 109392, "s": 109312, "text": "When the above code is compiled and executed you will see the following output." }, { "code": null, "e": 109530, "s": 109392, "text": "To find the length of the string you can use the CString::GetLength() method, which returns the number of characters in a CString object." }, { "code": null, "e": 110145, "s": 109530, "text": "BOOL CMFCStringDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n \n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n CString string1 = _T(\"This is string 1\");\n int length = string1.GetLength();\n CString strLen;\n\n strLen.Format(L\"\\nString1 contains %d characters\", length);\n m_strText = string1 + strLen;\n\n UpdateData(FALSE);\n\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 110225, "s": 110145, "text": "When the above code is compiled and executed you will see the following output." }, { "code": null, "e": 110282, "s": 110225, "text": "To compare two strings variables you can use == operator" }, { "code": null, "e": 111130, "s": 110282, "text": "BOOL CMFCStringDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n \n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n CString string1 = _T(\"Hello\");\n CString string2 = _T(\"World\");\n\n CString string3 = _T(\"MFC Tutorial\");\n CString string4 = _T(\"MFC Tutorial\");\n\n if (string1 == string2)\n m_strText = \"string1 and string1 are same\\n\";\n else\n m_strText = \"string1 and string1 are not same\\n\";\n\n if (string3 == string4)\n m_strText += \"string3 and string4 are same\";\n else\n m_strText += \"string3 and string4 are not same\";\n\n UpdateData(FALSE);\n\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 111210, "s": 111130, "text": "When the above code is compiled and executed you will see the following output." }, { "code": null, "e": 111424, "s": 111210, "text": "CArray is a collection that is best used for data that is to be accessed in a random or non sequential manner. CArray class supports arrays that are like C arrays, but can dynamically shrink and grow as necessary." }, { "code": null, "e": 111466, "s": 111424, "text": "Array indexes always start at position 0." }, { "code": null, "e": 111508, "s": 111466, "text": "Array indexes always start at position 0." }, { "code": null, "e": 111630, "s": 111508, "text": "You can decide whether to fix the upper bound or enable the array to expand when you add elements past the current bound." }, { "code": null, "e": 111752, "s": 111630, "text": "You can decide whether to fix the upper bound or enable the array to expand when you add elements past the current bound." }, { "code": null, "e": 111837, "s": 111752, "text": "Memory is allocated contiguously to the upper bound, even if some elements are null." }, { "code": null, "e": 111922, "s": 111837, "text": "Memory is allocated contiguously to the upper bound, even if some elements are null." }, { "code": null, "e": 111926, "s": 111922, "text": "Add" }, { "code": null, "e": 111997, "s": 111926, "text": "Adds an element to the end of the array; grows the array if necessary." }, { "code": null, "e": 112004, "s": 111997, "text": "Append" }, { "code": null, "e": 112069, "s": 112004, "text": "Appends another array to the array; grows the array if necessary" }, { "code": null, "e": 112074, "s": 112069, "text": "Copy" }, { "code": null, "e": 112139, "s": 112074, "text": "Copies another array to the array; grows the array if necessary." }, { "code": null, "e": 112149, "s": 112139, "text": "ElementAt" }, { "code": null, "e": 112220, "s": 112149, "text": "Returns a temporary reference to the element pointer within the array." }, { "code": null, "e": 112230, "s": 112220, "text": "FreeExtra" }, { "code": null, "e": 112285, "s": 112230, "text": "Frees all unused memory above the current upper bound." }, { "code": null, "e": 112291, "s": 112285, "text": "GetAt" }, { "code": null, "e": 112346, "s": 112291, "text": "Frees all unused memory above the current upper bound." }, { "code": null, "e": 112355, "s": 112346, "text": "GetCount" }, { "code": null, "e": 112398, "s": 112355, "text": "Gets the number of elements in this array." }, { "code": null, "e": 112406, "s": 112398, "text": "GetData" }, { "code": null, "e": 112459, "s": 112406, "text": "Allows access to elements in the array. Can be NULL." }, { "code": null, "e": 112467, "s": 112459, "text": "GetSize" }, { "code": null, "e": 112510, "s": 112467, "text": "Gets the number of elements in this array." }, { "code": null, "e": 112524, "s": 112510, "text": "GetUpperBound" }, { "code": null, "e": 112557, "s": 112524, "text": "Returns the largest valid index." }, { "code": null, "e": 112566, "s": 112557, "text": "InsertAt" }, { "code": null, "e": 112646, "s": 112566, "text": "Inserts an element (or all the elements in another array) at a specified index." }, { "code": null, "e": 112654, "s": 112646, "text": "IsEmpty" }, { "code": null, "e": 112693, "s": 112654, "text": "Determines whether the array is empty." }, { "code": null, "e": 112703, "s": 112693, "text": "RemoveAll" }, { "code": null, "e": 112745, "s": 112703, "text": "Removes all the elements from this array." }, { "code": null, "e": 112754, "s": 112745, "text": "RemoveAt" }, { "code": null, "e": 112794, "s": 112754, "text": "Removes an element at a specific index." }, { "code": null, "e": 112800, "s": 112794, "text": "SetAt" }, { "code": null, "e": 112861, "s": 112800, "text": "Sets the value for a given index; array not allowed\nto grow." }, { "code": null, "e": 112871, "s": 112861, "text": "SetAtGrow" }, { "code": null, "e": 112935, "s": 112871, "text": "Sets the value for a given index; grows the array if necessary." }, { "code": null, "e": 112943, "s": 112935, "text": "SetSize" }, { "code": null, "e": 113002, "s": 112943, "text": "Sets the number of elements to be contained in this array." }, { "code": null, "e": 113061, "s": 113002, "text": "Following are the different operations on CArray objects −" }, { "code": null, "e": 113276, "s": 113061, "text": "To create a collection of CArray values or objects, you must first decide the type of values of the collection. You can use one of the existing primitive data types such as int, CString, double etc. as shown below;" }, { "code": null, "e": 113310, "s": 113276, "text": "CArray<CString, CString>strArray;" }, { "code": null, "e": 113508, "s": 113310, "text": "To add an item you can use CArray::Add() function. It adds an item at the end of the array. In the OnInitDialog(), CArray object is created and three names are added as shown in the following code." }, { "code": null, "e": 113634, "s": 113508, "text": "CArray<CString, CString>strArray;\n\n//Add names to CArray\nstrArray.Add(L\"Ali\");\nstrArray.Add(L\"Ahmed\");\nstrArray.Add(L\"Mark\");" }, { "code": null, "e": 113766, "s": 113634, "text": "To retrieve any item, you can use the CArray::GetAt() function. This function takes one integer parameter as an index of the array." }, { "code": null, "e": 113843, "s": 113766, "text": "Step 1 − Let us look at a simple example, which will retrieve all the names." }, { "code": null, "e": 113977, "s": 113843, "text": "//Retrive names from CArray\n for (int i = 0; i < strArray.GetSize(); i++) {\n m_strText.Append(strArray.GetAt(i) + L\"\\n\");\n }" }, { "code": null, "e": 114055, "s": 113977, "text": "Step 2 − Here is the complete implementation of CMFCCArrayDlg::OnInitDialog()" }, { "code": null, "e": 114794, "s": 114055, "text": "BOOL CMFCCArrayDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n CArray<CString, CString>strArray;\n \n //Add names to CArray\n strArray.Add(L\"Ali\");\n strArray.Add(L\"Ahmed\");\n strArray.Add(L\"Mark\");\n \n //Retrive names from CArray\n for (int i = 0; i < strArray.GetSize(); i++) {\n m_strText.Append(strArray.GetAt(i) + L\"\\n\");\n }\n \n UpdateData(FALSE);\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 114884, "s": 114794, "text": "Step 3 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 115032, "s": 114884, "text": "To add item in the middle of array you can use the CArray::.InsertAt() function. It takes two paramerters — First, the index and Second, the value." }, { "code": null, "e": 115100, "s": 115032, "text": "Let us insert a new item at index 1 as shown in the following code." }, { "code": null, "e": 115869, "s": 115100, "text": "BOOL CMFCCArrayDlg::OnInitDialog() {\n \n CDialogEx::OnInitDialog();\n \n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n CArray<CString, CString>strArray;\n //Add names to CArray\n strArray.Add(L\"Ali\");\n strArray.Add(L\"Ahmed\");\n strArray.Add(L\"Mark\");\n\n strArray.InsertAt(1, L\"Allan\");\n\n //Retrive names from CArray\n for (int i = 0; i < strArray.GetSize(); i++) {\n m_strText.Append(strArray.GetAt(i) + L\"\\n\");\n }\n\n UpdateData(FALSE);\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 116007, "s": 115869, "text": "When the above code is compiled and executed, you will see the following output. You can now see the name Allan dded as the second index." }, { "code": null, "e": 116155, "s": 116007, "text": "To update item in the middle of array you can use the CArray::.SetAt() function. It takes two paramerters — First, the index and Second, the value." }, { "code": null, "e": 116232, "s": 116155, "text": "Let us update the third element in the array as shown in the following code." }, { "code": null, "e": 117044, "s": 116232, "text": "BOOL CMFCCArrayDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n CArray<CString, CString>strArray;\n\n //Add names to CArray\n strArray.Add(L\"Ali\");\n strArray.Add(L\"Ahmed\");\n strArray.Add(L\"Mark\");\n \n strArray.InsertAt(1, L\"Allan\");\n \n strArray.SetAt(2, L\"Salman\");\n \n //Retrive names from CArray\n for (int i = 0; i < strArray.GetSize(); i++) {\n m_strText.Append(strArray.GetAt(i) + L\"\\n\");\n }\n\n UpdateData(FALSE);\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 117185, "s": 117044, "text": "When the above code is compiled and executed, you will see the following output. You can now see that the value of third element is updated." }, { "code": null, "e": 117275, "s": 117185, "text": "To copy the entire array into another CArray object, you can use CArray::Copy() function." }, { "code": null, "e": 117386, "s": 117275, "text": "Step1 − Let us create another array and copy all the elements from first array as shown in the following code." }, { "code": null, "e": 118813, "s": 117386, "text": "BOOL CMFCCArrayDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Add \"About...\" menu item to system menu.\n\n // IDM_ABOUTBOX must be in the system command range.\n ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);\n ASSERT(IDM_ABOUTBOX < 0xF000);\n CMenu* pSysMenu = GetSystemMenu(FALSE);\n if (pSysMenu != NULL) {\n BOOL bNameValid;\n CString strAboutMenu;\n bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);\n ASSERT(bNameValid);\n if (!strAboutMenu.IsEmpty()) {\n pSysMenu→AppendMenu(MF_SEPARATOR);\n pSysMenu→AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);\n }\n }\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n CArray<CString, CString>strArray;\n //Add names to CArray\n strArray.Add(L\"Ali\");\n strArray.Add(L\"Ahmed\");\n strArray.Add(L\"Mark\");\n\n strArray.InsertAt(1, L\"Allan\");\n\n strArray.SetAt(2, L\"Salman\");\n\n CArray<CString, CString>strArray2;\n strArray2.Copy(strArray);\n //Retrive names from CArray\n for (int i = 0; i < strArray2.GetSize(); i++) {\n m_strText.Append(strArray2.GetAt(i) + L\"\\n\");\n }\n\n UpdateData(FALSE);\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 118946, "s": 118813, "text": "You can now see that we have retrieved element from the 2nd array and the output is the same because we have used the copy function." }, { "code": null, "e": 119101, "s": 118946, "text": "To remove any particular item, you can use CArray::RemoveAt() function. To remove all the element from the list, CArray::RemoveAll() function can be used." }, { "code": null, "e": 119149, "s": 119101, "text": "Let us remove the second element from an array." }, { "code": null, "e": 119912, "s": 119149, "text": "BOOL CMFCCArrayDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n CArray<CString, CString>strArray;\n\n //Add names to CArray\n strArray.Add(L\"Ali\");\n strArray.Add(L\"Ahmed\");\n strArray.Add(L\"Mark\");\n\n strArray.InsertAt(1, L\"Allan\");\n\n strArray.SetAt(2, L\"Salman\");\n\n CArray<CString, CString>strArray2;\n strArray2.Copy(strArray);\n\n strArray2.RemoveAt(1);\n\n //Retrive names from CArray\n for (int i = 0; i < strArray2.GetSize(); i++) {\n m_strText.Append(strArray2.GetAt(i) + L\"\\n\");\n }\n\n UpdateData(FALSE);\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 120061, "s": 119912, "text": "When the above code is compiled and executed, you will see the following output. You can now see that the name Allan is no longer part of the array." }, { "code": null, "e": 120295, "s": 120061, "text": "A linked list is a linear data structure where each element is a separate object. Each element (we will call it a node) of a list comprises two items — the data and a reference to the next node. The last node has a reference to null." }, { "code": null, "e": 120568, "s": 120295, "text": "A linked list is a data structure consisting of a group of nodes which together represent a sequence. It is a way to store data with structures so that the programmer can automatically create a new place to store data whenever necessary. Some of its salient features are −" }, { "code": null, "e": 120625, "s": 120568, "text": "Linked List is a sequence of links which contains items." }, { "code": null, "e": 120682, "s": 120625, "text": "Linked List is a sequence of links which contains items." }, { "code": null, "e": 120731, "s": 120682, "text": "Each link contains a connection to another link." }, { "code": null, "e": 120780, "s": 120731, "text": "Each link contains a connection to another link." }, { "code": null, "e": 120820, "s": 120780, "text": "Each item in the list is called a node." }, { "code": null, "e": 120860, "s": 120820, "text": "Each item in the list is called a node." }, { "code": null, "e": 120963, "s": 120860, "text": "If the list contains at least one node, then a new node is positioned as the last element in the list." }, { "code": null, "e": 121066, "s": 120963, "text": "If the list contains at least one node, then a new node is positioned as the last element in the list." }, { "code": null, "e": 121147, "s": 121066, "text": "If the list has only one node, that node represents the first and the last item." }, { "code": null, "e": 121228, "s": 121147, "text": "If the list has only one node, that node represents the first and the last item." }, { "code": null, "e": 121263, "s": 121228, "text": "There are two types of link list −" }, { "code": null, "e": 121449, "s": 121263, "text": "Singly Linked Lists are a type of data structure. In a singly linked list, each node in the list stores the contents of the node and a pointer or reference to the next node in the list." }, { "code": null, "e": 121678, "s": 121449, "text": "A doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes." }, { "code": null, "e": 121983, "s": 121678, "text": "MFC provides a class CList which is a template linked list implementation and works perfectly. CList lists behave like doubly-linked lists. A variable of type POSITION is a key for the list. You can use a POSITION variable as an iterator to traverse a list sequentially and as a bookmark to hold a place." }, { "code": null, "e": 121991, "s": 121983, "text": "AddHead" }, { "code": null, "e": 122089, "s": 121991, "text": "Adds an element (or all the elements in another list) to the head of the list (makes a new head)." }, { "code": null, "e": 122097, "s": 122089, "text": "AddTail" }, { "code": null, "e": 122195, "s": 122097, "text": "Adds an element (or all the elements in another list) to the tail of the list (makes a new tail)." }, { "code": null, "e": 122200, "s": 122195, "text": "Find" }, { "code": null, "e": 122260, "s": 122200, "text": "Gets the position of an element specified by pointer value." }, { "code": null, "e": 122270, "s": 122260, "text": "FindIndex" }, { "code": null, "e": 122335, "s": 122270, "text": "Gets the position of an element specified by a zero-based index." }, { "code": null, "e": 122341, "s": 122335, "text": "GetAt" }, { "code": null, "e": 122379, "s": 122341, "text": "Gets the element at a given position." }, { "code": null, "e": 122388, "s": 122379, "text": "GetCount" }, { "code": null, "e": 122433, "s": 122388, "text": "Returns the number of elements in this list." }, { "code": null, "e": 122441, "s": 122433, "text": "GetHead" }, { "code": null, "e": 122497, "s": 122441, "text": "Returns the head element of the list (cannot be empty)." }, { "code": null, "e": 122513, "s": 122497, "text": "GetHeadPosition" }, { "code": null, "e": 122567, "s": 122513, "text": "Returns the position of the head element of the list." }, { "code": null, "e": 122575, "s": 122567, "text": "GetNext" }, { "code": null, "e": 122612, "s": 122575, "text": "Gets the next element for iterating." }, { "code": null, "e": 122620, "s": 122612, "text": "GetPrev" }, { "code": null, "e": 122661, "s": 122620, "text": "Gets the previous element for iterating." }, { "code": null, "e": 122669, "s": 122661, "text": "GetSize" }, { "code": null, "e": 122714, "s": 122669, "text": "Returns the number of elements in this list." }, { "code": null, "e": 122722, "s": 122714, "text": "GetTail" }, { "code": null, "e": 122778, "s": 122722, "text": "Returns the tail element of the list (cannot be empty)." }, { "code": null, "e": 122794, "s": 122778, "text": "GetTailPosition" }, { "code": null, "e": 122848, "s": 122794, "text": "Returns the position of the tail element of the list." }, { "code": null, "e": 122860, "s": 122848, "text": "InsertAfter" }, { "code": null, "e": 122906, "s": 122860, "text": "Inserts a new element after a given position." }, { "code": null, "e": 122919, "s": 122906, "text": "InsertBefore" }, { "code": null, "e": 122966, "s": 122919, "text": "Inserts a new element before a given position." }, { "code": null, "e": 122974, "s": 122966, "text": "IsEmpty" }, { "code": null, "e": 123024, "s": 122974, "text": "Tests for the empty list condition (no elements)." }, { "code": null, "e": 123034, "s": 123024, "text": "RemoveAll" }, { "code": null, "e": 123075, "s": 123034, "text": "Removes all the elements from this list." }, { "code": null, "e": 123084, "s": 123075, "text": "RemoveAt" }, { "code": null, "e": 123142, "s": 123084, "text": "Removes an element from this list, specified by position." }, { "code": null, "e": 123153, "s": 123142, "text": "RemoveHead" }, { "code": null, "e": 123200, "s": 123153, "text": "Removes the element from the head of the list." }, { "code": null, "e": 123211, "s": 123200, "text": "RemoveTail" }, { "code": null, "e": 123258, "s": 123211, "text": "Removes the element from the tail of the list." }, { "code": null, "e": 123264, "s": 123258, "text": "SetAt" }, { "code": null, "e": 123302, "s": 123264, "text": "Sets the element at a given position." }, { "code": null, "e": 123360, "s": 123302, "text": "Following are the different operations on CList objects −" }, { "code": null, "e": 123596, "s": 123360, "text": "To create a collection of CList values or objects, you must first decide the type of values of the collection. You can use one of the existing primitive data types such as int, CString, double etc. as shown below in the following code." }, { "code": null, "e": 123625, "s": 123596, "text": "CList<double, double>m_list;" }, { "code": null, "e": 123912, "s": 123625, "text": "To add an item, you can use CList::AddTail() function. It adds an item at the end of the list. To add an element at the start of the list, you can use the CList::AddHead() function. In the OnInitDialog() CList, object is created and four values are added as shown in the following code." }, { "code": null, "e": 124059, "s": 123912, "text": "CList<double, double>m_list;\n\n//Add items to the list\nm_list.AddTail(100.75);\nm_list.AddTail(85.26);\nm_list.AddTail(95.78);\nm_list.AddTail(90.1);\n" }, { "code": null, "e": 124190, "s": 124059, "text": "A variable of type POSITION is a key for the list. You can use a POSITION variable as an iterator to traverse a list sequentially." }, { "code": null, "e": 124304, "s": 124190, "text": "Step 1 − To retrieve the element from the list, we can use the following code which will retrieve all the values." }, { "code": null, "e": 124504, "s": 124304, "text": "//iterate the list\nPOSITION pos = m_list.GetHeadPosition();\nwhile (pos) { \n double nData = m_list.GetNext(pos);\n CString strVal;\n strVal.Format(L\"%.2f\\n\", nData);\n m_strText.Append(strVal);\n}" }, { "code": null, "e": 124577, "s": 124504, "text": "Step 2 − Here is the complete CMFCCListDemoDlg::OnInitDialog() function." }, { "code": null, "e": 125418, "s": 124577, "text": "BOOL CMFCCListDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n CList<double, double>m_list;\n\n //Add items to the list\n m_list.AddTail(100.75);\n m_list.AddTail(85.26);\n m_list.AddTail(95.78);\n m_list.AddTail(90.1);\n\n //iterate the list\n POSITION pos = m_list.GetHeadPosition();\n while (pos) {\n double nData = m_list.GetNext(pos);\n CString strVal;\n strVal.Format(L\"%.f\\n\", nData);\n m_strText.Append(strVal);\n }\n\n UpdateData(FALSE);\n \n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 125508, "s": 125418, "text": "Step 3 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 125717, "s": 125508, "text": "To add item in the middle of the list, you can use the CList::.InsertAfter() and CList::.InsertBefore() functions. It takes two paramerters — First, the position (where it can be added) and Second, the value." }, { "code": null, "e": 125782, "s": 125717, "text": "Step 1 − Let us insert a new item as shown in the followng code." }, { "code": null, "e": 126748, "s": 125782, "text": "BOOL CMFCCListDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n \n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n CList<double, double>m_list;\n\n //Add items to the list\n m_list.AddTail(100.75);\n m_list.AddTail(85.26);\n m_list.AddTail(95.78);\n m_list.AddTail(90.1);\n\n POSITION position = m_list.Find(85.26);\n m_list.InsertBefore(position, 200.0);\n m_list.InsertAfter(position, 300.0);\n\n //iterate the list\n POSITION pos = m_list.GetHeadPosition();\n while (pos) {\n double nData = m_list.GetNext(pos);\n CString strVal;\n strVal.Format(L\"%.2f\\n\", nData);\n m_strText.Append(strVal);\n }\n\n UpdateData(FALSE);\n\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 126900, "s": 126748, "text": "Step 2 − You can now see see that we first retrieved the position of value 85.26 and then inserted one element before and one element after that value." }, { "code": null, "e": 126990, "s": 126900, "text": "Step 3 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 127142, "s": 126990, "text": "To update item at the middle of array, you can use the CArray::.SetAt() function. It takes two paramerters — First, the position and Second, the value." }, { "code": null, "e": 127218, "s": 127142, "text": "Let us update the 300.00 to 400 in the list as shown in the following code." }, { "code": null, "e": 128255, "s": 127218, "text": "BOOL CMFCCListDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n CList<double, double>m_list;\n\n //Add items to the list\n m_list.AddTail(100.75);\n m_list.AddTail(85.26);\n m_list.AddTail(95.78);\n m_list.AddTail(90.1);\n\n POSITION position = m_list.Find(85.26);\n m_list.InsertBefore(position, 200.0);\n m_list.InsertAfter(position, 300.0);\n\n position = m_list.Find(300.00);\n m_list.SetAt(position, 400.00);\n\n //iterate the list\n POSITION pos = m_list.GetHeadPosition();\n while (pos) {\n double nData = m_list.GetNext(pos);\n CString strVal;\n strVal.Format(L\"%.2f\\n\", nData);\n m_strText.Append(strVal);\n }\n\n UpdateData(FALSE);\n\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 128399, "s": 128255, "text": "When the above code is compiled and executed, you will see the following output. You can now see that the value of 300.00 is updated to 400.00." }, { "code": null, "e": 128552, "s": 128399, "text": "To remove any particular item, you can use CList::RemoveAt() function. To remove all the element from the list, CList::RemoveAll() function can be used." }, { "code": null, "e": 128609, "s": 128552, "text": "Let us remove the element, which has 95.78 as its value." }, { "code": null, "e": 129717, "s": 128609, "text": "BOOL CMFCCListDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n CList<double, double>m_list;\n\n //Add items to the list\n m_list.AddTail(100.75);\n m_list.AddTail(85.26);\n m_list.AddTail(95.78);\n m_list.AddTail(90.1);\n\n POSITION position = m_list.Find(85.26);\n m_list.InsertBefore(position, 200.0);\n m_list.InsertAfter(position, 300.0);\n \n position = m_list.Find(300.00);\n m_list.SetAt(position, 400.00);\n\n position = m_list.Find(95.78);\n m_list.RemoveAt(position);\n\n //iterate the list\n POSITION pos = m_list.GetHeadPosition();\n while (pos) {\n double nData = m_list.GetNext(pos);\n CString strVal;\n strVal.Format(L\"%.2f\\n\", nData);\n m_strText.Append(strVal);\n }\n UpdateData(FALSE);\n \n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 129869, "s": 129717, "text": "When the above code is compiled and executed, you will see the following output. You can now see that the value of 95.78 is no longer part of the list." }, { "code": null, "e": 130248, "s": 129869, "text": "A database is a collection of information that is organized so that it can easily be accessed, managed, and updated. The MFC database classes based on ODBC are designed to provide access to any database for which an ODBC driver is available. Because the classes use ODBC, your application can access data in many different data formats and different local/remote configurations." }, { "code": null, "e": 130662, "s": 130248, "text": "You do not have to write special-case code to handle different database management systems (DBMSs). As long as your users have an appropriate ODBC driver for the data they want to access, they can use your program to manipulate data in tables stored there. A data source is a specific instance of data hosted by some database management system (DBMS). Examples include Microsoft SQL Server, Microsoft Access, etc." }, { "code": null, "e": 130872, "s": 130662, "text": "MFC provides a class CDatabase which represents a connection to a data source, through which you can operate on the data source. You can have one or more CDatabase objects active at a time in your application." }, { "code": null, "e": 130883, "s": 130872, "text": "BeginTrans" }, { "code": null, "e": 131123, "s": 130883, "text": "Starts a \"transaction\" — a series of reversible calls to the AddNew, Edit, Delete, and Update member functions of class CRecordset — on the connected data source. The data source must support transactions for BeginTrans to have any effect." }, { "code": null, "e": 131138, "s": 131123, "text": "BindParameters" }, { "code": null, "e": 131195, "s": 131138, "text": "Allows you to bind parameters before calling ExecuteSQL." }, { "code": null, "e": 131202, "s": 131195, "text": "Cancel" }, { "code": null, "e": 131271, "s": 131202, "text": "Cancels an asynchronous operation or a process from a second thread." }, { "code": null, "e": 131283, "s": 131271, "text": "CanTransact" }, { "code": null, "e": 131341, "s": 131283, "text": "Returns nonzero if the data source supports transactions." }, { "code": null, "e": 131351, "s": 131341, "text": "CanUpdate" }, { "code": null, "e": 131421, "s": 131351, "text": "Returns nonzero if the CDatabase object is updatable (not read-only)." }, { "code": null, "e": 131427, "s": 131421, "text": "Close" }, { "code": null, "e": 131462, "s": 131427, "text": "Closes the data source connection." }, { "code": null, "e": 131474, "s": 131462, "text": "CommitTrans" }, { "code": null, "e": 131591, "s": 131474, "text": "Completes a transaction begun by BeginTrans. Commands in the transaction that alter the data source are carried out." }, { "code": null, "e": 131602, "s": 131591, "text": "ExecuteSQL" }, { "code": null, "e": 131658, "s": 131602, "text": "Executes a SQL statement. No data records are returned." }, { "code": null, "e": 131681, "s": 131658, "text": "GetBookmarkPersistence" }, { "code": null, "e": 131761, "s": 131681, "text": "Identifies the operations through which bookmarks persist on recordset objects." }, { "code": null, "e": 131772, "s": 131761, "text": "GetConnect" }, { "code": null, "e": 131862, "s": 131772, "text": "Returns the ODBC connection string used to connect the CDatabase object to a data source." }, { "code": null, "e": 131886, "s": 131862, "text": "GetCursorCommitBehavior" }, { "code": null, "e": 131965, "s": 131886, "text": "Identifies the effect of committing a transaction on an open recordset object." }, { "code": null, "e": 131991, "s": 131965, "text": "GetCursorRollbackBehavior" }, { "code": null, "e": 132072, "s": 131991, "text": "Identifies the effect of rolling back a transaction on an open recordset object." }, { "code": null, "e": 132088, "s": 132072, "text": "GetDatabaseName" }, { "code": null, "e": 132139, "s": 132088, "text": "Returns the name of the database currently in use." }, { "code": null, "e": 132146, "s": 132139, "text": "IsOpen" }, { "code": null, "e": 132227, "s": 132146, "text": "Returns nonzero if the CDatabase object is currently connected to a data source." }, { "code": null, "e": 132240, "s": 132227, "text": "OnSetOptions" }, { "code": null, "e": 132431, "s": 132240, "text": "Called by the framework to set standard connection options. The default implementation sets the query timeout value. You can establish these options ahead of time by calling SetQueryTimeout." }, { "code": null, "e": 132436, "s": 132431, "text": "Open" }, { "code": null, "e": 132504, "s": 132436, "text": "Establishes a connection to a data source (through an ODBC driver)." }, { "code": null, "e": 132511, "s": 132504, "text": "OpenEx" }, { "code": null, "e": 132579, "s": 132511, "text": "Establishes a connection to a data source (through an ODBC driver)." }, { "code": null, "e": 132588, "s": 132579, "text": "Rollback" }, { "code": null, "e": 132735, "s": 132588, "text": "Reverses changes made during the current transaction. The data source returns to its previous state, as defined at the BeginTrans call, unaltered." }, { "code": null, "e": 132751, "s": 132735, "text": "SetLoginTimeout" }, { "code": null, "e": 132838, "s": 132751, "text": "Sets the number of seconds after which a data source connection attempt will time out." }, { "code": null, "e": 132854, "s": 132838, "text": "SetQueryTimeout" }, { "code": null, "e": 133005, "s": 132854, "text": "Sets the number of seconds after which database query operations will time out. Affects all subsequent recordset Open, AddNew, Edit, and Delete calls." }, { "code": null, "e": 133087, "s": 133005, "text": "Let us look into a simple example by creating a new MFC dialog based application." }, { "code": null, "e": 133236, "s": 133087, "text": "Step 1 − Change the caption of TODO line to Retrieve Data from Database and drag one button and one List control as shown in the following snapshot." }, { "code": null, "e": 133333, "s": 133236, "text": "Step 2 − Add click event handler for button and control variable m_ListControl for List Control." }, { "code": null, "e": 133455, "s": 133333, "text": "Step 3 − We have simple database which contains one Employees table with some records as shown in the following snapshot." }, { "code": null, "e": 133546, "s": 133455, "text": "Step 4 − We need to include the following headers file so that we can use CDatabase class." }, { "code": null, "e": 133587, "s": 133546, "text": "#include \"odbcinst.h\"\n#include \"afxdb.h\"" }, { "code": null, "e": 133677, "s": 133587, "text": "The SQL INSERT INTO Statement is used to add new rows of data to a table in the database." }, { "code": null, "e": 133795, "s": 133677, "text": "Step 1 − To add new records, we will use the ExecuteSQL() function of CDatabase class as shown in the following code." }, { "code": null, "e": 134503, "s": 133795, "text": "CDatabase database;\nCString SqlString;\nCString strID, strName, strAge;\nCString sDriver = L\"MICROSOFT ACCESS DRIVER (*.mdb)\";\nCString sDsn;\nCString sFile = L\"D:\\\\Test.mdb\";\n// You must change above path if it's different\nint iRec = 0;\n\n// Build ODBC connection string\nsDsn.Format(L\"ODBC;DRIVER={%s};DSN='';DBQ=%s\", sDriver, sFile);\nTRY {\n // Open the database\n database.Open(NULL,false,false,sDsn);\n\n SqlString = \"INSERT INTO Employees (ID,Name,age) VALUES (5,'Sanjay',69)\";\n database.ExecuteSQL(SqlString);\n // Close the database\n database.Close();\n}CATCH(CDBException, e) {\n // If a database exception occured, show error msg\n AfxMessageBox(L\"Database error: \" + e→m_strError);\n}\nEND_CATCH;" }, { "code": null, "e": 134616, "s": 134503, "text": "Step 2 − When the above code is compiled and executed, you will see that a new record is added in your database." }, { "code": null, "e": 134770, "s": 134616, "text": "To retrieve the above table in MFC application, we implement the database related operations in the button event handler as shown in the following steps." }, { "code": null, "e": 134887, "s": 134770, "text": "Step 1 − To use CDatabase, construct a CDatabase object and call its Open() function. This will open the connection." }, { "code": null, "e": 135036, "s": 134887, "text": "Step 2 − Construct CRecordset objects for operating on the connected data source, pass the recordset constructor a pointer to your CDatabase object." }, { "code": null, "e": 135131, "s": 135036, "text": "Step 3 − After using the connection, call the Close function and destroy the CDatabase object." }, { "code": null, "e": 137547, "s": 135131, "text": "void CMFCDatabaseDemoDlg::OnBnClickedButtonRead() {\n // TODO: Add your control notification handler code here\n CDatabase database;\n CString SqlString;\n CString strID, strName, strAge;\n CString sDriver = \"MICROSOFT ACCESS DRIVER (*.mdb)\";\n CString sFile = L\"D:\\\\Test.mdb\";\n // You must change above path if it's different\n int iRec = 0;\n\n // Build ODBC connection string\n sDsn.Format(\"ODBC;DRIVER={%s};DSN='';DBQ=%s\",sDriver,sFile);\n TRY {\n // Open the database\n database.Open(NULL,false,false,sDsn);\n\n // Allocate the recordset\n CRecordset recset( &database );\n\n // Build the SQL statement\n SqlString = \"SELECT ID, Name, Age \" \"FROM Employees\";\n\n // Execute the query\n\t \n recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);\n // Reset List control if there is any data\n ResetListControl();\n // populate Grids\n ListView_SetExtendedListViewStyle(m_ListControl,LVS_EX_GRIDLINES);\n\n // Column width and heading\n m_ListControl.InsertColumn(0,\"Emp ID\",LVCFMT_LEFT,-1,0);\n m_ListControl.InsertColumn(1,\"Name\",LVCFMT_LEFT,-1,1);\n m_ListControl.InsertColumn(2, \"Age\", LVCFMT_LEFT, -1, 1);\n m_ListControl.SetColumnWidth(0, 120);\n m_ListControl.SetColumnWidth(1, 200);\n m_ListControl.SetColumnWidth(2, 200);\n\n // Loop through each record\n while( !recset.IsEOF() ) {\n // Copy each column into a variable\n recset.GetFieldValue(\"ID\",strID);\n recset.GetFieldValue(\"Name\",strName);\n recset.GetFieldValue(\"Age\", strAge);\n\n // Insert values into the list control\n iRec = m_ListControl.InsertItem(0,strID,0);\n m_ListControl.SetItemText(0,1,strName);\n m_ListControl.SetItemText(0, 2, strAge);\n\n // goto next record\n recset.MoveNext();\n }\n // Close the database\n database.Close();\n }CATCH(CDBException, e) {\n // If a database exception occured, show error msg\n AfxMessageBox(\"Database error: \"+e→m_strError);\n }\n END_CATCH; \n}\n\n// Reset List control\nvoid CMFCDatabaseDemoDlg::ResetListControl() {\n m_ListControl.DeleteAllItems();\n int iNbrOfColumns;\n CHeaderCtrl* pHeader = (CHeaderCtrl*)m_ListControl.GetDlgItem(0);\n if (pHeader) {\n iNbrOfColumns = pHeader→GetItemCount();\n }\n for (int i = iNbrOfColumns; i >= 0; i--) {\n m_ListControl.DeleteColumn(i);\n }\n}" }, { "code": null, "e": 137581, "s": 137547, "text": "Step 4 − Here is the header file." }, { "code": null, "e": 138390, "s": 137581, "text": "// MFCDatabaseDemoDlg.h : header file\n//\n\n#pragma once\n#include \"afxcmn.h\"\n\n\n// CMFCDatabaseDemoDlg dialog\nclass CMFCDatabaseDemoDlg : public CDialogEx {\n // Construction\n public:\n CMFCDatabaseDemoDlg(CWnd* pParent = NULL); // standard constructor\n\n // Dialog Data\n #ifdef AFX_DESIGN_TIME\n enum { IDD = IDD_MFCDATABASEDEMO_DIALOG };\n #endif\n\n protected:\n virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support\n void ResetListControl();\n\n // Implementation\n protected:\n HICON m_hIcon;\n\n // Generated message map functions\n virtual BOOL OnInitDialog();\n afx_msg void OnPaint();\n afx_msg HCURSOR OnQueryDragIcon();\n DECLARE_MESSAGE_MAP()\n public:\n CListCtrl m_ListControl;\n afx_msg void OnBnClickedButtonRead();\n};" }, { "code": null, "e": 138480, "s": 138390, "text": "Step 5 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 138585, "s": 138480, "text": "Step 6 − Press the Read button to execute the database operations. It will retrieve the Employees table." }, { "code": null, "e": 138766, "s": 138585, "text": "The SQL UPDATE Query is used to modify the existing records in a table. You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows would be affected." }, { "code": null, "e": 138853, "s": 138766, "text": "Step 1 − Let us look into a simple example by updating the Age where ID is equal to 5." }, { "code": null, "e": 138945, "s": 138853, "text": "SqlString = L\"UPDATE Employees SET Age = 59 WHERE ID = 5;\";\ndatabase.ExecuteSQL(SqlString);" }, { "code": null, "e": 139003, "s": 138945, "text": "Step 2 − Here is the complete code of button click event." }, { "code": null, "e": 141284, "s": 139003, "text": "void CMFCDatabaseDemoDlg::OnBnClickedButtonRead() {\n // TODO: Add your control notification handler code here\n CDatabase database;\n CString SqlString;\n CString strID, strName, strAge;\n CString sDriver = L\"MICROSOFT ACCESS DRIVER (*.mdb)\";\n CString sDsn;\n CString sFile =\n L\"C:\\\\Users\\\\Muhammad.Waqas\\\\Downloads\\\\Compressed\\\\ReadDB_demo\\\\Test.mdb\";\n // You must change above path if it's different\n int iRec = 0;\n\n // Build ODBC connection string\n sDsn.Format(L\"ODBC;DRIVER={%s};DSN='';DBQ=%s\", sDriver, sFile);\n TRY {\n // Open the database\n database.Open(NULL,false,false,sDsn);\n\n // Allocate the recordset\n CRecordset recset(&database);\n\n SqlString = L\"UPDATE Employees SET Age = 59 WHERE ID = 5;\";\n\n database.ExecuteSQL(SqlString);\n\n SqlString = \"SELECT ID, Name, Age FROM Employees\";\n\n // Build the SQL statement\n SqlString = \"SELECT ID, Name, Age FROM Employees\";\n\n // Execute the query\n recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);\n\n // Reset List control if there is any data\n ResetListControl();\n // populate Grids\n ListView_SetExtendedListViewStyle(m_listCtrl,LVS_EX_GRIDLINES);\n\n // Column width and heading\n m_listCtrl.InsertColumn(0,L\"Emp ID\",LVCFMT_LEFT,-1,0);\n m_listCtrl.InsertColumn(1,L\"Name\",LVCFMT_LEFT,-1,1);\n m_listCtrl.InsertColumn(2, L\"Age\", LVCFMT_LEFT, -1, 1);\n m_listCtrl.SetColumnWidth(0, 120);\n m_listCtrl.SetColumnWidth(1, 200);\n m_listCtrl.SetColumnWidth(2, 200);\n\n // Loop through each record\n while (!recset.IsEOF()) {\n // Copy each column into a variable\n recset.GetFieldValue(L\"ID\",strID);\n recset.GetFieldValue(L\"Name\",strName);\n recset.GetFieldValue(L\"Age\", strAge);\n\n // Insert values into the list control\n iRec = m_listCtrl.InsertItem(0,strID,0);\n m_listCtrl.SetItemText(0,1,strName);\n m_listCtrl.SetItemText(0, 2, strAge);\n\n // goto next record\n recset.MoveNext();\n }\n\n // Close the database\n database.Close();\n }CATCH(CDBException, e) {\n // If a database exception occured, show error msg\n AfxMessageBox(L\"Database error: \" + e→m_strError);\n }\n END_CATCH;\n}" }, { "code": null, "e": 141374, "s": 141284, "text": "Step 3 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 141489, "s": 141374, "text": "Step 4 − Press the Read button to execute the database operations. It will retrieve the following Employees table." }, { "code": null, "e": 141549, "s": 141489, "text": "Step 5 − You can now see that age is updated from 69 to 59." }, { "code": null, "e": 141735, "s": 141549, "text": "The SQL DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete selected rows, otherwise all the records would be deleted." }, { "code": null, "e": 141825, "s": 141735, "text": "Step 1 − Let us look into a simple example by deleting the record where ID is equal to 3." }, { "code": null, "e": 141910, "s": 141825, "text": "SqlString = L\"DELETE FROM Employees WHERE ID = 3;\";\n\ndatabase.ExecuteSQL(SqlString);" }, { "code": null, "e": 141968, "s": 141910, "text": "Step 2 − Here is the complete code of button click event." }, { "code": null, "e": 144241, "s": 141968, "text": "void CMFCDatabaseDemoDlg::OnBnClickedButtonRead() {\n // TODO: Add your control notification handler code here\n CDatabase database;\n CString SqlString;\n CString strID, strName, strAge;\n CString sDriver = L\"MICROSOFT ACCESS DRIVER (*.mdb)\";\n CString sDsn;\n CString sFile =\n L\"C:\\\\Users\\\\Muhammad.Waqas\\\\Downloads\\\\Compressed\\\\ReadDB_demo\\\\Test.mdb\";\n\n // You must change above path if it's different\n int iRec = 0;\n\n // Build ODBC connection string\n sDsn.Format(L\"ODBC;DRIVER={%s};DSN='';DBQ=%s\", sDriver, sFile);\n TRY {\n // Open the database\n database.Open(NULL,false,false,sDsn);\n\n // Allocate the recordset\n CRecordset recset(&database);\n\n SqlString = L\"DELETE FROM Employees WHERE ID = 3;\";\n\n database.ExecuteSQL(SqlString);\n\n SqlString = \"SELECT ID, Name, Age FROM Employees\";\n\n // Build the SQL statement\n SqlString = \"SELECT ID, Name, Age FROM Employees\";\n\n // Execute the query\n recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);\n\n // Reset List control if there is any data\n ResetListControl();\n // populate Grids\n ListView_SetExtendedListViewStyle(m_listCtrl,LVS_EX_GRIDLINES);\n // Column width and heading\n m_listCtrl.InsertColumn(0,L\"Emp ID\",LVCFMT_LEFT,-1,0);\n m_listCtrl.InsertColumn(1,L\"Name\",LVCFMT_LEFT,-1,1);\n m_listCtrl.InsertColumn(2, L\"Age\", LVCFMT_LEFT, -1, 1);\n m_listCtrl.SetColumnWidth(0, 120);\n m_listCtrl.SetColumnWidth(1, 200);\n m_listCtrl.SetColumnWidth(2, 200);\n\n // Loop through each record\n while (!recset.IsEOF()) {\n // Copy each column into a variable\n recset.GetFieldValue(L\"ID\",strID);\n recset.GetFieldValue(L\"Name\",strName);\n recset.GetFieldValue(L\"Age\", strAge);\n\n // Insert values into the list control\n iRec = m_listCtrl.InsertItem(0,strID,0);\n m_listCtrl.SetItemText(0,1,strName);\n m_listCtrl.SetItemText(0, 2, strAge);\n\n // goto next record\n recset.MoveNext();\n }\n // Close the database\n database.Close();\n }CATCH(CDBException, e) {\n // If a database exception occured, show error msg\n AfxMessageBox(L\"Database error: \" + e→m_strError);\n }\n END_CATCH;\n}" }, { "code": null, "e": 144331, "s": 144241, "text": "Step 3 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 144436, "s": 144331, "text": "Step 4 − Press the Read button to execute the database operations. It will retrieve the Employees table." }, { "code": null, "e": 144736, "s": 144436, "text": "Serialization is the process of writing or reading an object to or from a persistent storage medium such as a disk file. Serialization is ideal for situations where it is desired to maintain the state of structured data (such as C++ classes or structures) during or after the execution of a program." }, { "code": null, "e": 145003, "s": 144736, "text": "When performing file processing, the values are typically of primitive types (char, short, int, float, or double). In the same way, we can individually save many values, one at a time. This technique doesn't include an object created from (as a variable of) a class." }, { "code": null, "e": 145195, "s": 145003, "text": "The MFC library has a high level of support for serialization. It starts with the CObject class that is the ancestor to most MFC classes, which is equipped with a Serialize() member function." }, { "code": null, "e": 145260, "s": 145195, "text": "Let us look into a simple example by creating a new MFC project." }, { "code": null, "e": 145353, "s": 145260, "text": "Step 1 − Remove the TODO line and design your dialog box as shown in the following snapshot." }, { "code": null, "e": 145504, "s": 145353, "text": "Step 2 − Add value variables for all the edit controls. For Emp ID and Age mentioned, the value type is an integer as shown in the following snapshot." }, { "code": null, "e": 145557, "s": 145504, "text": "Step 3 − Add the event handler for both the buttons." }, { "code": null, "e": 145692, "s": 145557, "text": "Step 4 − Let us now add a simple Employee class, which we need to serialize. Here is the declaration of Employee class in header file." }, { "code": null, "e": 145936, "s": 145692, "text": "class CEmployee : public CObject {\n public:\n int empID;\n CString empName;\n int age;\n CEmployee(void);\n ~CEmployee(void);\n private:\n\n public:\n void Serialize(CArchive& ar);\n DECLARE_SERIAL(CEmployee);\n};" }, { "code": null, "e": 146010, "s": 145936, "text": "Step 5 − Here is the definition of Employee class in source (*.cpp) file." }, { "code": null, "e": 146294, "s": 146010, "text": "IMPLEMENT_SERIAL(CEmployee, CObject, 0)\nCEmployee::CEmployee(void) {\n\n}\n\nCEmployee::~CEmployee(void) {\n\n}\n\nvoid CEmployee::Serialize(CArchive& ar) {\n CObject::Serialize(ar);\n\n if (ar.IsStoring())\n ar << empID << empName << age;\n else\n ar >> empID >> empName >> age;\n}" }, { "code": null, "e": 146360, "s": 146294, "text": "Step 6 − Here is the implementation of Save button event handler." }, { "code": null, "e": 146773, "s": 146360, "text": "void CMFCSerializationDlg::OnBnClickedButtonSave() {\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n CEmployee employee;\n CFile file;\n file.Open(L\"EmployeeInfo.hse\", CFile::modeCreate | CFile::modeWrite);\n CArchive ar(&file, CArchive::store);\n employee.empID = m_id;\n employee.empName = m_strName;\n employee.age = m_age;\n employee.Serialize(ar);\n ar.Close();\n}" }, { "code": null, "e": 146839, "s": 146773, "text": "Step 7 − Here is the implementation of Open button event handler." }, { "code": null, "e": 147274, "s": 146839, "text": "void CMFCSerializationDlg::OnBnClickedButtonOpen() {\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n\n CFile file;\n\n file.Open(L\"EmployeeInfo.hse\", CFile::modeRead);\n CArchive ar(&file, CArchive::load);\n CEmployee employee;\n\n employee.Serialize(ar);\n\n m_id = employee.empID;\n m_strName = employee.empName;\n m_age = employee.age;\n ar.Close();\n file.Close();\n\n UpdateData(FALSE);\n}" }, { "code": null, "e": 147364, "s": 147274, "text": "Step 8 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 147445, "s": 147364, "text": "Step 9 − Enter the info in all the fields and click Save and close this program." }, { "code": null, "e": 147559, "s": 147445, "text": "Step 10 − It will save the data. Run the application again and click open. It will load the Employee information." }, { "code": null, "e": 147873, "s": 147559, "text": "The Microsoft Foundation Class (MFC) library provides support for multithreaded applications. A thread is a path of execution within a process. When you start Notepad, the operating system creates a process and begins executing the primary thread of that process. When this thread terminates, so does the process." }, { "code": null, "e": 148192, "s": 147873, "text": "You can create additional threads in your application if you want. All threads in MFC applications are represented by CWinThread objects. In most situations, you do not even have to explicitly create these objects; instead call the framework helper function AfxBeginThread, which creates the CWinThread object for you." }, { "code": null, "e": 148274, "s": 148192, "text": "Let us look into a simple example by creating a new MFC dialog based application." }, { "code": null, "e": 148393, "s": 148274, "text": "Step 1 − Change the Caption and ID of Static control to Click on Start Thread button and IDC_STATIC_TEXT respectively." }, { "code": null, "e": 148467, "s": 148393, "text": "Step 2 − Drag two buttons and add click event handlers for these buttons." }, { "code": null, "e": 148522, "s": 148467, "text": "Step 3 − Add control variable for static text control." }, { "code": null, "e": 148624, "s": 148522, "text": "Step 4 − Now add the following three global variables at the start of CMFCMultithreadingDlg.cpp file." }, { "code": null, "e": 148667, "s": 148624, "text": "int currValue;\nint maxValue;\nBOOL stopNow;" }, { "code": null, "e": 148733, "s": 148667, "text": "Step 5 − Add the WM_TIMER message in CMFCMultithreadingDlg class." }, { "code": null, "e": 148773, "s": 148733, "text": "Here is the implementation of OnTimer()" }, { "code": null, "e": 149048, "s": 148773, "text": "void CMFCMultithreadingDlg::OnTimer(UINT_PTR nIDEvent) {\n // TODO: Add your message handler code here and/or call default\n CString sStatusMsg;\n sStatusMsg.Format(L\"Running: %d\", currValue);\n m_ctrlStatus.SetWindowText(sStatusMsg);\n\n CDialogEx::OnTimer(nIDEvent);\n}" }, { "code": null, "e": 149143, "s": 149048, "text": "Step 6 − Now add a sample function for using in AfxBeginThread in CMFCMultithreadingDlg class." }, { "code": null, "e": 149319, "s": 149143, "text": "UINT MyThreadProc(LPVOID Param) {\n while (!stopNow && (currValue < maxValue)) {\n currValue++;\n Sleep(50); // would do some work here\n }\n \n return TRUE;\n}" }, { "code": null, "e": 149426, "s": 149319, "text": "Step 7 − Here is the implementation of event handler for Start Thread button, which will start the thread." }, { "code": null, "e": 149755, "s": 149426, "text": "void CMFCMultithreadingDlg::OnBnClickedButtonStart() {\n // TODO: Add your control notification handler code here\n currValue = 0;\n maxValue = 5000;\n stopNow = 0;\n m_ctrlStatus.SetWindowText(L\"Starting...\");\n SetTimer(1234, 333, 0); // 3 times per second\n\n AfxBeginThread(MyThreadProc, 0); // <<== START THE THREAD\n}" }, { "code": null, "e": 149860, "s": 149755, "text": "Step 8 − Here is the implementation of event handler for Stop Thread button, which will stop the thread." }, { "code": null, "e": 150062, "s": 149860, "text": "void CMFCMultithreadingDlg::OnBnClickedButtonStop() {\n \n // TODO: Add your control notification handler code here\n stopNow = TRUE;\n KillTimer(1234);\n m_ctrlStatus.SetWindowText(L\"Stopped\");\n}" }, { "code": null, "e": 150105, "s": 150062, "text": "Step 9 − Here is the complete source file." }, { "code": null, "e": 153547, "s": 150105, "text": "// MFCMultithreadingDlg.cpp : implementation file\n//\n\n#include \"stdafx.h\"\n#include \"MFCMultithreading.h\"\n#include \"MFCMultithreadingDlg.h\"\n#include \"afxdialogex.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n\n// CMFCMultithreadingDlg dialog\n\nint currValue;\nint maxValue;\nBOOL stopNow;\n\nCMFCMultithreadingDlg::CMFCMultithreadingDlg(CWnd* pParent /* = NULL*/)\n : CDialogEx(IDD_MFCMULTITHREADING_DIALOG, pParent) {\n m_hIcon = AfxGetApp() -> LoadIcon(IDR_MAINFRAME);\n}\nvoid CMFCMultithreadingDlg::DoDataExchange(CDataExchange* pDX) {\n CDialogEx::DoDataExchange(pDX);\n DDX_Control(pDX, IDC_STATIC_TEXT, m_ctrlStatus);\n}\n\nBEGIN_MESSAGE_MAP(CMFCMultithreadingDlg, CDialogEx)\n ON_WM_PAINT()\n ON_WM_QUERYDRAGICON()\n ON_BN_CLICKED(IDC_BUTTON_START,\n &CMFCMultithreadingDlg::OnBnClickedButtonStart)\n ON_WM_TIMER()\n ON_BN_CLICKED(IDC_BUTTON_STOP,\n &CMFCMultithreadingDlg::OnBnClickedButtonStop)\nEND_MESSAGE_MAP()\n\n// CMFCMultithreadingDlg message handlers\n\nBOOL CMFCMultithreadingDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n\n return TRUE; // return TRUE unless you set the focus to a control\n}\n\n// If you add a minimize button to your dialog, you will need the code below\n// to draw the icon. For MFC applications using the document/view model,\n// this is automatically done for you by the framework.\n\nvoid CMFCMultithreadingDlg::OnPaint() {\n if (IsIconic()) {\n CPaintDC dc(this); // device context for painting\n SendMessage(WM_ICONERASEBKGND,\n reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);\n\t\t\t\n // Center icon in client rectangle\n int cxIcon = GetSystemMetrics(SM_CXICON);\n int cyIcon = GetSystemMetrics(SM_CYICON);\n CRect rect;\n GetClientRect(&rect);\n int x = (rect.Width() - cxIcon + 1) / 2;\n int y = (rect.Height() - cyIcon + 1) / 2;\n\n // Draw the icon\n dc.DrawIcon(x, y, m_hIcon);\n }else {\n CDialogEx::OnPaint();\n }\n}\n// The system calls this function to obtain the cursor to display while the user drags\n// the minimized window.\nHCURSOR CMFCMultithreadingDlg::OnQueryDragIcon() {\n return static_cast<HCURSOR>(m_hIcon);\n}\n\nUINT /*CThreadDlg::*/MyThreadProc(LPVOID Param) //Sample function for using in\nAfxBeginThread {\n while (!stopNow && (currValue < maxValue)) {\n currValue++;\n Sleep(50); // would do some work here\n }\n return TRUE;\n}\nvoid CMFCMultithreadingDlg::OnBnClickedButtonStart() {\n // TODO: Add your control notification handler code here\n currValue = 0;\n maxValue = 5000;\n stopNow = 0;\n m_ctrlStatus.SetWindowText(L\"Starting...\");\n SetTimer(1234, 333, 0); // 3 times per second\n\n AfxBeginThread(MyThreadProc, 0); // <<== START THE THREAD\n}\n\nvoid CMFCMultithreadingDlg::OnTimer(UINT_PTR nIDEvent) {\n // TODO: Add your message handler code here and/or call default\n CString sStatusMsg;\n sStatusMsg.Format(L\"Running: %d\", currValue);\n m_ctrlStatus.SetWindowText(sStatusMsg);\n\n CDialogEx::OnTimer(nIDEvent);\n}\n\nvoid CMFCMultithreadingDlg::OnBnClickedButtonStop() {\n // TODO: Add your control notification handler code here\n stopNow = TRUE;\n KillTimer(1234);\n m_ctrlStatus.SetWindowText(L\"Stopped\");\n}" }, { "code": null, "e": 153638, "s": 153547, "text": "Step 10 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 153682, "s": 153638, "text": "Step 11 − Now click on Start Thread button." }, { "code": null, "e": 153747, "s": 153682, "text": "Step 12 − Click the Stop Thread button. It will stop the thread." }, { "code": null, "e": 154085, "s": 153747, "text": "Microsoft provides many APIs for programming both client and server applications. Many new applications are being written for the Internet, and as technologies, browser capabilities, and security options change, new types of applications will be written. Your custom application can retrieve information and provide data on the Internet." }, { "code": null, "e": 154180, "s": 154085, "text": "MFC provides a class CSocket for writing network communications programs with Windows Sockets." }, { "code": null, "e": 154224, "s": 154180, "text": "Here is a list of methods in CSocket class." }, { "code": null, "e": 154231, "s": 154224, "text": "Attach" }, { "code": null, "e": 154277, "s": 154231, "text": "Attaches a SOCKET handle to a CSocket object." }, { "code": null, "e": 154296, "s": 154277, "text": "CancelBlockingCall" }, { "code": null, "e": 154351, "s": 154296, "text": "Cancels a blocking call that is currently in progress." }, { "code": null, "e": 154358, "s": 154351, "text": "Create" }, { "code": null, "e": 154376, "s": 154358, "text": "Creates a socket." }, { "code": null, "e": 154387, "s": 154376, "text": "FromHandle" }, { "code": null, "e": 154449, "s": 154387, "text": "Returns a pointer to a CSocket object, given a SOCKET handle." }, { "code": null, "e": 154460, "s": 154449, "text": "IsBlocking" }, { "code": null, "e": 154511, "s": 154460, "text": "Determines whether a blocking call is in progress." }, { "code": null, "e": 154580, "s": 154511, "text": "Let us look into a simple example by creating a MFS SDI application." }, { "code": null, "e": 154637, "s": 154580, "text": "Step 1 − Enter MFCServer in the name field and click OK." }, { "code": null, "e": 154706, "s": 154637, "text": "Step 2 − On Advanced Features tab, check the Windows sockets option." }, { "code": null, "e": 154779, "s": 154706, "text": "Step 3 − Once the project is created, add a new MFC class CServerSocket." }, { "code": null, "e": 154839, "s": 154779, "text": "Step 4 − Select the CSocket as base class and click Finish." }, { "code": null, "e": 154885, "s": 154839, "text": "Step 5 − Add more MFC class CReceivingSocket." }, { "code": null, "e": 154954, "s": 154885, "text": "Step 6 − CRecevingSocket will receive incoming messages from client." }, { "code": null, "e": 155019, "s": 154954, "text": "In CMFCServerApp, the header file includes the following files −" }, { "code": null, "e": 155072, "s": 155019, "text": "#include \"ServerSocket.h\"\n#include \"MFCServerView.h\"" }, { "code": null, "e": 155143, "s": 155072, "text": "Step 7 − Add the following two class variables in CMFCServerApp class." }, { "code": null, "e": 155204, "s": 155143, "text": "CServerSocket m_serverSocket;\nCMFCServerView m_pServerView;\n" }, { "code": null, "e": 155341, "s": 155204, "text": "Step 8 − In CMFCServerApp::InitInstance() method, create the socket and specify the port and then call the Listen method as shown below." }, { "code": null, "e": 155396, "s": 155341, "text": "m_serverSocket.Create(6666);\nm_serverSocket.Listen();\n" }, { "code": null, "e": 155470, "s": 155396, "text": "Step 9 − Include the following header file in CMFCServerView header file." }, { "code": null, "e": 155496, "s": 155470, "text": "#include \"MFCServerDoc.h\"" }, { "code": null, "e": 155556, "s": 155496, "text": "Step 10 − Override the OnAccept function from Socket class." }, { "code": null, "e": 155716, "s": 155556, "text": "Step 11 − Select CServerSocket in class view and the highlighted icon in Properties window. Now, Add OnAccept. Here is the implementation of OnAccept function." }, { "code": null, "e": 155912, "s": 155716, "text": "void CServerSocket::OnAccept(int nErrorCode) {\n\n // TODO: Add your specialized code here and/or call the base class\n AfxMessageBox(L\"Connection accepted\");\n CSocket::OnAccept(nErrorCode);\n}" }, { "code": null, "e": 155948, "s": 155912, "text": "Step 12 − Add OnReceive() function." }, { "code": null, "e": 156144, "s": 155948, "text": "void CServerSocket::OnReceive(int nErrorCode) { \n \n // TODO: Add your specialized code here and/or call the base class\n AfxMessageBox(L\"Data Received\");\n CSocket::OnReceive(nErrorCode);\n}" }, { "code": null, "e": 156206, "s": 156144, "text": "Step 13 − Add OnReceive() function in CReceivingSocket class." }, { "code": null, "e": 156297, "s": 156206, "text": "Right-click on the CMFCServerView class in solution explorer and select Add → AddFunction." }, { "code": null, "e": 156363, "s": 156297, "text": "Step 14 − Enter the above mentioned information and click finish." }, { "code": null, "e": 156444, "s": 156363, "text": "Step 15 − Add the following CStringArray variable in CMFCServerView header file." }, { "code": null, "e": 156470, "s": 156444, "text": "CStringArray m_msgArray;\n" }, { "code": null, "e": 156529, "s": 156470, "text": "Step 16 − Here is the implementation of AddMsg() function." }, { "code": null, "e": 156624, "s": 156529, "text": "void CMFCServerView::AddMsg(CString message) {\n\n m_msgArray.Add(message);\n Invalidate();\n}" }, { "code": null, "e": 156689, "s": 156624, "text": "Step 17 − Update the constructor as shown in the following code." }, { "code": null, "e": 156785, "s": 156689, "text": "CMFCServerView::CMFCServerView() {\n\n ((CMFCServerApp*)AfxGetApp()) -> m_pServerView = this;\n}" }, { "code": null, "e": 156868, "s": 156785, "text": "Step 18 − Here is the implementation of OnDraw() function, which display messages." }, { "code": null, "e": 157187, "s": 156868, "text": "void CMFCServerView::OnDraw(CDC* pDC) {\n\n int y = 100;\n for (int i = 0; m_msgArray.GetSize(); i++) {\n \n pDC->TextOut(100, y, m_msgArray.GetAt(i));\n y += 50;\n }\n CMFCServerDoc* pDoc = GetDocument();\n ASSERT_VALID(pDoc);\n if (!pDoc)\n return;\n\n // TODO: add draw code for native data here\n}" }, { "code": null, "e": 157271, "s": 157187, "text": "Step 19 − The server side is now complete. It will receive message from the client." }, { "code": null, "e": 157358, "s": 157271, "text": "Step 1 − Let us create a new MFC dialog based application for client side application." }, { "code": null, "e": 157442, "s": 157358, "text": "Step 2 − On Advanced Features tab, check the Windows sockets option as shown above." }, { "code": null, "e": 157539, "s": 157442, "text": "Step 3 − Once the project is created, design your dialog box as shown in the following snapshot." }, { "code": null, "e": 157597, "s": 157539, "text": "Step 4 − Add event handlers for Connect and Send buttons." }, { "code": null, "e": 157713, "s": 157597, "text": "Step 5 − Add value variables for all the three edit controls. For port edit control, select the variable type UINT." }, { "code": null, "e": 157773, "s": 157713, "text": "Step 6 − Add MFC class for connecting and sending messages." }, { "code": null, "e": 157976, "s": 157773, "text": "Step 7 − Include the header file of CClientSocket class in the header file CMFCClientDemoApp class and add the class variable. Similarly, add the class variable in CMFCClientDemoDlg header file as well." }, { "code": null, "e": 158006, "s": 157976, "text": "CClientSocket m_clientSocket;" }, { "code": null, "e": 158075, "s": 158006, "text": "Step 8 − Here is the implementation of Connect button event handler." }, { "code": null, "e": 158434, "s": 158075, "text": "void CMFCClientDemoDlg::OnBnClickedButtonConnect() {\n\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n m_clientSocket.Create();\n if (m_clientSocket.Connect(m_ipAddress, m_port)) {\n AfxMessageBox(L\"Connection Successfull\");\n }else {\n AfxMessageBox(L\"Connection Failed\");\n }\n DWORD error = GetLastError();\n}" }, { "code": null, "e": 158500, "s": 158434, "text": "Step 9 − Here is the implementation of Send button event handler." }, { "code": null, "e": 158799, "s": 158500, "text": "void CMFCClientDemoDlg::OnBnClickedButtonSend() {\n\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n if (m_clientSocket.Send(m_message.GetBuffer(m_message.GetLength()), m_message.GetLength())) {\n \n }else {\n AfxMessageBox(L\"Failed to send message\");\n }\n}" }, { "code": null, "e": 158927, "s": 158799, "text": "Step 10 − First run the Server application and then the client application. Enter the local host ip and port and click Connect." }, { "code": null, "e": 159017, "s": 158927, "text": "Step 11 − You will now see the message on Server side as shown in the following snapshot." }, { "code": null, "e": 159251, "s": 159017, "text": "Windows provides a variety of drawing tools to use in device contexts. It provides pens to draw lines, brushes to fill interiors, and fonts to draw text. MFC provides graphic-object classes equivalent to the drawing tools in Windows." }, { "code": null, "e": 159525, "s": 159251, "text": "A device context is a Windows data structure containing information about the drawing attributes of a device such as a display or a printer. All drawing calls are made through a device-context object, which encapsulates the Windows APIs for drawing lines, shapes, and text." }, { "code": null, "e": 159671, "s": 159525, "text": "Device contexts allow device-independent drawing in Windows. Device contexts can be used to draw to the screen, to the printer, or to a metafile." }, { "code": null, "e": 159897, "s": 159671, "text": "CDC is the most fundamental class to draw in MFC. The CDC object provides member functions to perform the basic drawing steps, as well as members for working with a display context associated with the client area of a window." }, { "code": null, "e": 159906, "s": 159897, "text": "AbortDoc" }, { "code": null, "e": 160054, "s": 159906, "text": "Terminates the current print job, erasing everything the application has written to the device since the last call of the StartDoc member function." }, { "code": null, "e": 160064, "s": 160054, "text": "AbortPath" }, { "code": null, "e": 160117, "s": 160064, "text": "Closes and discards any paths in the device context." }, { "code": null, "e": 160136, "s": 160117, "text": "AddMetaFileComment" }, { "code": null, "e": 160212, "s": 160136, "text": "Copies the comment from a buffer into a specified enhanced-format metafile." }, { "code": null, "e": 160223, "s": 160212, "text": "AlphaBlend" }, { "code": null, "e": 160289, "s": 160223, "text": "Displays bitmaps that have transparent or semitransparent pixels." }, { "code": null, "e": 160298, "s": 160289, "text": "AngleArc" }, { "code": null, "e": 160394, "s": 160298, "text": "Draws a line segment and an arc, and moves the current position to the ending point of the arc." }, { "code": null, "e": 160398, "s": 160394, "text": "Arc" }, { "code": null, "e": 160423, "s": 160398, "text": "Draws an elliptical arc." }, { "code": null, "e": 160429, "s": 160423, "text": "ArcTo" }, { "code": null, "e": 160532, "s": 160429, "text": "Draws an elliptical arc. This function is similar to Arc, except that the current position is updated." }, { "code": null, "e": 160539, "s": 160532, "text": "Attach" }, { "code": null, "e": 160593, "s": 160539, "text": "Attaches a Windows device context to this CDC object." }, { "code": null, "e": 160603, "s": 160593, "text": "BeginPath" }, { "code": null, "e": 160647, "s": 160603, "text": "Opens a path bracket in the device context." }, { "code": null, "e": 160654, "s": 160647, "text": "BitBlt" }, { "code": null, "e": 160703, "s": 160654, "text": "Copies a bitmap from a specified device context." }, { "code": null, "e": 160709, "s": 160703, "text": "Chord" }, { "code": null, "e": 160803, "s": 160709, "text": "Draws a chord (a closed figure bounded by the intersection of an ellipse and a line segment)." }, { "code": null, "e": 160815, "s": 160803, "text": "CloseFigure" }, { "code": null, "e": 160848, "s": 160815, "text": "Closes an open figure in a path." }, { "code": null, "e": 160867, "s": 160848, "text": "CreateCompatibleDC" }, { "code": null, "e": 160991, "s": 160867, "text": "Creates a memory-device context that is compatible with another device context. You can use it to prepare images in memory." }, { "code": null, "e": 161000, "s": 160991, "text": "CreateDC" }, { "code": null, "e": 161048, "s": 161000, "text": "Creates a device context for a specific device." }, { "code": null, "e": 161057, "s": 161048, "text": "CreateIC" }, { "code": null, "e": 161207, "s": 161057, "text": "Creates an information context for a specific device. This provides a fast way to get information about the device without creating a device context." }, { "code": null, "e": 161216, "s": 161207, "text": "DeleteDC" }, { "code": null, "e": 161284, "s": 161216, "text": "Deletes the Windows device context associated with this CDC object." }, { "code": null, "e": 161298, "s": 161284, "text": "DeleteTempMap" }, { "code": null, "e": 161430, "s": 161298, "text": "Called by the CWinApp idle-time handler to delete any temporary CDC object created by FromHandle. Also detaches the device context." }, { "code": null, "e": 161437, "s": 161430, "text": "Detach" }, { "code": null, "e": 161495, "s": 161437, "text": "Detaches the Windows device context from this CDC object." }, { "code": null, "e": 161508, "s": 161495, "text": "DPtoHIMETRIC" }, { "code": null, "e": 161551, "s": 161508, "text": "Converts device units into HIMETRIC units." }, { "code": null, "e": 161558, "s": 161551, "text": "DPtoLP" }, { "code": null, "e": 161600, "s": 161558, "text": "Converts device units into logical units." }, { "code": null, "e": 161611, "s": 161600, "text": "Draw3dRect" }, { "code": null, "e": 161648, "s": 161611, "text": "Draws a three-dimensional rectangle." }, { "code": null, "e": 161661, "s": 161648, "text": "DrawDragRect" }, { "code": null, "e": 161710, "s": 161661, "text": "Erases and redraws a rectangle as it is dragged." }, { "code": null, "e": 161719, "s": 161710, "text": "DrawEdge" }, { "code": null, "e": 161751, "s": 161719, "text": "Draws the edges of a rectangle." }, { "code": null, "e": 161762, "s": 161751, "text": "DrawEscape" }, { "code": null, "e": 161888, "s": 161762, "text": "Accesses drawing capabilities of a video display that are not directly available through the graphics device interface (GDI)." }, { "code": null, "e": 161902, "s": 161888, "text": "DrawFocusRect" }, { "code": null, "e": 161957, "s": 161902, "text": "Draws a rectangle in the style used to indicate focus." }, { "code": null, "e": 161974, "s": 161957, "text": "DrawFrameControl" }, { "code": null, "e": 161996, "s": 161974, "text": "Draw a frame control." }, { "code": null, "e": 162005, "s": 161996, "text": "DrawIcon" }, { "code": null, "e": 162020, "s": 162005, "text": "Draws an icon." }, { "code": null, "e": 162030, "s": 162020, "text": "DrawState" }, { "code": null, "e": 162097, "s": 162030, "text": "Displays an image and applies a visual effect to indicate a state." }, { "code": null, "e": 162106, "s": 162097, "text": "DrawText" }, { "code": null, "e": 162155, "s": 162106, "text": "Draws formatted text in the specified rectangle." }, { "code": null, "e": 162166, "s": 162155, "text": "DrawTextEx" }, { "code": null, "e": 162240, "s": 162166, "text": "Draws formatted text in the specified rectangle using additional formats." }, { "code": null, "e": 162248, "s": 162240, "text": "Ellipse" }, { "code": null, "e": 162266, "s": 162248, "text": "Draws an ellipse." }, { "code": null, "e": 162273, "s": 162266, "text": "EndDoc" }, { "code": null, "e": 162331, "s": 162273, "text": "Ends a print job started by the StartDoc member function." }, { "code": null, "e": 162339, "s": 162331, "text": "EndPage" }, { "code": null, "e": 162388, "s": 162339, "text": "Informs the device driver that a page is ending." }, { "code": null, "e": 162396, "s": 162388, "text": "EndPath" }, { "code": null, "e": 162487, "s": 162396, "text": "Closes a path bracket and selects the path defined by the bracket into the device context." }, { "code": null, "e": 162499, "s": 162487, "text": "EnumObjects" }, { "code": null, "e": 162562, "s": 162499, "text": "Enumerates the pens and brushes available in a device context." }, { "code": null, "e": 162569, "s": 162562, "text": "Escape" }, { "code": null, "e": 162810, "s": 162569, "text": "Allows applications to access facilities that are not directly available from a particular device through GDI. Also allows access to Windows escape functions. Escape calls made by an application are translated and sent to the device driver." }, { "code": null, "e": 162826, "s": 162810, "text": "ExcludeClipRect" }, { "code": null, "e": 162933, "s": 162826, "text": "Creates a new clipping region that consists of the existing clipping region minus the specified rectangle." }, { "code": null, "e": 162950, "s": 162933, "text": "ExcludeUpdateRgn" }, { "code": null, "e": 163069, "s": 162950, "text": "Prevents drawing within invalid areas of a window by excluding an updated region in the window from a clipping region." }, { "code": null, "e": 163082, "s": 163069, "text": "ExtFloodFill" }, { "code": null, "e": 163182, "s": 163082, "text": "Fills an area with the current brush. Provides more flexibility than the FloodFill member function." }, { "code": null, "e": 163193, "s": 163182, "text": "ExtTextOut" }, { "code": null, "e": 163282, "s": 163193, "text": "Writes a character string within a rectangular region using the currently selected font." }, { "code": null, "e": 163291, "s": 163282, "text": "FillPath" }, { "code": null, "e": 163417, "s": 163291, "text": "Closes any open figures in the current path and fills the path's interior by using the current brush and polygonfilling mode." }, { "code": null, "e": 163426, "s": 163417, "text": "FillRect" }, { "code": null, "e": 163477, "s": 163426, "text": "Fills a given rectangle by using a specific brush." }, { "code": null, "e": 163485, "s": 163477, "text": "FillRgn" }, { "code": null, "e": 163535, "s": 163485, "text": "Fills a specific region with the specified brush." }, { "code": null, "e": 163549, "s": 163535, "text": "FillSolidRect" }, { "code": null, "e": 163587, "s": 163549, "text": "Fills a rectangle with a solid color." }, { "code": null, "e": 163599, "s": 163587, "text": "FlattenPath" }, { "code": null, "e": 163722, "s": 163599, "text": "Transforms any curves in the path selected into the current device context, and turns each curve into a sequence of lines." }, { "code": null, "e": 163732, "s": 163722, "text": "FloodFill" }, { "code": null, "e": 163770, "s": 163732, "text": "Fills an area with the current brush." }, { "code": null, "e": 163780, "s": 163770, "text": "FrameRect" }, { "code": null, "e": 163815, "s": 163780, "text": "Draws a border around a rectangle." }, { "code": null, "e": 163824, "s": 163815, "text": "FrameRgn" }, { "code": null, "e": 163879, "s": 163824, "text": "Draws a border around a specific region using a brush." }, { "code": null, "e": 163890, "s": 163879, "text": "FromHandle" }, { "code": null, "e": 164060, "s": 163890, "text": "Returns a pointer to a CDC object when given a handle to a device context. If a CDC object is not attached to the handle, a temporary CDC object is created and attached." }, { "code": null, "e": 164076, "s": 164060, "text": "GetArcDirection" }, { "code": null, "e": 164134, "s": 164076, "text": "Returns the current arc direction for the device context." }, { "code": null, "e": 164155, "s": 164134, "text": "GetAspectRatioFilter" }, { "code": null, "e": 164214, "s": 164155, "text": "Retrieves the setting for the current aspect-ratio filter." }, { "code": null, "e": 164225, "s": 164214, "text": "GetBkColor" }, { "code": null, "e": 164265, "s": 164225, "text": "Retrieves the current background color." }, { "code": null, "e": 164275, "s": 164265, "text": "GetBkMode" }, { "code": null, "e": 164306, "s": 164275, "text": "Retrieves the background mode." }, { "code": null, "e": 164320, "s": 164306, "text": "GetBoundsRect" }, { "code": null, "e": 164405, "s": 164320, "text": "Returns the current accumulated bounding rectangle for the specified device context." }, { "code": null, "e": 164417, "s": 164405, "text": "GetBrushOrg" }, { "code": null, "e": 164460, "s": 164417, "text": "Retrieves the origin of the current brush." }, { "code": null, "e": 164477, "s": 164460, "text": "GetCharABCWidths" }, { "code": null, "e": 164583, "s": 164477, "text": "Retrieves the widths, in logical units, of consecutive characters in a given range from the current font." }, { "code": null, "e": 164601, "s": 164583, "text": "GetCharABCWidthsI" }, { "code": null, "e": 164723, "s": 164601, "text": "Retrieves the widths, in logical units, of consecutive glyph indices in a specified range from the current TrueType font." }, { "code": null, "e": 164745, "s": 164723, "text": "GetCharacterPlacement" }, { "code": null, "e": 164807, "s": 164745, "text": "Retrieves various types of information on a character string." }, { "code": null, "e": 164820, "s": 164807, "text": "GetCharWidth" }, { "code": null, "e": 164918, "s": 164820, "text": "Retrieves the fractional widths of consecutive characters in a given range from the current font." }, { "code": null, "e": 164932, "s": 164918, "text": "GetCharWidthI" }, { "code": null, "e": 165051, "s": 164932, "text": "Retrieves the widths, in logical coordinates, of consecutive glyph indices in a specified range from the current font." }, { "code": null, "e": 165062, "s": 165051, "text": "GetClipBox" }, { "code": null, "e": 165160, "s": 165062, "text": "Retrieves the dimensions of the tightest bounding rectangle around the current clipping boundary." }, { "code": null, "e": 165179, "s": 165160, "text": "GetColorAdjustment" }, { "code": null, "e": 165241, "s": 165179, "text": "Retrieves the color adjustment values for the device context." }, { "code": null, "e": 165258, "s": 165241, "text": "GetCurrentBitmap" }, { "code": null, "e": 165318, "s": 165258, "text": "Returns a pointer to the currently selected CBitmap object." }, { "code": null, "e": 165334, "s": 165318, "text": "GetCurrentBrush" }, { "code": null, "e": 165393, "s": 165334, "text": "Returns a pointer to the currently selected CBrush object." }, { "code": null, "e": 165408, "s": 165393, "text": "GetCurrentFont" }, { "code": null, "e": 165466, "s": 165408, "text": "Returns a pointer to the currently selected CFont object." }, { "code": null, "e": 165484, "s": 165466, "text": "GetCurrentPalette" }, { "code": null, "e": 165545, "s": 165484, "text": "Returns a pointer to the currently selected CPalette object." }, { "code": null, "e": 165559, "s": 165545, "text": "GetCurrentPen" }, { "code": null, "e": 165616, "s": 165559, "text": "Returns a pointer to the currently selected CPen object." }, { "code": null, "e": 165635, "s": 165616, "text": "GetCurrentPosition" }, { "code": null, "e": 165703, "s": 165635, "text": "Retrieves the current position of the pen (in logical coordinates)." }, { "code": null, "e": 165719, "s": 165703, "text": "GetDCBrushColor" }, { "code": null, "e": 165754, "s": 165719, "text": "Retrieves the current brush color." }, { "code": null, "e": 165768, "s": 165754, "text": "GetDCPenColor" }, { "code": null, "e": 165801, "s": 165768, "text": "Retrieves the current pen color." }, { "code": null, "e": 165815, "s": 165801, "text": "GetDeviceCaps" }, { "code": null, "e": 165918, "s": 165815, "text": "Retrieves a specified kind of device-specific information about a given display device's capabilities." }, { "code": null, "e": 165930, "s": 165918, "text": "GetFontData" }, { "code": null, "e": 166121, "s": 165930, "text": "Retrieves font metric information from a scalable font file. The information to retrieve is identified by specifying an offset into the font file and the length of the information to return." }, { "code": null, "e": 166141, "s": 166121, "text": "GetFontLanguageInfo" }, { "code": null, "e": 166230, "s": 166141, "text": "Returns information about the currently selected font for the specified display context." }, { "code": null, "e": 166246, "s": 166230, "text": "GetGlyphOutline" }, { "code": null, "e": 166330, "s": 166246, "text": "Retrieves the outline curve or bitmap for an outline character in the current font." }, { "code": null, "e": 166346, "s": 166330, "text": "GetGraphicsMode" }, { "code": null, "e": 166416, "s": 166346, "text": "Retrieves the current graphics mode for the specified device context." }, { "code": null, "e": 166433, "s": 166416, "text": "GetHalftoneBrush" }, { "code": null, "e": 166461, "s": 166433, "text": "Retrieves a halftone brush." }, { "code": null, "e": 166477, "s": 166461, "text": "GetKerningPairs" }, { "code": null, "e": 166588, "s": 166477, "text": "Retrieves the character kerning pairs for the font that is currently selected in the specified device context." }, { "code": null, "e": 166598, "s": 166588, "text": "GetLayout" }, { "code": null, "e": 166723, "s": 166598, "text": "Retrieves the layout of a device context (DC). The layout can be either left to right (default) or right to left (mirrored)." }, { "code": null, "e": 166734, "s": 166723, "text": "GetMapMode" }, { "code": null, "e": 166770, "s": 166734, "text": "Retrieves the current mapping mode." }, { "code": null, "e": 166784, "s": 166770, "text": "GetMiterLimit" }, { "code": null, "e": 166832, "s": 166784, "text": "Returns the miter limit for the device context." }, { "code": null, "e": 166848, "s": 166832, "text": "GetNearestColor" }, { "code": null, "e": 166950, "s": 166848, "text": "Retrieves the closest logical color to a specified logical color that the given device can represent." }, { "code": null, "e": 166972, "s": 166950, "text": "GetOutlineTextMetrics" }, { "code": null, "e": 167026, "s": 166972, "text": "Retrieves font metric information for TrueType fonts." }, { "code": null, "e": 167045, "s": 167026, "text": "GetOutputCharWidth" }, { "code": null, "e": 167183, "s": 167045, "text": "Retrieves the widths of individual characters in a consecutive group of characters from the current font using the output device context." }, { "code": null, "e": 167209, "s": 167183, "text": "GetOutputTabbedTextExtent" }, { "code": null, "e": 167291, "s": 167209, "text": "Computes the width and height of a character string on the output device context." }, { "code": null, "e": 167311, "s": 167291, "text": "GetOutputTextExtent" }, { "code": null, "e": 167440, "s": 167311, "text": "Computes the width and height of a line of text on the output device context using the current font to determine the dimensions." }, { "code": null, "e": 167461, "s": 167440, "text": "GetOutputTextMetrics" }, { "code": null, "e": 167536, "s": 167461, "text": "Retrieves the metrics for the current font from the output device context." }, { "code": null, "e": 167544, "s": 167536, "text": "GetPath" }, { "code": null, "e": 167695, "s": 167544, "text": "Retrieves the coordinates defining the endpoints of lines and the control points of curves found in the path that is selected into the device context." }, { "code": null, "e": 167704, "s": 167695, "text": "GetPixel" }, { "code": null, "e": 167771, "s": 167704, "text": "Retrieves the RGB color value of the pixel at the specified point." }, { "code": null, "e": 167787, "s": 167771, "text": "GetPolyFillMode" }, { "code": null, "e": 167831, "s": 167787, "text": "Retrieves the current polygon-filling mode." }, { "code": null, "e": 167839, "s": 167831, "text": "GetROP2" }, { "code": null, "e": 167875, "s": 167839, "text": "Retrieves the current drawing mode." }, { "code": null, "e": 167886, "s": 167875, "text": "GetSafeHdc" }, { "code": null, "e": 167928, "s": 167886, "text": "Returns m_hDC, the output device context." }, { "code": null, "e": 167946, "s": 167928, "text": "GetStretchBltMode" }, { "code": null, "e": 167992, "s": 167946, "text": "Retrieves the current bitmap-stretching mode." }, { "code": null, "e": 168012, "s": 167992, "text": "GetTabbedTextExtent" }, { "code": null, "e": 168097, "s": 168012, "text": "Computes the width and height of a character string on the attribute device context." }, { "code": null, "e": 168110, "s": 168097, "text": "GetTextAlign" }, { "code": null, "e": 168146, "s": 168110, "text": "Retrieves the text-alignment flags." }, { "code": null, "e": 168168, "s": 168146, "text": "GetTextCharacterExtra" }, { "code": null, "e": 168240, "s": 168168, "text": "Retrieves the current setting for the amount of intercharacter spacing." }, { "code": null, "e": 168253, "s": 168240, "text": "GetTextColor" }, { "code": null, "e": 168287, "s": 168253, "text": "Retrieves the current text color." }, { "code": null, "e": 168301, "s": 168287, "text": "GetTextExtent" }, { "code": null, "e": 168433, "s": 168301, "text": "Computes the width and height of a line of text on the attribute device context using the current font to determine the dimensions." }, { "code": null, "e": 168455, "s": 168433, "text": "GetTextExtentExPointI" }, { "code": null, "e": 168621, "s": 168455, "text": "Retrieves the number of characters in a specified string that will fit within a specified space and fills an array with the text extent for each of those characters." }, { "code": null, "e": 168641, "s": 168621, "text": "GetTextExtentPointI" }, { "code": null, "e": 168713, "s": 168641, "text": "Retrieves the width and height of the specified array of\nglyph indices." }, { "code": null, "e": 168725, "s": 168713, "text": "GetTextFace" }, { "code": null, "e": 168813, "s": 168725, "text": "Copies the typeface name of the current font into a buffer as a null-terminated string." }, { "code": null, "e": 168828, "s": 168813, "text": "GetTextMetrics" }, { "code": null, "e": 168906, "s": 168828, "text": "Retrieves the metrics for the current font from the attribute device context." }, { "code": null, "e": 168921, "s": 168906, "text": "GetViewportExt" }, { "code": null, "e": 168969, "s": 168921, "text": "Retrieves the x- and y-extents of the viewport." }, { "code": null, "e": 168984, "s": 168969, "text": "GetViewportOrg" }, { "code": null, "e": 169043, "s": 168984, "text": "Retrieves the x- and y-coordinates of the viewport origin." }, { "code": null, "e": 169053, "s": 169043, "text": "GetWindow" }, { "code": null, "e": 169116, "s": 169053, "text": "Returns the window associated with the display device context." }, { "code": null, "e": 169129, "s": 169116, "text": "GetWindowExt" }, { "code": null, "e": 169186, "s": 169129, "text": "Retrieves the x- and y-extents of the associated window." }, { "code": null, "e": 169199, "s": 169186, "text": "GetWindowOrg" }, { "code": null, "e": 169274, "s": 169199, "text": "Retrieves the x- and y-coordinates of the origin of the associated window." }, { "code": null, "e": 169292, "s": 169274, "text": "GetWorldTransform" }, { "code": null, "e": 169356, "s": 169292, "text": "Retrieves the current world-space to page-space transformation." }, { "code": null, "e": 169369, "s": 169356, "text": "GradientFill" }, { "code": null, "e": 169433, "s": 169369, "text": "Fills rectangle and triangle structures with a gradating color." }, { "code": null, "e": 169444, "s": 169433, "text": "GrayString" }, { "code": null, "e": 169494, "s": 169444, "text": "Draws dimmed (grayed) text at the given location." }, { "code": null, "e": 169507, "s": 169494, "text": "HIMETRICtoDP" }, { "code": null, "e": 169550, "s": 169507, "text": "Converts HIMETRIC units into device units." }, { "code": null, "e": 169563, "s": 169550, "text": "HIMETRICtoLP" }, { "code": null, "e": 169607, "s": 169563, "text": "Converts HIMETRIC units into logical units." }, { "code": null, "e": 169625, "s": 169607, "text": "IntersectClipRect" }, { "code": null, "e": 169722, "s": 169625, "text": "Creates a new clipping region by forming the intersection of the current region and a rectangle." }, { "code": null, "e": 169733, "s": 169722, "text": "InvertRect" }, { "code": null, "e": 169770, "s": 169733, "text": "Inverts the contents of a rectangle." }, { "code": null, "e": 169780, "s": 169770, "text": "InvertRgn" }, { "code": null, "e": 169812, "s": 169780, "text": "Inverts the colors in a region." }, { "code": null, "e": 169823, "s": 169812, "text": "IsPrinting" }, { "code": null, "e": 169889, "s": 169823, "text": "Determines whether the device context is being used for printing." }, { "code": null, "e": 169896, "s": 169889, "text": "LineTo" }, { "code": null, "e": 169970, "s": 169896, "text": "Draws a line from the current position up to, but not including, a point." }, { "code": null, "e": 169977, "s": 169970, "text": "LPtoDP" }, { "code": null, "e": 170019, "s": 169977, "text": "Converts logical units into device units." }, { "code": null, "e": 170032, "s": 170019, "text": "LPtoHIMETRIC" }, { "code": null, "e": 170076, "s": 170032, "text": "Converts logical units into HIMETRIC units." }, { "code": null, "e": 170084, "s": 170076, "text": "MaskBlt" }, { "code": null, "e": 170190, "s": 170084, "text": "Combines the color data for the source and destination bitmaps using the given mask and raster operation." }, { "code": null, "e": 170211, "s": 170190, "text": "ModifyWorldTransform" }, { "code": null, "e": 170291, "s": 170211, "text": "Changes the world transformation for a device context using the specified mode." }, { "code": null, "e": 170298, "s": 170291, "text": "MoveTo" }, { "code": null, "e": 170326, "s": 170298, "text": "Moves the current position." }, { "code": null, "e": 170340, "s": 170326, "text": "OffsetClipRgn" }, { "code": null, "e": 170387, "s": 170340, "text": "Moves the clipping region of the given device." }, { "code": null, "e": 170405, "s": 170387, "text": "OffsetViewportOrg" }, { "code": null, "e": 170494, "s": 170405, "text": "Modifies the viewport origin relative to the coordinates of the current viewport origin." }, { "code": null, "e": 170510, "s": 170494, "text": "OffsetWindowOrg" }, { "code": null, "e": 170595, "s": 170510, "text": "Modifies the window origin relative to the coordinates of the current window origin." }, { "code": null, "e": 170604, "s": 170595, "text": "PaintRgn" }, { "code": null, "e": 170644, "s": 170604, "text": "Fills a region with the selected brush." }, { "code": null, "e": 170651, "s": 170644, "text": "PatBlt" }, { "code": null, "e": 170674, "s": 170651, "text": "Creates a bit pattern." }, { "code": null, "e": 170678, "s": 170674, "text": "Pie" }, { "code": null, "e": 170704, "s": 170678, "text": "Draws a pie-shaped wedge." }, { "code": null, "e": 170717, "s": 170704, "text": "PlayMetaFile" }, { "code": null, "e": 170935, "s": 170717, "text": "Plays the contents of the specified metafile on the given device. The enhanced version of PlayMetaFile displays the picture stored in the given enhanced-format metafile. The metafile can be played any number of times." }, { "code": null, "e": 170942, "s": 170935, "text": "PlgBlt" }, { "code": null, "e": 171116, "s": 170942, "text": "Performs a bit-block transfer of the bits of color data from the specified rectangle in the source device context to the specified parallelogram in the given device context." }, { "code": null, "e": 171127, "s": 171116, "text": "PolyBezier" }, { "code": null, "e": 171210, "s": 171127, "text": "Draws one or more Bzier splines. The current position is neither used nor updated." }, { "code": null, "e": 171223, "s": 171210, "text": "PolyBezierTo" }, { "code": null, "e": 171333, "s": 171223, "text": "Draws one or more Bzier splines, and moves the current position to the ending point of the last Bzier spline." }, { "code": null, "e": 171342, "s": 171333, "text": "PolyDraw" }, { "code": null, "e": 171434, "s": 171342, "text": "Draws a set of line segments and Bzier splines. This function updates the current position." }, { "code": null, "e": 171442, "s": 171434, "text": "Polygon" }, { "code": null, "e": 171522, "s": 171442, "text": "Draws a polygon consisting of two or more points (vertices) connected by lines." }, { "code": null, "e": 171531, "s": 171522, "text": "Polyline" }, { "code": null, "e": 171593, "s": 171531, "text": "Draws a set of line segments connecting the specified points." }, { "code": null, "e": 171604, "s": 171593, "text": "PolylineTo" }, { "code": null, "e": 171706, "s": 171604, "text": "Draws one or more straight lines and moves the current position to the ending point of the last line." }, { "code": null, "e": 171718, "s": 171706, "text": "PolyPolygon" }, { "code": null, "e": 171853, "s": 171718, "text": "Creates two or more polygons that are filled using the current polygon-filling mode. The polygons may be disjoint or they may overlap." }, { "code": null, "e": 171866, "s": 171853, "text": "PolyPolyline" }, { "code": null, "e": 171983, "s": 171866, "text": "Draws multiple series of connected line segments. The current position is neither used nor updated by this function." }, { "code": null, "e": 171993, "s": 171983, "text": "PtVisible" }, { "code": null, "e": 172058, "s": 171993, "text": "Specifies whether the given point is within the clipping region." }, { "code": null, "e": 172073, "s": 172058, "text": "RealizePalette" }, { "code": null, "e": 172148, "s": 172073, "text": "Maps palette entries in the current logical palette to the\nsystem palette." }, { "code": null, "e": 172158, "s": 172148, "text": "Rectangle" }, { "code": null, "e": 172236, "s": 172158, "text": "Draws a rectangle using the current pen and fills it using the current brush." }, { "code": null, "e": 172248, "s": 172236, "text": "RectVisible" }, { "code": null, "e": 172332, "s": 172248, "text": "Determines whether any part of the given rectangle lies within the clipping region." }, { "code": null, "e": 172348, "s": 172332, "text": "ReleaseAttribDC" }, { "code": null, "e": 172400, "s": 172348, "text": "Releases m_hAttribDC, the attribute device context." }, { "code": null, "e": 172416, "s": 172400, "text": "ReleaseOutputDC" }, { "code": null, "e": 172459, "s": 172416, "text": "Releases m_hDC, the output device context." }, { "code": null, "e": 172467, "s": 172459, "text": "ResetDC" }, { "code": null, "e": 172507, "s": 172467, "text": "Updates the m_hAttribDC device context." }, { "code": null, "e": 172517, "s": 172507, "text": "RestoreDC" }, { "code": null, "e": 172584, "s": 172517, "text": "Restores the device context to a previous state saved with SaveDC." }, { "code": null, "e": 172594, "s": 172584, "text": "RoundRect" }, { "code": null, "e": 172691, "s": 172594, "text": "Draws a rectangle with rounded corners using the current pen and filled using the current brush." }, { "code": null, "e": 172698, "s": 172691, "text": "SaveDC" }, { "code": null, "e": 172745, "s": 172698, "text": "Saves the current state of the device context." }, { "code": null, "e": 172762, "s": 172745, "text": "ScaleViewportExt" }, { "code": null, "e": 172823, "s": 172762, "text": "Modifies the viewport extent relative to the current values." }, { "code": null, "e": 172838, "s": 172823, "text": "ScaleWindowExt" }, { "code": null, "e": 172898, "s": 172838, "text": "Modifies the window extents relative to the current values." }, { "code": null, "e": 172907, "s": 172898, "text": "ScrollDC" }, { "code": null, "e": 172964, "s": 172907, "text": "Scrolls a rectangle of bits horizontally and vertically." }, { "code": null, "e": 172979, "s": 172964, "text": "SelectClipPath" }, { "code": null, "e": 173137, "s": 172979, "text": "Selects the current path as a clipping region for the device context, combining the new region with any existing clipping region by using the specified mode." }, { "code": null, "e": 173151, "s": 173137, "text": "SelectClipRgn" }, { "code": null, "e": 173239, "s": 173151, "text": "Combines the given region with the current clipping region by using the specified mode." }, { "code": null, "e": 173252, "s": 173239, "text": "SelectObject" }, { "code": null, "e": 173296, "s": 173252, "text": "Selects a GDI drawing object such as a pen." }, { "code": null, "e": 173310, "s": 173296, "text": "SelectPalette" }, { "code": null, "e": 173339, "s": 173310, "text": "Selects the logical palette." }, { "code": null, "e": 173357, "s": 173339, "text": "SelectStockObject" }, { "code": null, "e": 173438, "s": 173357, "text": "Selects one of the predefined stock pens, brushes, or fonts provided by Windows." }, { "code": null, "e": 173451, "s": 173438, "text": "SetAbortProc" }, { "code": null, "e": 173547, "s": 173451, "text": "Sets a programmer-supplied callback function that Windows calls if a print job must be aborted." }, { "code": null, "e": 173563, "s": 173547, "text": "SetArcDirection" }, { "code": null, "e": 173634, "s": 173563, "text": "Sets the drawing direction to be used for arc and rectangle functions." }, { "code": null, "e": 173646, "s": 173634, "text": "SetAttribDC" }, { "code": null, "e": 173694, "s": 173646, "text": "Sets m_hAttribDC, the attribute device context." }, { "code": null, "e": 173705, "s": 173694, "text": "SetBkColor" }, { "code": null, "e": 173740, "s": 173705, "text": "Sets the current background color." }, { "code": null, "e": 173750, "s": 173740, "text": "SetBkMode" }, { "code": null, "e": 173776, "s": 173750, "text": "Sets the background mode." }, { "code": null, "e": 173790, "s": 173776, "text": "SetBoundsRect" }, { "code": null, "e": 173884, "s": 173790, "text": "Controls the accumulation of bounding-rectangle information for the specified device context." }, { "code": null, "e": 173896, "s": 173884, "text": "SetBrushOrg" }, { "code": null, "e": 173968, "s": 173896, "text": "Specifies the origin for the next brush selected into a device context." }, { "code": null, "e": 173987, "s": 173968, "text": "SetColorAdjustment" }, { "code": null, "e": 174071, "s": 173987, "text": "Sets the color adjustment values for the device context using the specified values." }, { "code": null, "e": 174087, "s": 174071, "text": "SetDCBrushColor" }, { "code": null, "e": 174117, "s": 174087, "text": "Sets the current brush color." }, { "code": null, "e": 174131, "s": 174117, "text": "SetDCPenColor" }, { "code": null, "e": 174159, "s": 174131, "text": "Sets the current pen color." }, { "code": null, "e": 174175, "s": 174159, "text": "SetGraphicsMode" }, { "code": null, "e": 174240, "s": 174175, "text": "Sets the current graphics mode for the specified device context." }, { "code": null, "e": 174250, "s": 174240, "text": "SetLayout" }, { "code": null, "e": 174295, "s": 174250, "text": "Changes the layout of a device context (DC)." }, { "code": null, "e": 174306, "s": 174295, "text": "SetMapMode" }, { "code": null, "e": 174337, "s": 174306, "text": "Sets the current mapping mode." }, { "code": null, "e": 174352, "s": 174337, "text": "SetMapperFlags" }, { "code": null, "e": 174445, "s": 174352, "text": "Alters the algorithm that the font mapper uses when it maps logical fonts to physical fonts." }, { "code": null, "e": 174459, "s": 174445, "text": "SetMiterLimit" }, { "code": null, "e": 174528, "s": 174459, "text": "Sets the limit for the length of miter joins for the device context." }, { "code": null, "e": 174540, "s": 174528, "text": "SetOutputDC" }, { "code": null, "e": 174579, "s": 174540, "text": "Sets m_hDC, the output device context." }, { "code": null, "e": 174588, "s": 174579, "text": "SetPixel" }, { "code": null, "e": 174679, "s": 174588, "text": "Sets the pixel at the specified point to the closest approximation of the specified color." }, { "code": null, "e": 174689, "s": 174679, "text": "SetPixelV" }, { "code": null, "e": 174902, "s": 174689, "text": "Sets the pixel at the specified coordinates to the closest approximation of the specified color. SetPixelV is faster than SetPixel because it does not need to return the color value of the point actually painted." }, { "code": null, "e": 174918, "s": 174902, "text": "SetPolyFillMode" }, { "code": null, "e": 174949, "s": 174918, "text": "Sets the polygon-filling mode." }, { "code": null, "e": 174957, "s": 174949, "text": "SetROP2" }, { "code": null, "e": 174988, "s": 174957, "text": "Sets the current drawing mode." }, { "code": null, "e": 175006, "s": 174988, "text": "SetStretchBltMode" }, { "code": null, "e": 175039, "s": 175006, "text": "Sets the bitmap-stretching mode." }, { "code": null, "e": 175052, "s": 175039, "text": "SetTextAlign" }, { "code": null, "e": 175083, "s": 175052, "text": "Sets the text-alignment flags." }, { "code": null, "e": 175105, "s": 175083, "text": "SetTextCharacterExtra" }, { "code": null, "e": 175148, "s": 175105, "text": "Sets the amount of intercharacter spacing." }, { "code": null, "e": 175161, "s": 175148, "text": "SetTextColor" }, { "code": null, "e": 175182, "s": 175161, "text": "Sets the text color." }, { "code": null, "e": 175203, "s": 175182, "text": "SetTextJustification" }, { "code": null, "e": 175251, "s": 175203, "text": "Adds space to the break characters in a string." }, { "code": null, "e": 175266, "s": 175251, "text": "SetViewportExt" }, { "code": null, "e": 175309, "s": 175266, "text": "Sets the x- and y-extents of the viewport." }, { "code": null, "e": 175324, "s": 175309, "text": "SetViewportOrg" }, { "code": null, "e": 175350, "s": 175324, "text": "Sets the viewport origin." }, { "code": null, "e": 175363, "s": 175350, "text": "SetWindowExt" }, { "code": null, "e": 175415, "s": 175363, "text": "Sets the x- and y-extents of the associated window." }, { "code": null, "e": 175428, "s": 175415, "text": "SetWindowOrg" }, { "code": null, "e": 175474, "s": 175428, "text": "Sets the window origin of the device context." }, { "code": null, "e": 175492, "s": 175474, "text": "SetWorldTransform" }, { "code": null, "e": 175551, "s": 175492, "text": "Sets the current world-space to page-space transformation." }, { "code": null, "e": 175560, "s": 175551, "text": "StartDoc" }, { "code": null, "e": 175620, "s": 175560, "text": "Informs the device driver that a new print job is starting." }, { "code": null, "e": 175630, "s": 175620, "text": "StartPage" }, { "code": null, "e": 175685, "s": 175630, "text": "Informs the device driver that a new page is starting." }, { "code": null, "e": 175696, "s": 175685, "text": "StretchBlt" }, { "code": null, "e": 175878, "s": 175696, "text": "Moves a bitmap from a source rectangle and device into a destination rectangle, stretching or compressing the bitmap if necessary to fit the dimensions of the destination rectangle." }, { "code": null, "e": 175896, "s": 175878, "text": "StrokeAndFillPath" }, { "code": null, "e": 176040, "s": 175896, "text": "Closes any open figures in a path, strikes the outline of the path by using the current pen, and fills its interior by using the current brush." }, { "code": null, "e": 176051, "s": 176040, "text": "StrokePath" }, { "code": null, "e": 176104, "s": 176051, "text": "Renders the specified path by using the current pen." }, { "code": null, "e": 176118, "s": 176104, "text": "TabbedTextOut" }, { "code": null, "e": 176243, "s": 176118, "text": "Writes a character string at a specified location, expanding tabs to the values specified in an array of tab-stop positions." }, { "code": null, "e": 176251, "s": 176243, "text": "TextOut" }, { "code": null, "e": 176336, "s": 176251, "text": "Writes a character string at a specified location using the currently selected font." }, { "code": null, "e": 176351, "s": 176336, "text": "TransparentBlt" }, { "code": null, "e": 176520, "s": 176351, "text": "Transfers a bit-block of color data from the specified source device context into a destination device context, rendering a specified color transparent in the transfer." }, { "code": null, "e": 176533, "s": 176520, "text": "UpdateColors" }, { "code": null, "e": 176678, "s": 176533, "text": "Updates the client area of the device context by matching the current colors in the client area to the system palette on a pixel-by-pixel basis." }, { "code": null, "e": 176688, "s": 176678, "text": "WidenPath" }, { "code": null, "e": 176832, "s": 176688, "text": "Redefines the current path as the area that would be painted if the path were stroked using the pen currently selected into the device context." }, { "code": null, "e": 176949, "s": 176832, "text": "Step 1 − Let us look into a simple example by creating a new MFC based single document project with MFCGDIDemo name." }, { "code": null, "e": 177091, "s": 176949, "text": "Step 2 − Once the project is created, go the Solution Explorer and double click on the MFCGDIDemoView.cpp file under the Source Files folder." }, { "code": null, "e": 177166, "s": 177091, "text": "Step 3 − Draw the line as shown below in CMFCGDIDemoView::OnDraw() method." }, { "code": null, "e": 177400, "s": 177166, "text": "void CMFCGDIDemoView::OnDraw(CDC* pDC) {\n pDC->MoveTo(95, 125);\n pDC->LineTo(230, 125);\n CMFCGDIDemoDoc* pDoc = GetDocument();\n ASSERT_VALID(pDoc);\n if (!pDoc)\n return;\n\n // TODO: add draw code for native data here\n}" }, { "code": null, "e": 177466, "s": 177400, "text": "Step 4 − Run this application. You will see the following output." }, { "code": null, "e": 177548, "s": 177466, "text": "Step 5 − The CDC::MoveTo() method is used to set the starting position of a line." }, { "code": null, "e": 177633, "s": 177548, "text": "When using LineTo(), the program starts from the MoveTo() point to the LineTo() end." }, { "code": null, "e": 177810, "s": 177633, "text": "After LineTo() when you do not call MoveTo(), and call again LineTo() with other point value, the program will draw a line from the previous LineTo() to the new LineTo() point." }, { "code": null, "e": 177902, "s": 177810, "text": "Step 6 − To draw different lines, you can use this property as shown in the following code." }, { "code": null, "e": 178189, "s": 177902, "text": "void CMFCGDIDemoView::OnDraw(CDC* pDC) { \n pDC->MoveTo(95, 125);\n pDC->LineTo(230, 125);\n pDC->LineTo(230, 225);\n pDC->LineTo(95, 325);\n CMFCGDIDemoDoc* pDoc = GetDocument();\n ASSERT_VALID(pDoc);\n if (!pDoc)\n return;\n\n // TODO: add draw code for native data here \n}" }, { "code": null, "e": 178255, "s": 178189, "text": "Step 7 − Run this application. You will see the following output." }, { "code": null, "e": 178624, "s": 178255, "text": "A polyline is a series of connected lines. The lines are stored in an array of POINT or CPoint values. To draw a polyline, you use the CDC::Polyline() method. To draw a polyline, at least two points are required. If you define more than two points, each line after the first would be drawn from the previous point to the next point until all points have been included." }, { "code": null, "e": 178668, "s": 178624, "text": "Step 1 − Let us look into a simple example." }, { "code": null, "e": 178981, "s": 178668, "text": "void CMFCGDIDemoView::OnDraw(CDC* pDC) {\n CPoint Pt[7];\n Pt[0] = CPoint(20, 150);\n Pt[1] = CPoint(180, 150);\n Pt[2] = CPoint(180, 20);\n pDC−Polyline(Pt, 3);\n \n CMFCGDIDemoDoc* pDoc = GetDocument();\n ASSERT_VALID(pDoc);\n if (!pDoc)\n return;\n\n // TODO: add draw code for native data here\n}" }, { "code": null, "e": 179056, "s": 178981, "text": "Step 2 − When you run this application, you will see the following output." }, { "code": null, "e": 179290, "s": 179056, "text": "A rectangle is a geometric figure made of four sides that compose four right angles. Like the line, to draw a rectangle, you must define where it starts and where it ends. To draw a rectangle, you can use the CDC::Rectangle() method." }, { "code": null, "e": 179334, "s": 179290, "text": "Step 1 − Let us look into a simple example." }, { "code": null, "e": 179558, "s": 179334, "text": "void CMFCGDIDemoView::OnDraw(CDC* pDC) {\n pDC->Rectangle(15, 15, 250, 160);\n \n CMFCGDIDemoDoc* pDoc = GetDocument();\n ASSERT_VALID(pDoc);\n if (!pDoc)\n return;\n\n // TODO: add draw code for native data here\n}" }, { "code": null, "e": 179633, "s": 179558, "text": "Step 2 − When you run this application, you will see the following output." }, { "code": null, "e": 179754, "s": 179633, "text": "A square is a geometric figure made of four sides that compose four right angles, but each side must be equal in length." }, { "code": null, "e": 179789, "s": 179754, "text": "Let us look into a simple example." }, { "code": null, "e": 180013, "s": 179789, "text": "void CMFCGDIDemoView::OnDraw(CDC* pDC) {\n pDC->Rectangle(15, 15, 250, 250);\n \n CMFCGDIDemoDoc* pDoc = GetDocument();\n ASSERT_VALID(pDoc);\n if (!pDoc)\n return;\n\n // TODO: add draw code for native data here\n}" }, { "code": null, "e": 180079, "s": 180013, "text": "When you run this application, you will see the following output." }, { "code": null, "e": 180261, "s": 180079, "text": "A pie is a fraction of an ellipse delimited by two lines that span from the center of the ellipse to one side each. To draw a pie, you can use the CDC::Pie() method as shown below −" }, { "code": null, "e": 180335, "s": 180261, "text": "BOOL Pie(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4);" }, { "code": null, "e": 180519, "s": 180335, "text": "The (x1, y1) point determines the upper-left corner of the rectangle in which the ellipse that represents the pie fits. The (x2, y2) point is the bottom-right corner of the rectangle." }, { "code": null, "e": 180703, "s": 180519, "text": "The (x1, y1) point determines the upper-left corner of the rectangle in which the ellipse that represents the pie fits. The (x2, y2) point is the bottom-right corner of the rectangle." }, { "code": null, "e": 180804, "s": 180703, "text": "The (x3, y3) point specifies the starting corner of the pie in a default counterclockwise direction." }, { "code": null, "e": 180905, "s": 180804, "text": "The (x3, y3) point specifies the starting corner of the pie in a default counterclockwise direction." }, { "code": null, "e": 180958, "s": 180905, "text": "The (x4, y4) point species the end point of the pie." }, { "code": null, "e": 181011, "s": 180958, "text": "The (x4, y4) point species the end point of the pie." }, { "code": null, "e": 181046, "s": 181011, "text": "Let us look into a simple example." }, { "code": null, "e": 181283, "s": 181046, "text": "void CMFCGDIDemoView::OnDraw(CDC* pDC) {\n pDC->Pie(40, 20, 226, 144, 155, 32, 202, 115);\n \n CMFCGDIDemoDoc* pDoc = GetDocument();\n ASSERT_VALID(pDoc);\n if (!pDoc)\n return;\n\n // TODO: add draw code for native data here\n}" }, { "code": null, "e": 181358, "s": 181283, "text": "Step 2 − When you run this application, you will see the following output." }, { "code": null, "e": 181497, "s": 181358, "text": "An arc is a portion or segment of an ellipse, meaning an arc is a non-complete ellipse. To draw an arc, you can use the CDC::Arc() method." }, { "code": null, "e": 181571, "s": 181497, "text": "BOOL Arc(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4);" }, { "code": null, "e": 181632, "s": 181571, "text": "The CDC class is equipped with the SetArcDirection() method." }, { "code": null, "e": 181653, "s": 181632, "text": "Here is the syntax −" }, { "code": null, "e": 181693, "s": 181653, "text": "int SetArcDirection(int nArcDirection)\n" }, { "code": null, "e": 181706, "s": 181693, "text": "AD_CLOCKWISE" }, { "code": null, "e": 181736, "s": 181706, "text": "The figure is drawn clockwise" }, { "code": null, "e": 181756, "s": 181736, "text": "AD_COUNTERCLOCKWISE" }, { "code": null, "e": 181793, "s": 181756, "text": "The figure is drawn counterclockwise" }, { "code": null, "e": 181837, "s": 181793, "text": "Step 1 − Let us look into a simple example." }, { "code": null, "e": 182120, "s": 181837, "text": "void CMFCGDIDemoView::OnDraw(CDC* pDC) {\n pDC->SetArcDirection(AD_COUNTERCLOCKWISE);\n pDC->Arc(20, 20, 226, 144, 202, 115, 105, 32);\n \n CMFCGDIDemoDoc* pDoc = GetDocument();\n ASSERT_VALID(pDoc);\n if (!pDoc)\n return;\n\n // TODO: add draw code for native data here\n}" }, { "code": null, "e": 182195, "s": 182120, "text": "Step 2 − When you run this application, you will see the following output." }, { "code": null, "e": 182430, "s": 182195, "text": "The arcs we have drawn so far are considered open figures because they are made of a line that has a beginning and an end (unlike a circle or a rectangle that do not). A chord is an arc whose two ends are connected by a straight line." }, { "code": null, "e": 182484, "s": 182430, "text": "To draw a chord, you can use the CDC::Chord() method." }, { "code": null, "e": 182560, "s": 182484, "text": "BOOL Chord(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4);" }, { "code": null, "e": 182595, "s": 182560, "text": "Let us look into a simple example." }, { "code": null, "e": 182873, "s": 182595, "text": "void CMFCGDIDemoView::OnDraw(CDC* pDC) {\n pDC->SetArcDirection(AD_CLOCKWISE);\n pDC->Chord(20, 20, 226, 144, 202, 115, 105, 32);\n \n CMFCGDIDemoDoc* pDoc = GetDocument();\n ASSERT_VALID(pDoc);\n if (!pDoc)\n return;\n\n // TODO: add draw code for native data here\n}" }, { "code": null, "e": 182944, "s": 182873, "text": "When you run the above application, you will see the following output." }, { "code": null, "e": 182996, "s": 182944, "text": "The arc direction in this example is set clockwise." }, { "code": null, "e": 183329, "s": 182996, "text": "The color is one the most fundamental objects that enhances the aesthetic appearance of an object. The color is a non-spatial object that is added to an object to modify some of its visual aspects. The MFC library, combined with the Win32 API, provides various actions you can use to take advantage of the various aspects of colors." }, { "code": null, "e": 183502, "s": 183329, "text": "The RGB macro behaves like a function and allows you to pass three numeric values separated by a comma. Each value must be between 0 and 255 as shown in the following code." }, { "code": null, "e": 183584, "s": 183502, "text": "void CMFCGDIDemoView::OnDraw(CDC* pDC) {\n COLORREF color = RGB(239, 15, 225);\n}" }, { "code": null, "e": 183619, "s": 183584, "text": "Let us look into a simple example." }, { "code": null, "e": 183925, "s": 183619, "text": "void CMFCGDIDemoView::OnDraw(CDC* pDC) {\n COLORREF color = RGB(239, 15, 225);\n pDC->SetTextColor(color);\n pDC->TextOut(100, 80, L\"MFC GDI Tutorial\", 16);\n \n CMFCGDIDemoDoc* pDoc = GetDocument();\n ASSERT_VALID(pDoc);\n if (!pDoc)\n return;\n\n // TODO: add draw code for native data here\n}" }, { "code": null, "e": 183991, "s": 183925, "text": "When you run this application, you will see the following output." }, { "code": null, "e": 184262, "s": 183991, "text": "CFont encapsulates a Windows graphics device interface (GDI) font and provides member functions for manipulating the font. To use a CFont object, construct a CFont object and attach a Windows font to it, and then use the object's member functions to manipulate the font." }, { "code": null, "e": 184273, "s": 184262, "text": "CreateFont" }, { "code": null, "e": 184329, "s": 184273, "text": "Initializes a CFont with the specified characteristics." }, { "code": null, "e": 184348, "s": 184329, "text": "CreateFontIndirect" }, { "code": null, "e": 184430, "s": 184348, "text": "Initializes a CFont object with the characteristics given in a LOGFONT structure." }, { "code": null, "e": 184446, "s": 184430, "text": "CreatePointFont" }, { "code": null, "e": 184538, "s": 184446, "text": "Initializes a CFont with the specified height, measured in tenths of a point, and typeface." }, { "code": null, "e": 184562, "s": 184538, "text": "CreatePointFontIndirect" }, { "code": null, "e": 184677, "s": 184562, "text": "Same as CreateFontIndirect except that the font height is measured in tenths of a point rather than logical units." }, { "code": null, "e": 184688, "s": 184677, "text": "FromHandle" }, { "code": null, "e": 184752, "s": 184688, "text": "Returns a pointer to a CFont object when given a Windows HFONT." }, { "code": null, "e": 184763, "s": 184752, "text": "GetLogFont" }, { "code": null, "e": 184849, "s": 184763, "text": "Fills a LOGFONT with information about the logical font attached to the CFont object." }, { "code": null, "e": 184884, "s": 184849, "text": "Let us look into a simple example." }, { "code": null, "e": 185342, "s": 184884, "text": "void CMFCGDIDemoView::OnDraw(CDC* pDC) {\n CFont font;\n font.CreatePointFont(920, L\"Garamond\");\n CFont *pFont = pDC->SelectObject(&font);\n COLORREF color = RGB(239, 15, 225);\n pDC->SetTextColor(color);\n pDC->TextOut(100, 80, L\"MFC GDI Tutorial\", 16);\n pDC->SelectObject(pFont);\n font.DeleteObject();\n \n CMFCGDIDemoDoc* pDoc = GetDocument();\n ASSERT_VALID(pDoc);\n if (!pDoc)\n return;\n\n // TODO: add draw code for native data here\n}" }, { "code": null, "e": 185413, "s": 185342, "text": "When you run the above application, you will see the following output." }, { "code": null, "e": 185682, "s": 185413, "text": "A pen is a tool used to draw lines and curves on a device context. In the graphics programming, a pen is also used to draw the borders of a geometric closed shape such as a rectangle or a polygon. Microsoft Windows considers two types of pens — cosmetic and geometric." }, { "code": null, "e": 185975, "s": 185682, "text": "A pen is referred to as cosmetic when it can be used to draw only simple lines of a fixed width, less than or equal to 1 pixel. A pen is geometric when it can assume different widths and various ends. MFC provides a class CPen which encapsulates a Windows graphics device interface (GDI) pen." }, { "code": null, "e": 185985, "s": 185975, "text": "CreatePen" }, { "code": null, "e": 186120, "s": 185985, "text": "Creates a logical cosmetic or geometric pen with the specified style, width, and brush attributes, and attaches it to the CPen object." }, { "code": null, "e": 186138, "s": 186120, "text": "CreatePenIndirect" }, { "code": null, "e": 186250, "s": 186138, "text": "Creates a pen with the style, width, and color given in a LOGPEN structure, and attaches it to the CPen object." }, { "code": null, "e": 186261, "s": 186250, "text": "FromHandle" }, { "code": null, "e": 186323, "s": 186261, "text": "Returns a pointer to a CPen object when\ngiven a Windows HPEN." }, { "code": null, "e": 186336, "s": 186323, "text": "GetExtLogPen" }, { "code": null, "e": 186376, "s": 186336, "text": "Gets an EXTLOGPEN underlying structure." }, { "code": null, "e": 186386, "s": 186376, "text": "GetLogPen" }, { "code": null, "e": 186422, "s": 186386, "text": "Gets a LOGPEN underlying structure." }, { "code": null, "e": 186431, "s": 186422, "text": "PS_SOLID" }, { "code": null, "e": 186456, "s": 186431, "text": "A continuous solid line." }, { "code": null, "e": 186464, "s": 186456, "text": "PS_DASH" }, { "code": null, "e": 186509, "s": 186464, "text": "A continuous line with dashed interruptions." }, { "code": null, "e": 186516, "s": 186509, "text": "PS_DOT" }, { "code": null, "e": 186569, "s": 186516, "text": "A line with a dot interruption at every other pixel." }, { "code": null, "e": 186580, "s": 186569, "text": "PS_DASHDOT" }, { "code": null, "e": 186635, "s": 186580, "text": "A combination of alternating dashed and dotted points." }, { "code": null, "e": 186649, "s": 186635, "text": "PS_DASHDOTDOT" }, { "code": null, "e": 186704, "s": 186649, "text": "A combination of dash and double dotted interruptions." }, { "code": null, "e": 186712, "s": 186704, "text": "PS_NULL" }, { "code": null, "e": 186729, "s": 186712, "text": "No visible line." }, { "code": null, "e": 186744, "s": 186729, "text": "PS_INSIDEFRAME" }, { "code": null, "e": 186802, "s": 186744, "text": "A line drawn just inside of the border of a closed shape." }, { "code": null, "e": 186837, "s": 186802, "text": "Let us look into a simple example." }, { "code": null, "e": 187156, "s": 186837, "text": "void CMFCGDIDemoView::OnDraw(CDC* pDC) {\n CPen pen;\n pen.CreatePen(PS_DASHDOTDOT, 1, RGB(160, 75, 90));\n pDC->SelectObject(&pen);\n pDC->Rectangle(25, 35, 250, 125);\n \n CMFCGDIDemoDoc* pDoc = GetDocument();\n ASSERT_VALID(pDoc);\n if (!pDoc)\n return;\n\n // TODO: add draw code for native data here\n}" }, { "code": null, "e": 187227, "s": 187156, "text": "When you run the above application, you will see the following output." }, { "code": null, "e": 187482, "s": 187227, "text": "A brush is a drawing tool used to fill out closed shaped or the interior of lines. A brush behaves like picking up a bucket of paint and pouring it somewhere. MFC provides a class CBrush which encapsulates a Windows graphics device interface (GDI) brush." }, { "code": null, "e": 187502, "s": 187482, "text": "CreateBrushIndirect" }, { "code": null, "e": 187592, "s": 187502, "text": "Initializes a brush with the style, color, and pattern specified in a LOGBRUSH structure." }, { "code": null, "e": 187614, "s": 187592, "text": "CreateDIBPatternBrush" }, { "code": null, "e": 187697, "s": 187614, "text": "Initializes a brush with a pattern specified by a device-independent bitmap (DIB)." }, { "code": null, "e": 187714, "s": 187697, "text": "CreateHatchBrush" }, { "code": null, "e": 187780, "s": 187714, "text": "Initializes a brush with the specified hatched pattern and color." }, { "code": null, "e": 187799, "s": 187780, "text": "CreatePatternBrush" }, { "code": null, "e": 187857, "s": 187799, "text": "Initializes a brush with a pattern specified by a bitmap." }, { "code": null, "e": 187874, "s": 187857, "text": "CreateSolidBrush" }, { "code": null, "e": 187926, "s": 187874, "text": "Initializes a brush with the specified solid color." }, { "code": null, "e": 187946, "s": 187926, "text": "CreateSysColorBrush" }, { "code": null, "e": 187996, "s": 187946, "text": "Creates a brush that is the default system color." }, { "code": null, "e": 188007, "s": 187996, "text": "FromHandle" }, { "code": null, "e": 188092, "s": 188007, "text": "Returns a pointer to a CBrush object when given a handle to a Windows HBRUSH object." }, { "code": null, "e": 188104, "s": 188092, "text": "GetLogBrush" }, { "code": null, "e": 188131, "s": 188104, "text": "Gets a LOGBRUSH structure." }, { "code": null, "e": 188166, "s": 188131, "text": "Let us look into a simple example." }, { "code": null, "e": 188504, "s": 188166, "text": "void CMFCGDIDemoView::OnDraw(CDC* pDC) {\n CBrush brush(RGB(100, 150, 200));\n CBrush *pBrush = pDC->SelectObject(&brush);\n pDC->Rectangle(25, 35, 250, 125);\n pDC->SelectObject(pBrush);\n \n CMFCGDIDemoDoc* pDoc = GetDocument();\n ASSERT_VALID(pDoc);\n if (!pDoc)\n return;\n\n // TODO: add draw code for native data here\n}" }, { "code": null, "e": 188570, "s": 188504, "text": "When you run this application, you will see the following output." }, { "code": null, "e": 189049, "s": 188570, "text": "A library is a group of functions, classes, or other resources that can be made available to programs that need already implemented entities without the need to know how these functions, classes, or resources were created or how they function. A library makes it easy for a programmer to use functions, classes, and resources etc. created by another person or company and trust that this external source is reliable and efficient. Some unique features related to libraries are −" }, { "code": null, "e": 189189, "s": 189049, "text": "A library is created and functions like a normal regular program, using functions or other resources and communicating with other programs." }, { "code": null, "e": 189329, "s": 189189, "text": "A library is created and functions like a normal regular program, using functions or other resources and communicating with other programs." }, { "code": null, "e": 189454, "s": 189329, "text": "To implement its functionality, a library contains functions that other programs would need to complete their functionality." }, { "code": null, "e": 189579, "s": 189454, "text": "To implement its functionality, a library contains functions that other programs would need to complete their functionality." }, { "code": null, "e": 189666, "s": 189579, "text": "At the same time, a library may use some functions that other programs would not need." }, { "code": null, "e": 189753, "s": 189666, "text": "At the same time, a library may use some functions that other programs would not need." }, { "code": null, "e": 189832, "s": 189753, "text": "The program that uses the library, are also called the clients of the library." }, { "code": null, "e": 189911, "s": 189832, "text": "The program that uses the library, are also called the clients of the library." }, { "code": null, "e": 189991, "s": 189911, "text": "There are two types of functions you will create or include in your libraries −" }, { "code": null, "e": 190119, "s": 189991, "text": "An internal function is one used only by the library itself and clients of the library will not need access to these functions." }, { "code": null, "e": 190247, "s": 190119, "text": "An internal function is one used only by the library itself and clients of the library will not need access to these functions." }, { "code": null, "e": 190328, "s": 190247, "text": "External functions are those that can be accessed by the clients of the library." }, { "code": null, "e": 190409, "s": 190328, "text": "External functions are those that can be accessed by the clients of the library." }, { "code": null, "e": 190491, "s": 190409, "text": "There are two broad categories of libraries you will deal with in your programs −" }, { "code": null, "e": 190508, "s": 190491, "text": "Static libraries" }, { "code": null, "e": 190526, "s": 190508, "text": "Dynamic libraries" }, { "code": null, "e": 190840, "s": 190526, "text": "A static library is a file that contains functions, classes, or resources that an external program can use to complement its functionality. To use a library, the programmer has to create a link to it. The project can be a console application, a Win32 or an MFC application. The library file has the lib extension." }, { "code": null, "e": 190934, "s": 190840, "text": "Step 1 − Let us look into a simple example of static library by creating a new Win32 Project." }, { "code": null, "e": 191011, "s": 190934, "text": "Step 2 − On Application Wizard dialog box, choose the Static Library option." }, { "code": null, "e": 191046, "s": 191011, "text": "Step 3 − Click Finish to continue." }, { "code": null, "e": 191160, "s": 191046, "text": "Step 4 − Right-click on the project in solution explorer and add a header file from Add → New Item...menu option." }, { "code": null, "e": 191221, "s": 191160, "text": "Step 5 − Enter Calculator.h in the Name field and click Add." }, { "code": null, "e": 191265, "s": 191221, "text": "Add the following code in the header file −" }, { "code": null, "e": 191612, "s": 191265, "text": "#pragma once\n#ifndef _CALCULATOR_H_\n#define _CALCULATOR_H_\ndouble Min(const double *Numbers, const int Count);\ndouble Max(const double *Numbers, const int Count);\ndouble Sum(const double *Numbers, const int Count);\ndouble Average(const double *Numbers, const int Count);\nlong GreatestCommonDivisor(long Nbr1, long Nbr2);\n#endif // _CALCULATOR_H_\n" }, { "code": null, "e": 191663, "s": 191612, "text": "Step 6 − Add a source (*.cpp) file in the project." }, { "code": null, "e": 191726, "s": 191663, "text": "Step 7 − Enter Calculator.cpp in the Name field and click Add." }, { "code": null, "e": 191778, "s": 191726, "text": "Step 8 − Add the following code in the *.cpp file −" }, { "code": null, "e": 192714, "s": 191778, "text": "#include \"StdAfx.h\"\n#include \"Calculator.h\"\ndouble Min(const double *Nbr, const int Total) {\n double Minimum = Nbr[0];\n for (int i = 0; i < Total; i++)\n if (Minimum > Nbr[i])\n Minimum = Nbr[i];\n return Minimum;\n}\ndouble Max(const double *Nbr, const int Total) {\n double Maximum = Nbr[0];\n for (int i = 0; i < Total; i++)\n if (Maximum < Nbr[i])\n Maximum = Nbr[i];\n return Maximum;\n}\ndouble Sum(const double *Nbr, const int Total) {\n double S = 0;\n for (int i = 0; i < Total; i++)\n S += Nbr[i];\n return S;\n}\ndouble Average(const double *Nbr, const int Total) {\n double avg, S = 0;\n for (int i = 0; i < Total; i++)\n S += Nbr[i];\n avg = S / Total;\n return avg;\n}\nlong GreatestCommonDivisor(long Nbr1, long Nbr2) {\n while (true) {\n Nbr1 = Nbr1 % Nbr2;\n if (Nbr1 == 0)\n return Nbr2;\n Nbr2 = Nbr2 % Nbr1;\n if (Nbr2 == 0)\n return Nbr1;\n }\n}" }, { "code": null, "e": 192796, "s": 192714, "text": "Step 9 − Build this library from the main menu, by clicking Build → Build MFCLib." }, { "code": null, "e": 192877, "s": 192796, "text": "Step 10 − When library is built successfully, it will display the above message." }, { "code": null, "e": 193003, "s": 192877, "text": "Step 11 − To use these functions from the library, let us add another MFC dialog application based from File → New → Project." }, { "code": null, "e": 193146, "s": 193003, "text": "Step 12 − Go to the MFCLib\\Debug folder and copy the header file and *.lib files to the MFCLibTest project as shown in the following snapshot." }, { "code": null, "e": 193274, "s": 193146, "text": "Step 13 − To add the library to the current project, on the main menu, click Project → Add Existing Item and select MFCLib.lib." }, { "code": null, "e": 193343, "s": 193274, "text": "Step 14 − Design your dialog box as shown in the following snapshot." }, { "code": null, "e": 193417, "s": 193343, "text": "Step 15 − Add value variable for both edit controls of value type double." }, { "code": null, "e": 193510, "s": 193417, "text": "Step 16 − Add value variable for Static text control, which is at the end of the dialog box." }, { "code": null, "e": 193564, "s": 193510, "text": "Step 17 − Add the event handler for Calculate button." }, { "code": null, "e": 193666, "s": 193564, "text": "To add functionality from the library, we need to include the header file in CMFCLibTestDlg.cpp file." }, { "code": null, "e": 193787, "s": 193666, "text": "#include \"stdafx.h\"\n#include \"MFCLibTest.h\"\n#include \"MFCLibTestDlg.h\"\n#include \"afxdialogex.h\"\n#include \"Calculator.h\"\n" }, { "code": null, "e": 193849, "s": 193787, "text": "Step 18 − Here is the implementation of button event handler." }, { "code": null, "e": 194584, "s": 193849, "text": "void CMFCLibTestDlg::OnBnClickedButtonCal() {\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n CString strTemp;\n double numbers[2];\n numbers[0] = m_Num1;\n numbers[1] = m_Num2;\n\n strTemp.Format(L\"%.2f\", Max(numbers,2));\n m_strText.Append(L\"Max is:\\t\" + strTemp);\n\n strTemp.Format(L\"%.2f\", Min(numbers, 2));\n m_strText.Append(L\"\\nMin is:\\t\" + strTemp);\n \n strTemp.Format(L\"%.2f\", Sum(numbers, 2));\n m_strText.Append(L\"\\nSum is:\\t\" + strTemp);\n\n strTemp.Format(L\"%.2f\", Average(numbers, 2));\n m_strText.Append(L\"\\nAverage is:\\t\" + strTemp);\n\n strTemp.Format(L\"%d\", GreatestCommonDivisor(m_Num1, m_Num2));\n m_strText.Append(L\"\\nGDC is:\\t\" + strTemp);\n\n UpdateData(FALSE);\n}" }, { "code": null, "e": 194675, "s": 194584, "text": "Step 19 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 194805, "s": 194675, "text": "Step 20 − Enter two values in the edit field and click Calculate. You will now see the result after calculating from the library." }, { "code": null, "e": 194998, "s": 194805, "text": "A Win32 DLL is a library that can be made available to programs that run on a Microsoft Windows computer. As a normal library, it is made of functions and/or other resources grouped in a file." }, { "code": null, "e": 195214, "s": 194998, "text": "The DLL abbreviation stands for Dynamic Link Library. This means that, as opposed to a static library, a DLL allows the programmer to decide on when and how other applications will be linked to this type of library." }, { "code": null, "e": 195512, "s": 195214, "text": "For example, a DLL allows difference applications to use its library as they see fit and as necessary. In fact, applications created on different programming environments can use functions or resources stored in one particular DLL. For this reason, an application dynamically links to the library." }, { "code": null, "e": 195588, "s": 195512, "text": "Step 1 − Let us look into a simple example by creating a new Win32 Project." }, { "code": null, "e": 195658, "s": 195588, "text": "Step 2 − In the Application Type section, click the DLL radio button." }, { "code": null, "e": 195693, "s": 195658, "text": "Step 3 − Click Finish to continue." }, { "code": null, "e": 195794, "s": 195693, "text": "Step 4 − Add the following functions in MFCDynamicLib.cpp file and expose its definitions by using −" }, { "code": null, "e": 195827, "s": 195794, "text": "extern \"C\" _declspec(dllexport)\n" }, { "code": null, "e": 195931, "s": 195827, "text": "Step 5 − Use the _declspec(dllexport) modifier for each function that will be accessed outside the DLL." }, { "code": null, "e": 197347, "s": 195931, "text": "// MFCDynamicLib.cpp : Defines the exported functions for the DLL application.//\n\n#include \"stdafx.h\"\n\nextern \"C\" _declspec(dllexport) double Min(const double *Numbers, const int Count);\nextern \"C\" _declspec(dllexport) double Max(const double *Numbers, const int Count);\nextern \"C\" _declspec(dllexport) double Sum(const double *Numbers, const int Count);\nextern \"C\" _declspec(dllexport) double Average(const double *Numbers, const int Count);\nextern \"C\" _declspec(dllexport) long GreatestCommonDivisor(long Nbr1, long Nbr2);\n\ndouble Min(const double *Nbr, const int Total) {\n double Minimum = Nbr[0];\n for (int i = 0; i < Total; i++)\n if (Minimum > Nbr[i])\n Minimum = Nbr[i];\n return Minimum;\n}\ndouble Max(const double *Nbr, const int Total) {\n double Maximum = Nbr[0];\n for (int i = 0; i < Total; i++)\n if (Maximum < Nbr[i])\n Maximum = Nbr[i];\n return Maximum;\n}\ndouble Sum(const double *Nbr, const int Total) {\n double S = 0;\n for (int i = 0; i < Total; i++)\n S += Nbr[i];\n return S;\n}\ndouble Average(const double *Nbr, const int Total){\n double avg, S = 0;\n for (int i = 0; i < Total; i++)\n S += Nbr[i];\n avg = S / Total;\n return avg;\n}\nlong GreatestCommonDivisor(long Nbr1, long Nbr2) {\n while (true) {\n Nbr1 = Nbr1 % Nbr2;\n if (Nbr1 == 0)\n return Nbr2;\n Nbr2 = Nbr2 % Nbr1;\n if (Nbr2 == 0)\n return Nbr1;\n }\n}" }, { "code": null, "e": 197447, "s": 197347, "text": "Step 6 − To create the DLL, on the main menu, click Build > Build MFCDynamicLib from the main menu." }, { "code": null, "e": 197542, "s": 197447, "text": "Step 7 − Once the DLL is successfully created, you will see amessage display in output window." }, { "code": null, "e": 197623, "s": 197542, "text": "Step 8 − Open Windows Explorer and then the Debug folder of the current project." }, { "code": null, "e": 197724, "s": 197623, "text": "Step 9 − Notice that a file with dll extension and another file with lib extension has been created." }, { "code": null, "e": 197852, "s": 197724, "text": "Step 10 − To test this file with dll extension, we need to create a new MFC dialog based application from File → New → Project." }, { "code": null, "e": 197996, "s": 197852, "text": "Step 11 − Go to the MFCDynamicLib\\Debug folder and copy the *.dll and *.lib files to the MFCLibTest project as shown in the following snapshot." }, { "code": null, "e": 198138, "s": 197996, "text": "Step 12 − To add the DLL to the current project, on the main menu, click Project → Add Existing Item and then, select MFCDynamicLib.lib file." }, { "code": null, "e": 198207, "s": 198138, "text": "Step 13 − Design your dialog box as shown in the following snapshot." }, { "code": null, "e": 198281, "s": 198207, "text": "Step 14 − Add value variable for both edit controls of value type double." }, { "code": null, "e": 198374, "s": 198281, "text": "Step 15 − Add value variable for Static text control, which is at the end of the dialog box." }, { "code": null, "e": 198428, "s": 198374, "text": "Step 16 − Add the event handler for Calculate button." }, { "code": null, "e": 198570, "s": 198428, "text": "Step 17 − In the project that is using the DLL, each function that will be accessed must be declared using the _declspec(dllimport) modifier." }, { "code": null, "e": 198646, "s": 198570, "text": "Step 18 − Add the following function declaration in MFCLibTestDlg.cpp file." }, { "code": null, "e": 199069, "s": 198646, "text": "extern \"C\" _declspec(dllimport) double Min(const double *Numbers, const int Count);\nextern \"C\" _declspec(dllimport) double Max(const double *Numbers, const int Count);\nextern \"C\" _declspec(dllimport) double Sum(const double *Numbers, const int Count);\nextern \"C\" _declspec(dllimport) double Average(const double *Numbers, const int Count);\nextern \"C\" _declspec(dllimport) long GreatestCommonDivisor(long Nbr1, long Nbr2);\n" }, { "code": null, "e": 199131, "s": 199069, "text": "Step 19 − Here is the implementation of button event handler." }, { "code": null, "e": 199866, "s": 199131, "text": "void CMFCLibTestDlg::OnBnClickedButtonCal() {\n\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n\n CString strTemp;\n double numbers[2];\n numbers[0] = m_Num1;\n numbers[1] = m_Num2;\n\n strTemp.Format(L\"%.2f\", Max(numbers,2));\n m_strText.Append(L\"Max is:\\t\" + strTemp);\n\n strTemp.Format(L\"%.2f\", Min(numbers, 2));\n m_strText.Append(L\"\\nMin is:\\t\" + strTemp);\n\n strTemp.Format(L\"%.2f\", Sum(numbers, 2));\n m_strText.Append(L\"\\nSum is:\\t\" + strTemp);\n\n strTemp.Format(L\"%.2f\", Average(numbers, 2));\n m_strText.Append(L\"\\nAverage is:\\t\" + strTemp);\n\n strTemp.Format(L\"%d\", GreatestCommonDivisor(m_Num1, m_Num2));\n m_strText.Append(L\"\\nGDC is:\\t\" + strTemp);\n \n UpdateData(FALSE);\n}" }, { "code": null, "e": 199957, "s": 199866, "text": "Step 20 − When the above code is compiled and executed, you will see the following output." } ]
Training machine learning models online for free(GPU, TPU enabled)!!! | by Maithreyan Surya | Towards Data Science
Computation power needed to train machine learning and deep learning model on large datasets, has always been a huge hindrance for machine learning enthusiast. But with jupyter notebook which run on cloud anyone who is has the passion to learn can train and come up with great results. In this post I will providing information about the various service that gives us the computation power to us for training models. Google ColabKaggel KernelJupyter Notebook on GCPAmazon SageMakerAzure Notebooks Google Colab Kaggel Kernel Jupyter Notebook on GCP Amazon SageMaker Azure Notebooks Colaboratory is a google research project created to help disseminate machine learning education and research. Colaboratory (colab) provides free Jupyter notebook environment that requires no setup and runs entirely in the cloud.It comes pre-installed with most of the machine learning libraries, it acts as perfect place where you can plug and play and try out stuff where dependency and compute is not an issue. The notebooks are connected to your google drive, so you can acess it any time you want,and also upload or download notebook from github. First, you’ll need to enable GPU or TPU for the notebook. Navigate to Edit→Notebook Settings, and select TPU from the Hardware Accelerator drop-down . code to check whether TPU is enabled import osimport pprintimport tensorflow as tfif ‘COLAB_TPU_ADDR’ not in os.environ: print(‘ERROR: Not connected to a TPU runtime; please see the first cell in this notebook for instructions!’)else: tpu_address = ‘grpc://’ + os.environ[‘COLAB_TPU_ADDR’] print (‘TPU address is’, tpu_address)with tf.Session(tpu_address) as session: devices = session.list_devices() print(‘TPU devices:’) pprint.pprint(devices) Colab comes with most of ml libraries installed,but you can also add libraries easily which are not pre-installed. Colab supports both the pip and apt package managers. !pip install torch apt command !apt-get install graphviz -y both commands work in colab, dont forget the ! (exclamatory) before the command. There are many ways to upload datasets to the notebook One can upload files from the local machine. Upload files from google drive One can also directly upload datasets from kaggle Code to upload from local from google.colab import filesuploaded = files.upload() you can browse and select the file. Upload files from google drive PyDrive library is used to upload and files from google drive !pip install -U -q PyDrivefrom pydrive.auth import GoogleAuthfrom pydrive.drive import GoogleDrivefrom google.colab import authfrom oauth2client.client import GoogleCredentials# 1. Authenticate and create the PyDrive client.auth.authenticate_user()gauth = GoogleAuth()gauth.credentials = GoogleCredentials.get_application_default()drive = GoogleDrive(gauth)# PyDrive reference:# https://gsuitedevs.github.io/PyDrive/docs/build/html/index.html# 2. Create & upload a file text file.uploaded = drive.CreateFile({'title': 'Sample upload.txt'})uploaded.SetContentString('Sample upload file content')uploaded.Upload()print('Uploaded file with ID {}'.format(uploaded.get('id')))# 3. Load a file by ID and print its contents.downloaded = drive.CreateFile({'id': uploaded.get('id')})print('Downloaded content "{}"'.format(downloaded.GetContentString())) You can get id of the file you want to upload,and use the above code. For more resource to upload files from google services. Uploading dataset from kaggle We need to install kaggle api and add authentication json file which you can download from kaggle website(API_TOKEN). !pip install kaggle upload the json file to the notebook by, uploading file from the local machine. create a /.kaggle directory !mkdir -p ~/.kaggle copy the json file to the kaggle directory change the file permision !cp kaggle.json ~/.kaggle/!chmod 600 ~/.kaggle/kaggle.json Now you can use command to download any dataset from kaggle kaggle datasets download -d lazyjustin/pubgplayerstats Now you can use the below to download competition dataset from kaggle,but for that you have to participate in the competition. !kaggle competitions download -c tgs-salt-identification-challenge You can train and run fashion_mnist online without any dependency here. Colab is a great tool for everyone who are interested in machine learning,all the educational resource and code snippets to use colab is provide in the official website itself with notebook examples. Kaggle Kernels is a cloud computational environment that enables reproducible and collaborative analysis. One can run both Python and R code in kaggle kernel Kaggle Kernel runs in a remote computational environment. They provide the hardware needed. At time of writing, each kernel editing session is provided with the following resources: CPU Specifications 4 CPU cores 17 Gigabytes of RAM 6 hours execution time 5 Gigabytes of auto-saved disk space (/kaggle/working) 16 Gigabytes of temporary, scratchpad disk space (outside /kaggle/working) GPU Specifications 2 CPU cores 14 Gigabytes of RAM Once we create an account at kaggle.com, we can choose a dataset to play with and spin up a new kernel,with just a few clicks. Click on create new kernel You will be having jupyter notebook up and running.At the bottom you will be having the console which you can use,and at the right side you will be having various options like When you Commit & Run a kernel, you execute the kernel from top to bottom in a separate session from your interactive session. Once it finishes, you will have generated a new kernel version. A kernel version is a snapshot of your work including your compiled code, log files, output files, data sources, and more. The latest kernel version of your kernel is what is shown to users in the kernel viewer. When you create a kernel for a dataset ,the dataset will be preloaded into the notebook in the input directory ../input/ you can also click on add data source ,to add other datasets Settings Sharing: you can keep your kernel private,or you can also make it public so that others can learn from your kernel. Adding GPU:You can add a single NVIDIA Tesla K80 to your kernel. One of the major benefits to using Kernels as opposed to a local machine or your own VM is that the Kernels environment is already pre-configured with GPU-ready software and packages which can be time consuming and frustrating to set-up.To add a GPU, navigate to the “Settings” pane from the Kernel editor and click the “Enable GPU” option. Custom pakage:The kernel has the default pakages,if you need any other pakage you can easily add it by the following ways Just enter the libarary name ,kaggle will download it for you. Enter the user name/repo name both methods work fine in adding custom pakages. Kaggle acts as a perfect platform for both providing data,and also the compute to work with the great data provided.It also host various competition one can experiment it out to improve one’s skill set. For more resource regarding kaggle link here. If you are new to kaggle you should definitely try the titanic dataset it comes with awesome tutorials. Other resources regarding kaggle ,colab and machine learning follow Siraj Raval, and Yufeng G. Since I was not able to cover all the services to train ml model online in this post,there will be a part2 to this post. All the resource need to learn and practice machine learning is open sourced and available online.From Compute, datasets ,algorithms and there are various high quality tutorials available online for free,all you need is an internet connection,and passion to learn. Thank you for reading till the end,I hope this article would be useful, as it solves the major problem faced by people who are starting the path towards machine learning and data science. If you have enjoyed this article,please let me know by clapping for the article. Queries are most welcomed , you can follow my post in medium maithreyan surya,you can also mail me here. A video intro for using Colab effectively : https://www.youtube.com/playlist?list=PL9a4goxNJut3qyy56AY6Q9Zb2Nm4CQ3Tu Machine learning as the potential to transform the world so do you.
[ { "code": null, "e": 458, "s": 172, "text": "Computation power needed to train machine learning and deep learning model on large datasets, has always been a huge hindrance for machine learning enthusiast. But with jupyter notebook which run on cloud anyone who is has the passion to learn can train and come up with great results." }, { "code": null, "e": 589, "s": 458, "text": "In this post I will providing information about the various service that gives us the computation power to us for training models." }, { "code": null, "e": 669, "s": 589, "text": "Google ColabKaggel KernelJupyter Notebook on GCPAmazon SageMakerAzure Notebooks" }, { "code": null, "e": 682, "s": 669, "text": "Google Colab" }, { "code": null, "e": 696, "s": 682, "text": "Kaggel Kernel" }, { "code": null, "e": 720, "s": 696, "text": "Jupyter Notebook on GCP" }, { "code": null, "e": 737, "s": 720, "text": "Amazon SageMaker" }, { "code": null, "e": 753, "s": 737, "text": "Azure Notebooks" }, { "code": null, "e": 1167, "s": 753, "text": "Colaboratory is a google research project created to help disseminate machine learning education and research. Colaboratory (colab) provides free Jupyter notebook environment that requires no setup and runs entirely in the cloud.It comes pre-installed with most of the machine learning libraries, it acts as perfect place where you can plug and play and try out stuff where dependency and compute is not an issue." }, { "code": null, "e": 1305, "s": 1167, "text": "The notebooks are connected to your google drive, so you can acess it any time you want,and also upload or download notebook from github." }, { "code": null, "e": 1363, "s": 1305, "text": "First, you’ll need to enable GPU or TPU for the notebook." }, { "code": null, "e": 1456, "s": 1363, "text": "Navigate to Edit→Notebook Settings, and select TPU from the Hardware Accelerator drop-down ." }, { "code": null, "e": 1493, "s": 1456, "text": "code to check whether TPU is enabled" }, { "code": null, "e": 1903, "s": 1493, "text": "import osimport pprintimport tensorflow as tfif ‘COLAB_TPU_ADDR’ not in os.environ: print(‘ERROR: Not connected to a TPU runtime; please see the first cell in this notebook for instructions!’)else: tpu_address = ‘grpc://’ + os.environ[‘COLAB_TPU_ADDR’] print (‘TPU address is’, tpu_address)with tf.Session(tpu_address) as session: devices = session.list_devices() print(‘TPU devices:’) pprint.pprint(devices)" }, { "code": null, "e": 2018, "s": 1903, "text": "Colab comes with most of ml libraries installed,but you can also add libraries easily which are not pre-installed." }, { "code": null, "e": 2072, "s": 2018, "text": "Colab supports both the pip and apt package managers." }, { "code": null, "e": 2091, "s": 2072, "text": "!pip install torch" }, { "code": null, "e": 2103, "s": 2091, "text": "apt command" }, { "code": null, "e": 2132, "s": 2103, "text": "!apt-get install graphviz -y" }, { "code": null, "e": 2213, "s": 2132, "text": "both commands work in colab, dont forget the ! (exclamatory) before the command." }, { "code": null, "e": 2268, "s": 2213, "text": "There are many ways to upload datasets to the notebook" }, { "code": null, "e": 2313, "s": 2268, "text": "One can upload files from the local machine." }, { "code": null, "e": 2344, "s": 2313, "text": "Upload files from google drive" }, { "code": null, "e": 2394, "s": 2344, "text": "One can also directly upload datasets from kaggle" }, { "code": null, "e": 2420, "s": 2394, "text": "Code to upload from local" }, { "code": null, "e": 2476, "s": 2420, "text": "from google.colab import filesuploaded = files.upload()" }, { "code": null, "e": 2512, "s": 2476, "text": "you can browse and select the file." }, { "code": null, "e": 2543, "s": 2512, "text": "Upload files from google drive" }, { "code": null, "e": 2605, "s": 2543, "text": "PyDrive library is used to upload and files from google drive" }, { "code": null, "e": 3450, "s": 2605, "text": "!pip install -U -q PyDrivefrom pydrive.auth import GoogleAuthfrom pydrive.drive import GoogleDrivefrom google.colab import authfrom oauth2client.client import GoogleCredentials# 1. Authenticate and create the PyDrive client.auth.authenticate_user()gauth = GoogleAuth()gauth.credentials = GoogleCredentials.get_application_default()drive = GoogleDrive(gauth)# PyDrive reference:# https://gsuitedevs.github.io/PyDrive/docs/build/html/index.html# 2. Create & upload a file text file.uploaded = drive.CreateFile({'title': 'Sample upload.txt'})uploaded.SetContentString('Sample upload file content')uploaded.Upload()print('Uploaded file with ID {}'.format(uploaded.get('id')))# 3. Load a file by ID and print its contents.downloaded = drive.CreateFile({'id': uploaded.get('id')})print('Downloaded content \"{}\"'.format(downloaded.GetContentString()))" }, { "code": null, "e": 3520, "s": 3450, "text": "You can get id of the file you want to upload,and use the above code." }, { "code": null, "e": 3576, "s": 3520, "text": "For more resource to upload files from google services." }, { "code": null, "e": 3606, "s": 3576, "text": "Uploading dataset from kaggle" }, { "code": null, "e": 3724, "s": 3606, "text": "We need to install kaggle api and add authentication json file which you can download from kaggle website(API_TOKEN)." }, { "code": null, "e": 3744, "s": 3724, "text": "!pip install kaggle" }, { "code": null, "e": 3824, "s": 3744, "text": "upload the json file to the notebook by, uploading file from the local machine." }, { "code": null, "e": 3852, "s": 3824, "text": "create a /.kaggle directory" }, { "code": null, "e": 3872, "s": 3852, "text": "!mkdir -p ~/.kaggle" }, { "code": null, "e": 3915, "s": 3872, "text": "copy the json file to the kaggle directory" }, { "code": null, "e": 3941, "s": 3915, "text": "change the file permision" }, { "code": null, "e": 4000, "s": 3941, "text": "!cp kaggle.json ~/.kaggle/!chmod 600 ~/.kaggle/kaggle.json" }, { "code": null, "e": 4060, "s": 4000, "text": "Now you can use command to download any dataset from kaggle" }, { "code": null, "e": 4115, "s": 4060, "text": "kaggle datasets download -d lazyjustin/pubgplayerstats" }, { "code": null, "e": 4242, "s": 4115, "text": "Now you can use the below to download competition dataset from kaggle,but for that you have to participate in the competition." }, { "code": null, "e": 4309, "s": 4242, "text": "!kaggle competitions download -c tgs-salt-identification-challenge" }, { "code": null, "e": 4381, "s": 4309, "text": "You can train and run fashion_mnist online without any dependency here." }, { "code": null, "e": 4581, "s": 4381, "text": "Colab is a great tool for everyone who are interested in machine learning,all the educational resource and code snippets to use colab is provide in the official website itself with notebook examples." }, { "code": null, "e": 4687, "s": 4581, "text": "Kaggle Kernels is a cloud computational environment that enables reproducible and collaborative analysis." }, { "code": null, "e": 4739, "s": 4687, "text": "One can run both Python and R code in kaggle kernel" }, { "code": null, "e": 4831, "s": 4739, "text": "Kaggle Kernel runs in a remote computational environment. They provide the hardware needed." }, { "code": null, "e": 4921, "s": 4831, "text": "At time of writing, each kernel editing session is provided with the following resources:" }, { "code": null, "e": 4940, "s": 4921, "text": "CPU Specifications" }, { "code": null, "e": 4952, "s": 4940, "text": "4 CPU cores" }, { "code": null, "e": 4972, "s": 4952, "text": "17 Gigabytes of RAM" }, { "code": null, "e": 4995, "s": 4972, "text": "6 hours execution time" }, { "code": null, "e": 5050, "s": 4995, "text": "5 Gigabytes of auto-saved disk space (/kaggle/working)" }, { "code": null, "e": 5125, "s": 5050, "text": "16 Gigabytes of temporary, scratchpad disk space (outside /kaggle/working)" }, { "code": null, "e": 5144, "s": 5125, "text": "GPU Specifications" }, { "code": null, "e": 5156, "s": 5144, "text": "2 CPU cores" }, { "code": null, "e": 5176, "s": 5156, "text": "14 Gigabytes of RAM" }, { "code": null, "e": 5303, "s": 5176, "text": "Once we create an account at kaggle.com, we can choose a dataset to play with and spin up a new kernel,with just a few clicks." }, { "code": null, "e": 5330, "s": 5303, "text": "Click on create new kernel" }, { "code": null, "e": 5506, "s": 5330, "text": "You will be having jupyter notebook up and running.At the bottom you will be having the console which you can use,and at the right side you will be having various options like" }, { "code": null, "e": 5909, "s": 5506, "text": "When you Commit & Run a kernel, you execute the kernel from top to bottom in a separate session from your interactive session. Once it finishes, you will have generated a new kernel version. A kernel version is a snapshot of your work including your compiled code, log files, output files, data sources, and more. The latest kernel version of your kernel is what is shown to users in the kernel viewer." }, { "code": null, "e": 6020, "s": 5909, "text": "When you create a kernel for a dataset ,the dataset will be preloaded into the notebook in the input directory" }, { "code": null, "e": 6030, "s": 6020, "text": "../input/" }, { "code": null, "e": 6091, "s": 6030, "text": "you can also click on add data source ,to add other datasets" }, { "code": null, "e": 6100, "s": 6091, "text": "Settings" }, { "code": null, "e": 6216, "s": 6100, "text": "Sharing: you can keep your kernel private,or you can also make it public so that others can learn from your kernel." }, { "code": null, "e": 6622, "s": 6216, "text": "Adding GPU:You can add a single NVIDIA Tesla K80 to your kernel. One of the major benefits to using Kernels as opposed to a local machine or your own VM is that the Kernels environment is already pre-configured with GPU-ready software and packages which can be time consuming and frustrating to set-up.To add a GPU, navigate to the “Settings” pane from the Kernel editor and click the “Enable GPU” option." }, { "code": null, "e": 6744, "s": 6622, "text": "Custom pakage:The kernel has the default pakages,if you need any other pakage you can easily add it by the following ways" }, { "code": null, "e": 6807, "s": 6744, "text": "Just enter the libarary name ,kaggle will download it for you." }, { "code": null, "e": 6837, "s": 6807, "text": "Enter the user name/repo name" }, { "code": null, "e": 6886, "s": 6837, "text": "both methods work fine in adding custom pakages." }, { "code": null, "e": 7089, "s": 6886, "text": "Kaggle acts as a perfect platform for both providing data,and also the compute to work with the great data provided.It also host various competition one can experiment it out to improve one’s skill set." }, { "code": null, "e": 7239, "s": 7089, "text": "For more resource regarding kaggle link here. If you are new to kaggle you should definitely try the titanic dataset it comes with awesome tutorials." }, { "code": null, "e": 7334, "s": 7239, "text": "Other resources regarding kaggle ,colab and machine learning follow Siraj Raval, and Yufeng G." }, { "code": null, "e": 7455, "s": 7334, "text": "Since I was not able to cover all the services to train ml model online in this post,there will be a part2 to this post." }, { "code": null, "e": 7720, "s": 7455, "text": "All the resource need to learn and practice machine learning is open sourced and available online.From Compute, datasets ,algorithms and there are various high quality tutorials available online for free,all you need is an internet connection,and passion to learn." }, { "code": null, "e": 8094, "s": 7720, "text": "Thank you for reading till the end,I hope this article would be useful, as it solves the major problem faced by people who are starting the path towards machine learning and data science. If you have enjoyed this article,please let me know by clapping for the article. Queries are most welcomed , you can follow my post in medium maithreyan surya,you can also mail me here." }, { "code": null, "e": 8211, "s": 8094, "text": "A video intro for using Colab effectively : https://www.youtube.com/playlist?list=PL9a4goxNJut3qyy56AY6Q9Zb2Nm4CQ3Tu" } ]
Initialization of global and static variables in C - GeeksforGeeks
08 May, 2017 Predict the output of following C programs. // PROGRAM 1#include <stdio.h>#include <stdlib.h> int main(void){ static int *p = (int*)malloc(sizeof(p)); *p = 10; printf("%d", *p);} // PROGRAM 2#include <stdio.h>#include <stdlib.h>int *p = (int*)malloc(sizeof(p)); int main(void){ *p = 10; printf("%d", *p);} Both of the above programs don’t compile in C. We get the following compiler error in C. error: initializer element is not constant In C, static and global variables are initialized by the compiler itself. Therefore, they must be initialized with a constant value. Note that the above programs compile and run fine in C++, and produce the output as 10. As an exercise, predict the output of following program in both C and C++. #include <stdio.h>int fun(int x){ return (x+5);} int y = fun(20); int main(){ printf("%d ", y);} This article is contributed by Shankar Shastri. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C Basics C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Command line arguments in C/C++ Core Dump (Segmentation fault) in C/C++ Substring in C++ Function Pointer in C Different methods to reverse a string in C/C++ TCP Server-Client implementation in C
[ { "code": null, "e": 24087, "s": 24059, "text": "\n08 May, 2017" }, { "code": null, "e": 24131, "s": 24087, "text": "Predict the output of following C programs." }, { "code": "// PROGRAM 1#include <stdio.h>#include <stdlib.h> int main(void){ static int *p = (int*)malloc(sizeof(p)); *p = 10; printf(\"%d\", *p);}", "e": 24273, "s": 24131, "text": null }, { "code": "// PROGRAM 2#include <stdio.h>#include <stdlib.h>int *p = (int*)malloc(sizeof(p)); int main(void){ *p = 10; printf(\"%d\", *p);}", "e": 24407, "s": 24273, "text": null }, { "code": null, "e": 24496, "s": 24407, "text": "Both of the above programs don’t compile in C. We get the following compiler error in C." }, { "code": null, "e": 24539, "s": 24496, "text": "error: initializer element is not constant" }, { "code": null, "e": 24672, "s": 24539, "text": "In C, static and global variables are initialized by the compiler itself. Therefore, they must be initialized with a constant value." }, { "code": null, "e": 24760, "s": 24672, "text": "Note that the above programs compile and run fine in C++, and produce the output as 10." }, { "code": null, "e": 24835, "s": 24760, "text": "As an exercise, predict the output of following program in both C and C++." }, { "code": "#include <stdio.h>int fun(int x){ return (x+5);} int y = fun(20); int main(){ printf(\"%d \", y);}", "e": 24940, "s": 24835, "text": null }, { "code": null, "e": 25113, "s": 24940, "text": "This article is contributed by Shankar Shastri. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25122, "s": 25113, "text": "C Basics" }, { "code": null, "e": 25133, "s": 25122, "text": "C Language" }, { "code": null, "e": 25231, "s": 25133, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25240, "s": 25231, "text": "Comments" }, { "code": null, "e": 25253, "s": 25240, "text": "Old Comments" }, { "code": null, "e": 25288, "s": 25253, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 25316, "s": 25288, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 25362, "s": 25316, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 25374, "s": 25362, "text": "fork() in C" }, { "code": null, "e": 25406, "s": 25374, "text": "Command line arguments in C/C++" }, { "code": null, "e": 25446, "s": 25406, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 25463, "s": 25446, "text": "Substring in C++" }, { "code": null, "e": 25485, "s": 25463, "text": "Function Pointer in C" }, { "code": null, "e": 25532, "s": 25485, "text": "Different methods to reverse a string in C/C++" } ]
Tryit Editor v3.7
Tryit: Evenly spaced color stops
[]
Find the number of elements greater than k in a sorted array - GeeksforGeeks
05 Aug, 2021 Given a sorted array arr[] of integers and an integer k, the task is to find the count of elements in the array which are greater than k. Note that k may or may not be present in the array.Examples: Input: arr[] = {2, 3, 5, 6, 6, 9}, k = 6 Output: 1Input: arr[] = {1, 1, 2, 5, 5, 7}, k = 8 Output: 0 Approach: The idea is to perform binary search and find the number of elements greater than k. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of elements// from the array which are greater than kint countGreater(int arr[], int n, int k){ int l = 0; int r = n - 1; // Stores the index of the left most element // from the array which is greater than k int leftGreater = n; // Finds number of elements greater than k while (l <= r) { int m = l + (r - l) / 2; // If mid element is greater than // k update leftGreater and r if (arr[m] > k) { leftGreater = m; r = m - 1; } // If mid element is less than // or equal to k update l else l = m + 1; } // Return the count of elements greater than k return (n - leftGreater);} // Driver codeint main(){ int arr[] = { 3, 3, 4, 7, 7, 7, 11, 13, 13 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 7; cout << countGreater(arr, n, k); return 0;} // Java implementation of the approachclass GFG{ // Function to return the count of elements// from the array which are greater than kstatic int countGreater(int arr[], int n, int k){ int l = 0; int r = n - 1; // Stores the index of the left most element // from the array which is greater than k int leftGreater = n; // Finds number of elements greater than k while (l <= r) { int m = l + (r - l) / 2; // If mid element is greater than // k update leftGreater and r if (arr[m] > k) { leftGreater = m; r = m - 1; } // If mid element is less than // or equal to k update l else l = m + 1; } // Return the count of elements greater than k return (n - leftGreater);} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 3, 4, 7, 7, 7, 11, 13, 13 }; int n = arr.length; int k = 7; System.out.println(countGreater(arr, n, k));}} // This code is contributed by Code_Mech # Python 3 implementation of the approach # Function to return the count of elements# from the array which are greater than kdef countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) # If mid element is greater than # k update leftGreater and r if (arr[m] > k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # Driver codeif __name__ == '__main__': arr = [3, 3, 4, 7, 7, 7, 11, 13, 13] n = len(arr) k = 7 print(countGreater(arr, n, k))# This code is contributed by# Surendra_Gangwar // C# implementation of the approachusing System; class GFG{ // Function to return the count of elements// from the array which are greater than kstatic int countGreater(int[]arr, int n, int k){ int l = 0; int r = n - 1; // Stores the index of the left most element // from the array which is greater than k int leftGreater = n; // Finds number of elements greater than k while (l <= r) { int m = l + (r - l) / 2; // If mid element is greater than // k update leftGreater and r if (arr[m] > k) { leftGreater = m; r = m - 1; } // If mid element is less than // or equal to k update l else l = m + 1; } // Return the count of elements greater than k return (n - leftGreater);} // Driver codepublic static void Main(){ int[] arr = { 3, 3, 4, 7, 7, 7, 11, 13, 13 }; int n = arr.Length; int k = 7; Console.WriteLine(countGreater(arr, n, k));}} // This code is contributed by Code_Mech <?php// PHP implementation of the approach // Function to return the count of elements// from the array which are greater than kfunction countGreater($arr, $n, $k){ $l = 0; $r = $n - 1; // Stores the index of the left most element // from the array which is greater than k $leftGreater = $n; // Finds number of elements greater than k while ($l <= $r) { $m = $l + (int)(($r - $l) / 2); // If mid element is greater than // k update leftGreater and r if ($arr[$m] > $k) { $leftGreater = $m; $r = $m - 1; } // If mid element is less than // or equal to k update l else $l = $m + 1; } // Return the count of elements greater than k return ($n - $leftGreater);} // Driver code$arr = array(3, 3, 4, 7, 7, 7, 11, 13, 13);$n = sizeof($arr);$k = 7; echo countGreater($arr, $n, $k); // This code is contributed// by Akanksha Rai <script> // Javascript implementation of the approach // Function to return the count of elements// from the array which are greater than kfunction countGreater(arr, n, k){ var l = 0; var r = n - 1; // Stores the index of the left most element // from the array which is greater than k var leftGreater = n; // Finds number of elements greater than k while (l <= r) { var m = l + parseInt((r - l) / 2); // If mid element is greater than // k update leftGreater and r if (arr[m] > k) { leftGreater = m; r = m - 1; } // If mid element is less than // or equal to k update l else l = m + 1; } // Return the count of elements greater than k return (n - leftGreater);} // Driver codevar arr = [3, 3, 4, 7, 7, 7, 11, 13, 13];var n = arr.length;var k = 7;document.write( countGreater(arr, n, k)); </script> 3 Time Complexity: O(log(n)) where n is the number of elements in the array.Auxiliary Space: O(1) SURENDRA_GANGWAR Akanksha_Rai Code_Mech noob2000 pankajsharmagfg Binary Search Algorithms Arrays Searching Sorting Arrays Searching Sorting Binary Search Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms K means Clustering - Introduction SCAN (Elevator) Disk Scheduling Algorithms Arrays in Java Arrays in C/C++ Stack Data Structure (Introduction and Program) Program for array rotation Largest Sum Contiguous Subarray
[ { "code": null, "e": 24472, "s": 24444, "text": "\n05 Aug, 2021" }, { "code": null, "e": 24673, "s": 24472, "text": "Given a sorted array arr[] of integers and an integer k, the task is to find the count of elements in the array which are greater than k. Note that k may or may not be present in the array.Examples: " }, { "code": null, "e": 24776, "s": 24673, "text": "Input: arr[] = {2, 3, 5, 6, 6, 9}, k = 6 Output: 1Input: arr[] = {1, 1, 2, 5, 5, 7}, k = 8 Output: 0 " }, { "code": null, "e": 24926, "s": 24778, "text": "Approach: The idea is to perform binary search and find the number of elements greater than k. Below is the implementation of the above approach: " }, { "code": null, "e": 24930, "s": 24926, "text": "C++" }, { "code": null, "e": 24935, "s": 24930, "text": "Java" }, { "code": null, "e": 24943, "s": 24935, "text": "Python3" }, { "code": null, "e": 24946, "s": 24943, "text": "C#" }, { "code": null, "e": 24950, "s": 24946, "text": "PHP" }, { "code": null, "e": 24961, "s": 24950, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of elements// from the array which are greater than kint countGreater(int arr[], int n, int k){ int l = 0; int r = n - 1; // Stores the index of the left most element // from the array which is greater than k int leftGreater = n; // Finds number of elements greater than k while (l <= r) { int m = l + (r - l) / 2; // If mid element is greater than // k update leftGreater and r if (arr[m] > k) { leftGreater = m; r = m - 1; } // If mid element is less than // or equal to k update l else l = m + 1; } // Return the count of elements greater than k return (n - leftGreater);} // Driver codeint main(){ int arr[] = { 3, 3, 4, 7, 7, 7, 11, 13, 13 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 7; cout << countGreater(arr, n, k); return 0;}", "e": 25958, "s": 24961, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the count of elements// from the array which are greater than kstatic int countGreater(int arr[], int n, int k){ int l = 0; int r = n - 1; // Stores the index of the left most element // from the array which is greater than k int leftGreater = n; // Finds number of elements greater than k while (l <= r) { int m = l + (r - l) / 2; // If mid element is greater than // k update leftGreater and r if (arr[m] > k) { leftGreater = m; r = m - 1; } // If mid element is less than // or equal to k update l else l = m + 1; } // Return the count of elements greater than k return (n - leftGreater);} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 3, 4, 7, 7, 7, 11, 13, 13 }; int n = arr.length; int k = 7; System.out.println(countGreater(arr, n, k));}} // This code is contributed by Code_Mech", "e": 26983, "s": 25958, "text": null }, { "code": "# Python 3 implementation of the approach # Function to return the count of elements# from the array which are greater than kdef countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) # If mid element is greater than # k update leftGreater and r if (arr[m] > k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # Driver codeif __name__ == '__main__': arr = [3, 3, 4, 7, 7, 7, 11, 13, 13] n = len(arr) k = 7 print(countGreater(arr, n, k))# This code is contributed by# Surendra_Gangwar", "e": 27890, "s": 26983, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the count of elements// from the array which are greater than kstatic int countGreater(int[]arr, int n, int k){ int l = 0; int r = n - 1; // Stores the index of the left most element // from the array which is greater than k int leftGreater = n; // Finds number of elements greater than k while (l <= r) { int m = l + (r - l) / 2; // If mid element is greater than // k update leftGreater and r if (arr[m] > k) { leftGreater = m; r = m - 1; } // If mid element is less than // or equal to k update l else l = m + 1; } // Return the count of elements greater than k return (n - leftGreater);} // Driver codepublic static void Main(){ int[] arr = { 3, 3, 4, 7, 7, 7, 11, 13, 13 }; int n = arr.Length; int k = 7; Console.WriteLine(countGreater(arr, n, k));}} // This code is contributed by Code_Mech", "e": 28922, "s": 27890, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the count of elements// from the array which are greater than kfunction countGreater($arr, $n, $k){ $l = 0; $r = $n - 1; // Stores the index of the left most element // from the array which is greater than k $leftGreater = $n; // Finds number of elements greater than k while ($l <= $r) { $m = $l + (int)(($r - $l) / 2); // If mid element is greater than // k update leftGreater and r if ($arr[$m] > $k) { $leftGreater = $m; $r = $m - 1; } // If mid element is less than // or equal to k update l else $l = $m + 1; } // Return the count of elements greater than k return ($n - $leftGreater);} // Driver code$arr = array(3, 3, 4, 7, 7, 7, 11, 13, 13);$n = sizeof($arr);$k = 7; echo countGreater($arr, $n, $k); // This code is contributed// by Akanksha Rai", "e": 29876, "s": 28922, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the count of elements// from the array which are greater than kfunction countGreater(arr, n, k){ var l = 0; var r = n - 1; // Stores the index of the left most element // from the array which is greater than k var leftGreater = n; // Finds number of elements greater than k while (l <= r) { var m = l + parseInt((r - l) / 2); // If mid element is greater than // k update leftGreater and r if (arr[m] > k) { leftGreater = m; r = m - 1; } // If mid element is less than // or equal to k update l else l = m + 1; } // Return the count of elements greater than k return (n - leftGreater);} // Driver codevar arr = [3, 3, 4, 7, 7, 7, 11, 13, 13];var n = arr.length;var k = 7;document.write( countGreater(arr, n, k)); </script>", "e": 30799, "s": 29876, "text": null }, { "code": null, "e": 30801, "s": 30799, "text": "3" }, { "code": null, "e": 30899, "s": 30803, "text": "Time Complexity: O(log(n)) where n is the number of elements in the array.Auxiliary Space: O(1)" }, { "code": null, "e": 30916, "s": 30899, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 30929, "s": 30916, "text": "Akanksha_Rai" }, { "code": null, "e": 30939, "s": 30929, "text": "Code_Mech" }, { "code": null, "e": 30948, "s": 30939, "text": "noob2000" }, { "code": null, "e": 30964, "s": 30948, "text": "pankajsharmagfg" }, { "code": null, "e": 30978, "s": 30964, "text": "Binary Search" }, { "code": null, "e": 30989, "s": 30978, "text": "Algorithms" }, { "code": null, "e": 30996, "s": 30989, "text": "Arrays" }, { "code": null, "e": 31006, "s": 30996, "text": "Searching" }, { "code": null, "e": 31014, "s": 31006, "text": "Sorting" }, { "code": null, "e": 31021, "s": 31014, "text": "Arrays" }, { "code": null, "e": 31031, "s": 31021, "text": "Searching" }, { "code": null, "e": 31039, "s": 31031, "text": "Sorting" }, { "code": null, "e": 31053, "s": 31039, "text": "Binary Search" }, { "code": null, "e": 31064, "s": 31053, "text": "Algorithms" }, { "code": null, "e": 31162, "s": 31064, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31171, "s": 31162, "text": "Comments" }, { "code": null, "e": 31184, "s": 31171, "text": "Old Comments" }, { "code": null, "e": 31233, "s": 31184, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 31258, "s": 31233, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31285, "s": 31258, "text": "Introduction to Algorithms" }, { "code": null, "e": 31319, "s": 31285, "text": "K means Clustering - Introduction" }, { "code": null, "e": 31362, "s": 31319, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 31377, "s": 31362, "text": "Arrays in Java" }, { "code": null, "e": 31393, "s": 31377, "text": "Arrays in C/C++" }, { "code": null, "e": 31441, "s": 31393, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 31468, "s": 31441, "text": "Program for array rotation" } ]
Postorder Traversal | Practice | GeeksforGeeks
Given a binary tree, find the Postorder Traversal of it. For Example, the postorder traversal of the following tree is: 5 10 39 1 1 / \ 10 39 / 5 Example 1: Input: 19 / \ 10 8 / \ 11 13 Output: 11 13 10 8 19 Example 2: Input: 11 / 15 / 7 Output: 7 15 11 Your Task: You don't need to read input or print anything. Your task is to complete the function postOrder() that takes root node as input and returns an array containing the postorder traversal of the given Binary Tree. Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1 <= Number of nodes <= 105 0 <= Data of a node <= 106 0 superrhitik4582 days ago vector<int> vi;void post(Node* root){ if(root!=NULL){ post(root->left); post(root->right); vi.push_back(root->data); } return;}vector <int> postOrder(Node* root){ // Your code herepost(root); vector<int> res=vi;vi.clear();return res;} 0 itachinamikaze2211 week ago ArrayList<Integer> postOrder(Node root) { Stack<Node> st= new Stack<Node>(); ArrayList<Integer> res= new ArrayList<>(); Node curr=root; Node temp; while(curr!=null||st.isEmpty()==false) { if(curr!=null) { st.push(curr); curr=curr.left; } else { temp=st.peek().right; if(temp==null) { temp=st.peek(); st.pop(); res.add(temp.data); while(!st.isEmpty() && temp==st.peek().right) { temp=st.peek(); st.pop(); res.add(temp.data); } } else curr= temp; } } return res; } 0 rajpateriya3 weeks ago JAVA solution void post(Node root, ArrayList<Integer> res) { if(root == null) { return; } post(root.left,res); post(root.right,res); res.add(root.data); } ArrayList<Integer> postOrder(Node root) { ArrayList<Integer> res=new ArrayList<>(); post(root, res); return res; } 0 amankumar2781 month ago Java Solution...(Very easy): class Tree{ //Function to return a list containing the postorder traversal of the tree. ArrayList<Integer> postOrder(Node root) { // Your code goes here ArrayList<Integer> list=new ArrayList<>(); if(root==null){ return list; } list.addAll(postOrder(root.left)); list.addAll(postOrder(root.right)); list.add(root.data); return list; }} 0 adarshgupta4011 month ago Java recursive code - all test cases passed class Tree { ArrayList<Integer> postOrder(Node root) { //left- right- root ArrayList<Integer> res = new ArrayList<>(); if( root == null) return res; res.addAll(postOrder(root.left)); res.addAll(postOrder(root.right)); res.add(root.data); return res; } } 0 amiransarimy1 month ago Python Solutions #Function to return a list containing the postorder traversal of the tree. def postOrder(root): if root is None: return [] # return empty list if root is None resList = [] postOrderHelper(root,resList) return resList def postOrderHelper(root,resList): if root is None: return postOrderHelper(root.left,resList) postOrderHelper(root.right, resList) resList.append(root.data) -2 vs5094111 month ago Why this code is giving wrong output? vector<int> v;vector <int> postOrder(Node* root){ if(root==NULL)return v; postOrder(root->left); postOrder(root->right); v.push_back(root->data); return v;} +1 iamnobodyji2 months ago ArrayList<Integer> postOrder(Node root) { // Your code goes here ArrayList<Integer> arr = new ArrayList<Integer>(); if(root==null) return arr; arr.addAll(postOrder(root.left)); arr.addAll(postOrder(root.right)); arr.add(root.data); return arr; } +2 mridulbhaskarabc2 months ago #Contributed By: Mridul Bhaskar def postOrder(root): if(root is None): return [] else: return postOrder(root.left) + postOrder(root.right)+[root.data] +2 vishalja77192 months ago C++ 0.01 faster void postorder(Node* root,vector<int> &v) { if(root == NULL) return; postorder(root->left,v); postorder(root->right,v); v.push_back(root->data); } vector <int> postOrder(Node* root) { // Your code here vector<int>res; postorder(root,res); return res; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 357, "s": 226, "text": "Given a binary tree, find the Postorder Traversal of it.\nFor Example, the postorder traversal of the following tree is: \n5 10 39 1" }, { "code": null, "e": 399, "s": 357, "text": " 1\n / \\\n 10 39\n /\n5" }, { "code": null, "e": 411, "s": 399, "text": "\nExample 1:" }, { "code": null, "e": 498, "s": 411, "text": "Input:\n 19\n / \\\n 10 8\n / \\\n 11 13\nOutput: 11 13 10 8 19\n" }, { "code": null, "e": 509, "s": 498, "text": "Example 2:" }, { "code": null, "e": 582, "s": 509, "text": "Input:\n 11\n /\n 15\n /\n 7\nOutput: 7 15 11\n" }, { "code": null, "e": 804, "s": 582, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function postOrder() that takes root node as input and returns an array containing the postorder traversal of the given Binary Tree." }, { "code": null, "e": 869, "s": 804, "text": "\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 938, "s": 869, "text": "\nConstraints:\n1 <= Number of nodes <= 105\n0 <= Data of a node <= 106" }, { "code": null, "e": 942, "s": 940, "text": "0" }, { "code": null, "e": 967, "s": 942, "text": "superrhitik4582 days ago" }, { "code": null, "e": 1219, "s": 967, "text": "vector<int> vi;void post(Node* root){ if(root!=NULL){ post(root->left); post(root->right); vi.push_back(root->data); } return;}vector <int> postOrder(Node* root){ // Your code herepost(root); vector<int> res=vi;vi.clear();return res;}" }, { "code": null, "e": 1221, "s": 1219, "text": "0" }, { "code": null, "e": 1249, "s": 1221, "text": "itachinamikaze2211 week ago" }, { "code": null, "e": 2081, "s": 1249, "text": "ArrayList<Integer> postOrder(Node root) { Stack<Node> st= new Stack<Node>(); ArrayList<Integer> res= new ArrayList<>(); Node curr=root; Node temp; while(curr!=null||st.isEmpty()==false) { if(curr!=null) { st.push(curr); curr=curr.left; } else { temp=st.peek().right; if(temp==null) { temp=st.peek(); st.pop(); res.add(temp.data); while(!st.isEmpty() && temp==st.peek().right) { temp=st.peek(); st.pop(); res.add(temp.data); } } else curr= temp; } } return res; }" }, { "code": null, "e": 2083, "s": 2081, "text": "0" }, { "code": null, "e": 2106, "s": 2083, "text": "rajpateriya3 weeks ago" }, { "code": null, "e": 2491, "s": 2106, "text": " JAVA solution\n \n void post(Node root, ArrayList<Integer> res)\n {\n if(root == null)\n {\n return;\n }\n post(root.left,res);\n post(root.right,res);\n res.add(root.data);\n }\n \n ArrayList<Integer> postOrder(Node root)\n {\n ArrayList<Integer> res=new ArrayList<>();\n post(root, res);\n return res;\n }" }, { "code": null, "e": 2493, "s": 2491, "text": "0" }, { "code": null, "e": 2517, "s": 2493, "text": "amankumar2781 month ago" }, { "code": null, "e": 2547, "s": 2517, "text": "Java Solution...(Very easy): " }, { "code": null, "e": 2939, "s": 2547, "text": "class Tree{ //Function to return a list containing the postorder traversal of the tree. ArrayList<Integer> postOrder(Node root) { // Your code goes here ArrayList<Integer> list=new ArrayList<>(); if(root==null){ return list; } list.addAll(postOrder(root.left)); list.addAll(postOrder(root.right)); list.add(root.data); return list; }}" }, { "code": null, "e": 2941, "s": 2939, "text": "0" }, { "code": null, "e": 2967, "s": 2941, "text": "adarshgupta4011 month ago" }, { "code": null, "e": 2989, "s": 2967, "text": "Java recursive code -" }, { "code": null, "e": 3011, "s": 2989, "text": "all test cases passed" }, { "code": null, "e": 3358, "s": 3011, "text": "class Tree\n{\n ArrayList<Integer> postOrder(Node root)\n {\n //left- right- root\n ArrayList<Integer> res = new ArrayList<>();\n \n if( root == null)\n return res;\n \n res.addAll(postOrder(root.left));\n res.addAll(postOrder(root.right));\n res.add(root.data);\n \n return res;\n }\n}" }, { "code": null, "e": 3360, "s": 3358, "text": "0" }, { "code": null, "e": 3384, "s": 3360, "text": "amiransarimy1 month ago" }, { "code": null, "e": 3401, "s": 3384, "text": "Python Solutions" }, { "code": null, "e": 3815, "s": 3403, "text": "#Function to return a list containing the postorder traversal of the tree.\ndef postOrder(root):\n if root is None:\n return [] # return empty list if root is None\n resList = []\n postOrderHelper(root,resList)\n return resList\ndef postOrderHelper(root,resList):\n if root is None:\n return\n postOrderHelper(root.left,resList)\n postOrderHelper(root.right, resList)\n resList.append(root.data)" }, { "code": null, "e": 3818, "s": 3815, "text": "-2" }, { "code": null, "e": 3838, "s": 3818, "text": "vs5094111 month ago" }, { "code": null, "e": 3878, "s": 3840, "text": "Why this code is giving wrong output?" }, { "code": null, "e": 4039, "s": 3882, "text": "vector<int> v;vector <int> postOrder(Node* root){ if(root==NULL)return v; postOrder(root->left); postOrder(root->right); v.push_back(root->data); return v;}" }, { "code": null, "e": 4046, "s": 4043, "text": "+1" }, { "code": null, "e": 4070, "s": 4046, "text": "iamnobodyji2 months ago" }, { "code": null, "e": 4364, "s": 4070, "text": "ArrayList<Integer> postOrder(Node root)\n {\n // Your code goes here\n ArrayList<Integer> arr = new ArrayList<Integer>();\n if(root==null) return arr;\n arr.addAll(postOrder(root.left));\n arr.addAll(postOrder(root.right));\n arr.add(root.data);\n return arr;\n }" }, { "code": null, "e": 4367, "s": 4364, "text": "+2" }, { "code": null, "e": 4396, "s": 4367, "text": "mridulbhaskarabc2 months ago" }, { "code": null, "e": 4428, "s": 4396, "text": "#Contributed By: Mridul Bhaskar" }, { "code": null, "e": 4571, "s": 4428, "text": "def postOrder(root):\n if(root is None):\n return []\n else:\n return postOrder(root.left) + postOrder(root.right)+[root.data]" }, { "code": null, "e": 4576, "s": 4573, "text": "+2" }, { "code": null, "e": 4601, "s": 4576, "text": "vishalja77192 months ago" }, { "code": null, "e": 4618, "s": 4601, "text": "C++ 0.01 faster " }, { "code": null, "e": 4913, "s": 4618, "text": " void postorder(Node* root,vector<int> &v)\n {\n if(root == NULL)\n return;\n \n postorder(root->left,v);\n postorder(root->right,v);\n v.push_back(root->data);\n }\n\nvector <int> postOrder(Node* root)\n{\n // Your code here\n vector<int>res;\n postorder(root,res);\n return res;\n}" }, { "code": null, "e": 5059, "s": 4913, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5095, "s": 5059, "text": " Login to access your submissions. " }, { "code": null, "e": 5105, "s": 5095, "text": "\nProblem\n" }, { "code": null, "e": 5115, "s": 5105, "text": "\nContest\n" }, { "code": null, "e": 5178, "s": 5115, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5326, "s": 5178, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 5534, "s": 5326, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 5640, "s": 5534, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
PHP - password_needs_rehash() Function
The password_needs_rehash() function can check if the given hash matches the given options. boolean password_needs_rehash ( string $hash , integer $algo [, array $options ] ) The password_needs_rehash() function can check to see if the supplied hash implements the algorithm and options provided. If not, it's assumed that the hash needs to rehash. The password_needs_rehash() function can return true if the hash can be rehashed to match the given algo and options or false otherwise. <?php $passw01 = "53nh46u74m3nt3"; $hashp03 = '$argon2i$v=19$m=1024,t=2,p=2$d1JJWnNHMkVEekZwcTFUdA$zeSi7c/Adh/1KCTHddoF39Xxwo9ystxRzHEnRa0lQeM'; $algo03 = PASSWORD_ARGON2I; $test03 = password_verify($passw01, $hashp03); $conf03 = password_needs_rehash($hashp03, $algo03); if($conf03 == true) { echo "HASH NEEDS TO BE REHASHED!<br>SUGGESTED FOR THE NEW HASH:<br>"; $nwhas03 = password_hash($passw01, $algo03); echo $nwhas03; } else { echo "HASH DOES HAS NO NEED TO BE REHASHED!<br>"; echo $hashp03; $getinfo03 = password_get_info($hashp03); echo "<br><br>algo = " . $getinfo03["algo"] . "<br>algoName = " . $getinfo03["algoName"] . "<br>memory_cost = " . $getinfo03["options"]["memory_cost"] . "<br>time_cost = " . $getinfo03["options"]["time_cost"] . "<br>threds = " . $getinfo03["options"]["threads"] . "<br><br>"; } ?> HASH NEEDS TO BE REHASHED!<br>SUGGESTED FOR THE NEW HASH:<br>$argon2i$v=19$m=65536,t=4,p=1$dDVDRWFFTS9ObjFQMmhuRw$1uWmsNTQBbrwXtQPB7PQqWWIlcd0XBqg2mEDHGaElew 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": 2850, "s": 2757, "text": "The password_needs_rehash() function can check if the given hash matches the given options. " }, { "code": null, "e": 2934, "s": 2850, "text": "boolean password_needs_rehash ( string $hash , integer $algo [, array $options ] )\n" }, { "code": null, "e": 3109, "s": 2934, "text": "The password_needs_rehash() function can check to see if the supplied hash implements the algorithm and options provided. If not, it's assumed that the hash needs to rehash. " }, { "code": null, "e": 3247, "s": 3109, "text": "The password_needs_rehash() function can return true if the hash can be rehashed to match the given algo and options or false otherwise. " }, { "code": null, "e": 4164, "s": 3247, "text": "<?php\n $passw01 = \"53nh46u74m3nt3\";\n $hashp03 = '$argon2i$v=19$m=1024,t=2,p=2$d1JJWnNHMkVEekZwcTFUdA$zeSi7c/Adh/1KCTHddoF39Xxwo9ystxRzHEnRa0lQeM';\n $algo03 = PASSWORD_ARGON2I;\n\n $test03 = password_verify($passw01, $hashp03);\n $conf03 = password_needs_rehash($hashp03, $algo03);\n\n if($conf03 == true) {\n echo \"HASH NEEDS TO BE REHASHED!<br>SUGGESTED FOR THE NEW HASH:<br>\";\n $nwhas03 = password_hash($passw01, $algo03);\n echo $nwhas03;\n } else {\n echo \"HASH DOES HAS NO NEED TO BE REHASHED!<br>\";\n echo $hashp03;\n\n $getinfo03 = password_get_info($hashp03);\n\n echo \"<br><br>algo = \" . $getinfo03[\"algo\"] . \"<br>algoName = \" . $getinfo03[\"algoName\"] . \"<br>memory_cost = \" \n . $getinfo03[\"options\"][\"memory_cost\"] . \"<br>time_cost = \" . $getinfo03[\"options\"][\"time_cost\"] \n . \"<br>threds = \" . $getinfo03[\"options\"][\"threads\"] . \"<br><br>\"; \n }\n?>" }, { "code": null, "e": 4323, "s": 4164, "text": "HASH NEEDS TO BE REHASHED!<br>SUGGESTED FOR THE NEW HASH:<br>$argon2i$v=19$m=65536,t=4,p=1$dDVDRWFFTS9ObjFQMmhuRw$1uWmsNTQBbrwXtQPB7PQqWWIlcd0XBqg2mEDHGaElew\n" }, { "code": null, "e": 4356, "s": 4323, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 4372, "s": 4356, "text": " Malhar Lathkar" }, { "code": null, "e": 4405, "s": 4372, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 4416, "s": 4405, "text": " Syed Raza" }, { "code": null, "e": 4451, "s": 4416, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4468, "s": 4451, "text": " Frahaan Hussain" }, { "code": null, "e": 4501, "s": 4468, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 4516, "s": 4501, "text": " Nivedita Jain" }, { "code": null, "e": 4551, "s": 4516, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 4563, "s": 4551, "text": " Azaz Patel" }, { "code": null, "e": 4598, "s": 4563, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4626, "s": 4598, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 4633, "s": 4626, "text": " Print" }, { "code": null, "e": 4644, "s": 4633, "text": " Add Notes" } ]
Calculate the QR decomposition of a given matrix using NumPy - GeeksforGeeks
05 Sep, 2020 In this article, we will discuss QR decomposition of a matrix. QR factorization of a matrix is the decomposition of a matrix say ‘A’ into ‘A=QR’ where Q is orthogonal and R is an upper-triangular matrix. We can calculate the QR decomposition of a given matrix with the help of numpy.linalg.qr(). Syntax : numpy.linalg.qr(a, mode=’reduced’) Parameters : a : matrix(M,N) which needs to be factored. mode : it is optional. It can be : Example 1: Python3 import numpy as np # Original matrixmatrix1 = np.array([[1, 2, 3], [3, 4, 5]])print(matrix1) # Decomposition of the said matrixq, r = np.linalg.qr(matrix1)print('\nQ:\n', q)print('\nR:\n', r) Output: [[1 2 3] [3 4 5]] Q: [[-0.31622777 -0.9486833 ] [-0.9486833 0.31622777]] R: [[-3.16227766 -4.42718872 -5.69209979] [ 0. -0.63245553 -1.26491106]] Example 2: Python3 import numpy as np # Original matrixmatrix1 = np.array([[1, 0], [2, 4]])print(matrix1) # Decomposition of the said matrixq, r = np.linalg.qr(matrix1)print('\nQ:\n', q)print('\nR:\n', r) Output: [[1 0] [2 4]] Q: [[-0.4472136 -0.89442719] [-0.89442719 0.4472136 ]] R: [[-2.23606798 -3.57770876] [ 0. 1.78885438]] Example 3: Python3 import numpy as np # Create a numpy array arr = np.array([[5, 11, -15], [12, 34, -51], [-24, -43, 92]], dtype=np.int32) print(arr) # Find the QR factor of array q, r = np.linalg.qr(arr) print('\nQ:\n', q)print('\nR:\n', r) Output: [[ 5 11 -15] [ 12 34 -51] [-24 -43 92]] Q: [[-0.18318583 -0.08610905 0.97929984] [-0.43964598 -0.88381371 -0.15995231] [ 0.87929197 -0.45984624 0.12404465]] R: [[-27.29468813 -54.77256208 106.06459346] [ 0. -11.22347731 4.06028083] [ 0. 0. 4.88017756]] Python numpy-Linear Algebra Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24176, "s": 24148, "text": "\n05 Sep, 2020" }, { "code": null, "e": 24473, "s": 24176, "text": "In this article, we will discuss QR decomposition of a matrix. QR factorization of a matrix is the decomposition of a matrix say ‘A’ into ‘A=QR’ where Q is orthogonal and R is an upper-triangular matrix. We can calculate the QR decomposition of a given matrix with the help of numpy.linalg.qr(). " }, { "code": null, "e": 24517, "s": 24473, "text": "Syntax : numpy.linalg.qr(a, mode=’reduced’)" }, { "code": null, "e": 24530, "s": 24517, "text": "Parameters :" }, { "code": null, "e": 24574, "s": 24530, "text": "a : matrix(M,N) which needs to be factored." }, { "code": null, "e": 24609, "s": 24574, "text": "mode : it is optional. It can be :" }, { "code": null, "e": 24620, "s": 24609, "text": "Example 1:" }, { "code": null, "e": 24628, "s": 24620, "text": "Python3" }, { "code": "import numpy as np # Original matrixmatrix1 = np.array([[1, 2, 3], [3, 4, 5]])print(matrix1) # Decomposition of the said matrixq, r = np.linalg.qr(matrix1)print('\\nQ:\\n', q)print('\\nR:\\n', r)", "e": 24824, "s": 24628, "text": null }, { "code": null, "e": 24832, "s": 24824, "text": "Output:" }, { "code": null, "e": 24996, "s": 24832, "text": "[[1 2 3]\n [3 4 5]]\n\nQ:\n [[-0.31622777 -0.9486833 ]\n [-0.9486833 0.31622777]]\n\nR:\n [[-3.16227766 -4.42718872 -5.69209979]\n [ 0. -0.63245553 -1.26491106]]\n" }, { "code": null, "e": 25007, "s": 24996, "text": "Example 2:" }, { "code": null, "e": 25015, "s": 25007, "text": "Python3" }, { "code": "import numpy as np # Original matrixmatrix1 = np.array([[1, 0], [2, 4]])print(matrix1) # Decomposition of the said matrixq, r = np.linalg.qr(matrix1)print('\\nQ:\\n', q)print('\\nR:\\n', r)", "e": 25205, "s": 25015, "text": null }, { "code": null, "e": 25213, "s": 25205, "text": "Output:" }, { "code": null, "e": 25349, "s": 25213, "text": "[[1 0]\n [2 4]]\n\nQ:\n [[-0.4472136 -0.89442719]\n [-0.89442719 0.4472136 ]]\n\nR:\n [[-2.23606798 -3.57770876]\n [ 0. 1.78885438]]\n" }, { "code": null, "e": 25360, "s": 25349, "text": "Example 3:" }, { "code": null, "e": 25368, "s": 25360, "text": "Python3" }, { "code": "import numpy as np # Create a numpy array arr = np.array([[5, 11, -15], [12, 34, -51], [-24, -43, 92]], dtype=np.int32) print(arr) # Find the QR factor of array q, r = np.linalg.qr(arr) print('\\nQ:\\n', q)print('\\nR:\\n', r)", "e": 25617, "s": 25368, "text": null }, { "code": null, "e": 25625, "s": 25617, "text": "Output:" }, { "code": null, "e": 25927, "s": 25625, "text": "[[ 5 11 -15]\n [ 12 34 -51]\n [-24 -43 92]]\n\nQ:\n [[-0.18318583 -0.08610905 0.97929984]\n [-0.43964598 -0.88381371 -0.15995231]\n [ 0.87929197 -0.45984624 0.12404465]]\n\nR:\n [[-27.29468813 -54.77256208 106.06459346]\n [ 0. -11.22347731 4.06028083]\n [ 0. 0. 4.88017756]]\n" }, { "code": null, "e": 25955, "s": 25927, "text": "Python numpy-Linear Algebra" }, { "code": null, "e": 25968, "s": 25955, "text": "Python-numpy" }, { "code": null, "e": 25975, "s": 25968, "text": "Python" }, { "code": null, "e": 26073, "s": 25975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26091, "s": 26073, "text": "Python Dictionary" }, { "code": null, "e": 26126, "s": 26091, "text": "Read a file line by line in Python" }, { "code": null, "e": 26148, "s": 26126, "text": "Enumerate() in Python" }, { "code": null, "e": 26180, "s": 26148, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26210, "s": 26180, "text": "Iterate over a list in Python" }, { "code": null, "e": 26252, "s": 26210, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26278, "s": 26252, "text": "Python String | replace()" }, { "code": null, "e": 26315, "s": 26278, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26358, "s": 26315, "text": "Python program to convert a list to string" } ]
Python | Remove given element from the list - GeeksforGeeks
20 May, 2019 Given a list, write a Python program to remove the given element (list may have duplicates) from given list. There are multiple ways we can do this task in Python. Let’s see some of Pythonic ways to do this task. Method #1: Using pop() method [Remove given element found first.] # Python program to remove given element from the listlist1 = [1, 9, 8, 4, 9, 2, 9] # Printing initial list print ("original list : "+ str(list1)) remove = 9 # using pop() # to remove list element 9if remove in list1: list1.pop(list1.index(remove)) # Printing list after removal print ("List after element removal is : " + str(list1)) original list : [1, 9, 8, 4, 9, 2, 9] List after element removal is : [1, 8, 4, 9, 2, 9] Method #2: Using remove() method # Python program to remove given element from the listlist1 = [1, 9, 8, 4, 9, 2, 9] # Printing initial list print ("original list : "+ str(list1)) # using remove() to remove list element 9list1.remove(9) # Printing list after removal print ("List after element removal is : " + str(list1)) original list : [1, 9, 8, 4, 9, 2, 9] List after element removal is : [1, 8, 4, 9, 2, 9] Now, let’s see the ways to remove all occurrence of given element. Method #3: Using set Since the list is converted to set, all duplicates are removed, but the ordering of list cannot be preserved. # Python program to remove given element from the listlist1 = [1, 9, 8, 4, 9, 2, 9] # Printing initial list print ("original list : "+ str(list1)) # using discard() method to remove list element 9list1 = set(list1) list1.discard(9) list1 = list(list1) # Printing list after removal print ("List after element removal is : " + str(list1)) original list : [1, 9, 8, 4, 9, 2, 9] List after element removal is : [8, 1, 2, 4] Method #4: Using list comprehension # Python program to remove given element from the listlist1 = [1, 9, 8, 4, 9, 2, 9] # Printing initial list print ("original list : "+ str(list1)) # using List Comprehension # to remove list element 9list1 = [ele for ele in list1 if ele != 9] # Printing list after removal print ("List after element removal is : " + str(list1)) original list : [1, 9, 8, 4, 9, 2, 9] List after element removal is : [1, 8, 4, 2] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24340, "s": 24312, "text": "\n20 May, 2019" }, { "code": null, "e": 24553, "s": 24340, "text": "Given a list, write a Python program to remove the given element (list may have duplicates) from given list. There are multiple ways we can do this task in Python. Let’s see some of Pythonic ways to do this task." }, { "code": null, "e": 24619, "s": 24553, "text": "Method #1: Using pop() method [Remove given element found first.]" }, { "code": "# Python program to remove given element from the listlist1 = [1, 9, 8, 4, 9, 2, 9] # Printing initial list print (\"original list : \"+ str(list1)) remove = 9 # using pop() # to remove list element 9if remove in list1: list1.pop(list1.index(remove)) # Printing list after removal print (\"List after element removal is : \" + str(list1)) ", "e": 24975, "s": 24619, "text": null }, { "code": null, "e": 25065, "s": 24975, "text": "original list : [1, 9, 8, 4, 9, 2, 9]\nList after element removal is : [1, 8, 4, 9, 2, 9]\n" }, { "code": null, "e": 25099, "s": 25065, "text": " Method #2: Using remove() method" }, { "code": "# Python program to remove given element from the listlist1 = [1, 9, 8, 4, 9, 2, 9] # Printing initial list print (\"original list : \"+ str(list1)) # using remove() to remove list element 9list1.remove(9) # Printing list after removal print (\"List after element removal is : \" + str(list1)) ", "e": 25401, "s": 25099, "text": null }, { "code": null, "e": 25491, "s": 25401, "text": "original list : [1, 9, 8, 4, 9, 2, 9]\nList after element removal is : [1, 8, 4, 9, 2, 9]\n" }, { "code": null, "e": 25558, "s": 25491, "text": "Now, let’s see the ways to remove all occurrence of given element." }, { "code": null, "e": 25579, "s": 25558, "text": "Method #3: Using set" }, { "code": null, "e": 25689, "s": 25579, "text": "Since the list is converted to set, all duplicates are removed, but the ordering of list cannot be preserved." }, { "code": "# Python program to remove given element from the listlist1 = [1, 9, 8, 4, 9, 2, 9] # Printing initial list print (\"original list : \"+ str(list1)) # using discard() method to remove list element 9list1 = set(list1) list1.discard(9) list1 = list(list1) # Printing list after removal print (\"List after element removal is : \" + str(list1)) ", "e": 26043, "s": 25689, "text": null }, { "code": null, "e": 26127, "s": 26043, "text": "original list : [1, 9, 8, 4, 9, 2, 9]\nList after element removal is : [8, 1, 2, 4]\n" }, { "code": null, "e": 26164, "s": 26127, "text": " Method #4: Using list comprehension" }, { "code": "# Python program to remove given element from the listlist1 = [1, 9, 8, 4, 9, 2, 9] # Printing initial list print (\"original list : \"+ str(list1)) # using List Comprehension # to remove list element 9list1 = [ele for ele in list1 if ele != 9] # Printing list after removal print (\"List after element removal is : \" + str(list1)) ", "e": 26505, "s": 26164, "text": null }, { "code": null, "e": 26589, "s": 26505, "text": "original list : [1, 9, 8, 4, 9, 2, 9]\nList after element removal is : [1, 8, 4, 2]\n" }, { "code": null, "e": 26610, "s": 26589, "text": "Python list-programs" }, { "code": null, "e": 26617, "s": 26610, "text": "Python" }, { "code": null, "e": 26633, "s": 26617, "text": "Python Programs" }, { "code": null, "e": 26731, "s": 26633, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26766, "s": 26731, "text": "Read a file line by line in Python" }, { "code": null, "e": 26788, "s": 26766, "text": "Enumerate() in Python" }, { "code": null, "e": 26820, "s": 26788, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26850, "s": 26820, "text": "Iterate over a list in Python" }, { "code": null, "e": 26892, "s": 26850, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26914, "s": 26892, "text": "Defaultdict in Python" }, { "code": null, "e": 26960, "s": 26914, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26999, "s": 26960, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27037, "s": 26999, "text": "Python | Convert a list to dictionary" } ]
How to find the mean of columns of an R data frame or a matrix?
If all the columns in an R data frame are numeric then it makes sense to find the mean for each of the columns. This calculation will help us to view how different the values of means are for each of the columns but to make sure that they are significantly different, we will need to run a hypothesis test. To find the column means of a data frame or a matrix we can use colMeans function. Consider the below data frame − Live Demo set.seed(9) x1<-rnorm(20,0.2) x2<-rnorm(20,0.5) x3<-rnorm(20,0.8) x4<-rnorm(20,1.5) x5<-rpois(20,2) x6<-rpois(20,5) df<-data.frame(x1,x2,x3,x4,x5,x6) df x1 x2 x3 x4 x5 x6 1 -0.56679604 2.2569929 -0.008456344 1.7812222 2 4 2 -0.61645834 0.6822521 -1.219381694 0.2972914 4 5 3 0.05846481 0.2331113 0.061275928 1.9651637 1 3 4 -0.07760503 1.4264216 1.182886561 1.8520164 4 5 5 0.63630690 -0.1933319 2.530863668 0.9101438 2 3 6 -0.98687252 3.1819901 0.596918049 0.6464000 4 10 7 1.39198691 0.7225245 -0.196397348 1.2532679 4 7 8 0.18180966 -0.2066724 -0.506536295 3.0393386 3 5 9 -0.04808460 0.9172132 -0.197831604 2.0460777 0 4 10 -0.16293689 0.8695568 0.234971274 3.0649619 1 3 11 1.47757055 -0.4137643 2.552057836 1.7496702 2 4 12 -0.26889715 0.1830853 0.252228648 -0.4624186 1 4 13 0.27105410 1.5490592 -0.058525708 0.6909398 3 3 14 -0.06603845 0.6681118 0.849294533 1.0013149 2 5 15 2.04525720 0.5314402 0.599955518 1.8051218 1 7 16 -0.63944966 -0.5103305 -0.303954449 1.2107928 0 4 17 0.12255194 0.8827515 1.040588038 2.9577142 0 2 18 -2.41770553 -0.3196965 1.181113616 2.3737555 5 5 19 1.08788403 0.8617111 3.030458950 0.5470440 3 6 20 -0.50749145 0.5933714 1.999202392 1.4683245 1 6 colMeans(df) x1 x2 x3 x4 x5 x6 0.04572752 0.69578987 0.68103658 1.50990712 2.15000000 4.75000000 Finding the mean of columns of a matrix if the matrix is a square matrix − Live Demo Matrix<-matrix(1:100,nrow=10) Matrix [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 11 21 31 41 51 61 71 81 91 [2,] 2 12 22 32 42 52 62 72 82 92 [3,] 3 13 23 33 43 53 63 73 83 93 [4,] 4 14 24 34 44 54 64 74 84 94 [5,] 5 15 25 35 45 55 65 75 85 95 [6,] 6 16 26 36 46 56 66 76 86 96 [7,] 7 17 27 37 47 57 67 77 87 97 [8,] 8 18 28 38 48 58 68 78 88 98 [9,] 9 19 29 39 49 59 69 79 89 99 [10,] 10 20 30 40 50 60 70 80 90 100 colMeans(Matrix) [1] 5.5 15.5 25.5 35.5 45.5 55.5 65.5 75.5 85.5 95.5 Live Demo Finding the mean of columns of a matrix if the matrix is not a square matrix − Matrix_new<-matrix(1:100,ncol=20) Matrix_new [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [1,] 1 6 11 16 21 26 31 36 41 46 51 56 61 66 [2,] 2 7 12 17 22 27 32 37 42 47 52 57 62 67 [3,] 3 8 13 18 23 28 33 38 43 48 53 58 63 68 [4,] 4 9 14 19 24 29 34 39 44 49 54 59 64 69 [5,] 5 10 15 20 25 30 35 40 45 50 55 60 65 70 [,15] [,16] [,17] [,18] [,19] [,20] [1,] 71 76 81 86 91 96 [2,] 72 77 82 87 92 97 [3,] 73 78 83 88 93 98 [4,] 74 79 84 89 94 99 [5,] 75 80 85 90 95 100 colMeans(Matrix_new) [1] 3 8 13 18 23 28 33 38 43 48 53 58 63 68 73 78 83 88 93 98
[ { "code": null, "e": 1452, "s": 1062, "text": "If all the columns in an R data frame are numeric then it makes sense to find the mean for each of the columns. This calculation will help us to view how different the values of means are for each of the columns but to make sure that they are significantly different, we will need to run a hypothesis test. To find the column means of a data frame or a matrix we can use colMeans function." }, { "code": null, "e": 1484, "s": 1452, "text": "Consider the below data frame −" }, { "code": null, "e": 1495, "s": 1484, "text": " Live Demo" }, { "code": null, "e": 1648, "s": 1495, "text": "set.seed(9)\nx1<-rnorm(20,0.2)\nx2<-rnorm(20,0.5)\nx3<-rnorm(20,0.8)\nx4<-rnorm(20,1.5)\nx5<-rpois(20,2)\nx6<-rpois(20,5)\ndf<-data.frame(x1,x2,x3,x4,x5,x6)\ndf" }, { "code": null, "e": 2695, "s": 1648, "text": "x1 x2 x3 x4 x5 x6\n1 -0.56679604 2.2569929 -0.008456344 1.7812222 2 4\n2 -0.61645834 0.6822521 -1.219381694 0.2972914 4 5\n3 0.05846481 0.2331113 0.061275928 1.9651637 1 3\n4 -0.07760503 1.4264216 1.182886561 1.8520164 4 5\n5 0.63630690 -0.1933319 2.530863668 0.9101438 2 3\n6 -0.98687252 3.1819901 0.596918049 0.6464000 4 10\n7 1.39198691 0.7225245 -0.196397348 1.2532679 4 7\n8 0.18180966 -0.2066724 -0.506536295 3.0393386 3 5\n9 -0.04808460 0.9172132 -0.197831604 2.0460777 0 4\n10 -0.16293689 0.8695568 0.234971274 3.0649619 1 3\n11 1.47757055 -0.4137643 2.552057836 1.7496702 2 4\n12 -0.26889715 0.1830853 0.252228648 -0.4624186 1 4\n13 0.27105410 1.5490592 -0.058525708 0.6909398 3 3\n14 -0.06603845 0.6681118 0.849294533 1.0013149 2 5\n15 2.04525720 0.5314402 0.599955518 1.8051218 1 7\n16 -0.63944966 -0.5103305 -0.303954449 1.2107928 0 4\n17 0.12255194 0.8827515 1.040588038 2.9577142 0 2\n18 -2.41770553 -0.3196965 1.181113616 2.3737555 5 5\n19 1.08788403 0.8617111 3.030458950 0.5470440 3 6\n20 -0.50749145 0.5933714 1.999202392 1.4683245 1 6" }, { "code": null, "e": 2792, "s": 2695, "text": "colMeans(df)\nx1 x2 x3 x4 x5 x6\n0.04572752 0.69578987 0.68103658 1.50990712 2.15000000 4.75000000" }, { "code": null, "e": 2867, "s": 2792, "text": "Finding the mean of columns of a matrix if the matrix is a square matrix −" }, { "code": null, "e": 2878, "s": 2867, "text": " Live Demo" }, { "code": null, "e": 2915, "s": 2878, "text": "Matrix<-matrix(1:100,nrow=10)\nMatrix" }, { "code": null, "e": 3379, "s": 2915, "text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 14 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95\n[6,] 6 16 26 36 46 56 66 76 86 96\n[7,] 7 17 27 37 47 57 67 77 87 97\n[8,] 8 18 28 38 48 58 68 78 88 98\n[9,] 9 19 29 39 49 59 69 79 89 99\n[10,] 10 20 30 40 50 60 70 80 90 100\ncolMeans(Matrix)\n[1] 5.5 15.5 25.5 35.5 45.5 55.5 65.5 75.5 85.5 95.5" }, { "code": null, "e": 3390, "s": 3379, "text": " Live Demo" }, { "code": null, "e": 3469, "s": 3390, "text": "Finding the mean of columns of a matrix if the matrix is not a square matrix −" }, { "code": null, "e": 3514, "s": 3469, "text": "Matrix_new<-matrix(1:100,ncol=20)\nMatrix_new" }, { "code": null, "e": 4050, "s": 3514, "text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]\n[1,] 1 6 11 16 21 26 31 36 41 46 51 56 61 66\n[2,] 2 7 12 17 22 27 32 37 42 47 52 57 62 67\n[3,] 3 8 13 18 23 28 33 38 43 48 53 58 63 68\n[4,] 4 9 14 19 24 29 34 39 44 49 54 59 64 69\n[5,] 5 10 15 20 25 30 35 40 45 50 55 60 65 70\n[,15] [,16] [,17] [,18] [,19] [,20]\n[1,] 71 76 81 86 91 96\n[2,] 72 77 82 87 92 97\n[3,] 73 78 83 88 93 98\n[4,] 74 79 84 89 94 99\n[5,] 75 80 85 90 95 100\ncolMeans(Matrix_new)\n[1] 3 8 13 18 23 28 33 38 43 48 53 58 63 68 73 78 83 88 93 98" } ]
abs(), labs(), llabs() functions in C/C++ - GeeksforGeeks
26 Apr, 2018 abs(), labs(), llabs() functions are defined in cstdlib header file. These functions return the absolute value of integer that is input to them as their argument. abs() function: Input to this function is value of type int in C and value of type int, long int or long long int in C++. In C output is of int type and in C++ the output has same data type as input.Below is the sample C++ program to show working of abs() function.// CPP program to illustrate// abs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// abs() function. val1 = abs(22); val2 = abs(-43); cout << "abs(22) = " << val1 << "\n"; cout << "abs(-43) = " << val2 << "\n"; return 0;}Output: abs(22) = 22 abs(-43) = 43 labs() function: This is the long int version of abs() function. Both the input and output are of long int type.Below is the sample C++ program to show working of labs() function.// CPP program to illustrate// labs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// labs() function. val1 = labs(1234355L); val2 = labs(-4325600L); cout << "labs(1234355L) = " << val1 << "\n"; cout << "labs(-4325600L) = " << val2 << "\n"; return 0;}Output: labs(1234355L) = 1234355 labs(-4325600L) = 4325600 llabs() function: This is the long long int version of abs() function. Both the input and output are of long long int type.Below is the sample C++ program to show working of llabs() function.// CPP program to illustrate// llabs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// labs() function. val1 = llabs(1234863551LL); val2 = llabs(-432592160LL); cout << "llabs(1234863551LL) = " << val1 << "\n"; cout << "llabs(-432592160LL) = " << val2 << "\n"; return 0;}Output: llabs(1234863551LL) = 1234863551 llabs(-432592160LL) = 432592160 My Personal Notes arrow_drop_upSave abs() function: Input to this function is value of type int in C and value of type int, long int or long long int in C++. In C output is of int type and in C++ the output has same data type as input.Below is the sample C++ program to show working of abs() function.// CPP program to illustrate// abs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// abs() function. val1 = abs(22); val2 = abs(-43); cout << "abs(22) = " << val1 << "\n"; cout << "abs(-43) = " << val2 << "\n"; return 0;}Output: abs(22) = 22 abs(-43) = 43 // CPP program to illustrate// abs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// abs() function. val1 = abs(22); val2 = abs(-43); cout << "abs(22) = " << val1 << "\n"; cout << "abs(-43) = " << val2 << "\n"; return 0;} Output: abs(22) = 22 abs(-43) = 43 labs() function: This is the long int version of abs() function. Both the input and output are of long int type.Below is the sample C++ program to show working of labs() function.// CPP program to illustrate// labs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// labs() function. val1 = labs(1234355L); val2 = labs(-4325600L); cout << "labs(1234355L) = " << val1 << "\n"; cout << "labs(-4325600L) = " << val2 << "\n"; return 0;}Output: labs(1234355L) = 1234355 labs(-4325600L) = 4325600 // CPP program to illustrate// labs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// labs() function. val1 = labs(1234355L); val2 = labs(-4325600L); cout << "labs(1234355L) = " << val1 << "\n"; cout << "labs(-4325600L) = " << val2 << "\n"; return 0;} Output: labs(1234355L) = 1234355 labs(-4325600L) = 4325600 llabs() function: This is the long long int version of abs() function. Both the input and output are of long long int type.Below is the sample C++ program to show working of llabs() function.// CPP program to illustrate// llabs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// labs() function. val1 = llabs(1234863551LL); val2 = llabs(-432592160LL); cout << "llabs(1234863551LL) = " << val1 << "\n"; cout << "llabs(-432592160LL) = " << val2 << "\n"; return 0;}Output: llabs(1234863551LL) = 1234863551 llabs(-432592160LL) = 432592160 My Personal Notes arrow_drop_upSave // CPP program to illustrate// llabs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// labs() function. val1 = llabs(1234863551LL); val2 = llabs(-432592160LL); cout << "llabs(1234863551LL) = " << val1 << "\n"; cout << "llabs(-432592160LL) = " << val2 << "\n"; return 0;} Output: llabs(1234863551LL) = 1234863551 llabs(-432592160LL) = 432592160 CPP-Library STL C++ Technical Scripter STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Classes and Objects Virtual Function in C++ Constructors in C++ Templates in C++ with Examples Operator Overloading in C++ Socket Programming in C/C++ Polymorphism in C++ Copy Constructor in C++ Friend class and function in C++ C++ Data Types
[ { "code": null, "e": 24521, "s": 24493, "text": "\n26 Apr, 2018" }, { "code": null, "e": 24684, "s": 24521, "text": "abs(), labs(), llabs() functions are defined in cstdlib header file. These functions return the absolute value of integer that is input to them as their argument." }, { "code": null, "e": 26609, "s": 24684, "text": "abs() function: Input to this function is value of type int in C and value of type int, long int or long long int in C++. In C output is of int type and in C++ the output has same data type as input.Below is the sample C++ program to show working of abs() function.// CPP program to illustrate// abs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// abs() function. val1 = abs(22); val2 = abs(-43); cout << \"abs(22) = \" << val1 << \"\\n\"; cout << \"abs(-43) = \" << val2 << \"\\n\"; return 0;}Output: \nabs(22) = 22\nabs(-43) = 43\nlabs() function: This is the long int version of abs() function. Both the input and output are of long int type.Below is the sample C++ program to show working of labs() function.// CPP program to illustrate// labs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// labs() function. val1 = labs(1234355L); val2 = labs(-4325600L); cout << \"labs(1234355L) = \" << val1 << \"\\n\"; cout << \"labs(-4325600L) = \" << val2 << \"\\n\"; return 0;}Output: \nlabs(1234355L) = 1234355\nlabs(-4325600L) = 4325600\nllabs() function: This is the long long int version of abs() function. Both the input and output are of long long int type.Below is the sample C++ program to show working of llabs() function.// CPP program to illustrate// llabs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// labs() function. val1 = llabs(1234863551LL); val2 = llabs(-432592160LL); cout << \"llabs(1234863551LL) = \" << val1 << \"\\n\"; cout << \"llabs(-432592160LL) = \" << val2 << \"\\n\"; return 0;}Output: \nllabs(1234863551LL) = 1234863551\nllabs(-432592160LL) = 432592160\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 27246, "s": 26609, "text": "abs() function: Input to this function is value of type int in C and value of type int, long int or long long int in C++. In C output is of int type and in C++ the output has same data type as input.Below is the sample C++ program to show working of abs() function.// CPP program to illustrate// abs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// abs() function. val1 = abs(22); val2 = abs(-43); cout << \"abs(22) = \" << val1 << \"\\n\"; cout << \"abs(-43) = \" << val2 << \"\\n\"; return 0;}Output: \nabs(22) = 22\nabs(-43) = 43\n" }, { "code": "// CPP program to illustrate// abs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// abs() function. val1 = abs(22); val2 = abs(-43); cout << \"abs(22) = \" << val1 << \"\\n\"; cout << \"abs(-43) = \" << val2 << \"\\n\"; return 0;}", "e": 27582, "s": 27246, "text": null }, { "code": null, "e": 27619, "s": 27582, "text": "Output: \nabs(22) = 22\nabs(-43) = 43\n" }, { "code": null, "e": 28224, "s": 27619, "text": "labs() function: This is the long int version of abs() function. Both the input and output are of long int type.Below is the sample C++ program to show working of labs() function.// CPP program to illustrate// labs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// labs() function. val1 = labs(1234355L); val2 = labs(-4325600L); cout << \"labs(1234355L) = \" << val1 << \"\\n\"; cout << \"labs(-4325600L) = \" << val2 << \"\\n\"; return 0;}Output: \nlabs(1234355L) = 1234355\nlabs(-4325600L) = 4325600\n" }, { "code": "// CPP program to illustrate// labs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// labs() function. val1 = labs(1234355L); val2 = labs(-4325600L); cout << \"labs(1234355L) = \" << val1 << \"\\n\"; cout << \"labs(-4325600L) = \" << val2 << \"\\n\"; return 0;}", "e": 28590, "s": 28224, "text": null }, { "code": null, "e": 28651, "s": 28590, "text": "Output: \nlabs(1234355L) = 1234355\nlabs(-4325600L) = 4325600\n" }, { "code": null, "e": 29336, "s": 28651, "text": "llabs() function: This is the long long int version of abs() function. Both the input and output are of long long int type.Below is the sample C++ program to show working of llabs() function.// CPP program to illustrate// llabs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// labs() function. val1 = llabs(1234863551LL); val2 = llabs(-432592160LL); cout << \"llabs(1234863551LL) = \" << val1 << \"\\n\"; cout << \"llabs(-432592160LL) = \" << val2 << \"\\n\"; return 0;}Output: \nllabs(1234863551LL) = 1234863551\nllabs(-432592160LL) = 432592160\nMy Personal Notes\narrow_drop_upSave" }, { "code": "// CPP program to illustrate// llabs() function#include <cstdlib>#include <iostream> using namespace std; int main(){ int val1, val2; /// finding absolute value using /// labs() function. val1 = llabs(1234863551LL); val2 = llabs(-432592160LL); cout << \"llabs(1234863551LL) = \" << val1 << \"\\n\"; cout << \"llabs(-432592160LL) = \" << val2 << \"\\n\"; return 0;}", "e": 29721, "s": 29336, "text": null }, { "code": null, "e": 29796, "s": 29721, "text": "Output: \nllabs(1234863551LL) = 1234863551\nllabs(-432592160LL) = 432592160\n" }, { "code": null, "e": 29808, "s": 29796, "text": "CPP-Library" }, { "code": null, "e": 29812, "s": 29808, "text": "STL" }, { "code": null, "e": 29816, "s": 29812, "text": "C++" }, { "code": null, "e": 29835, "s": 29816, "text": "Technical Scripter" }, { "code": null, "e": 29839, "s": 29835, "text": "STL" }, { "code": null, "e": 29843, "s": 29839, "text": "CPP" }, { "code": null, "e": 29941, "s": 29843, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29965, "s": 29941, "text": "C++ Classes and Objects" }, { "code": null, "e": 29989, "s": 29965, "text": "Virtual Function in C++" }, { "code": null, "e": 30009, "s": 29989, "text": "Constructors in C++" }, { "code": null, "e": 30040, "s": 30009, "text": "Templates in C++ with Examples" }, { "code": null, "e": 30068, "s": 30040, "text": "Operator Overloading in C++" }, { "code": null, "e": 30096, "s": 30068, "text": "Socket Programming in C/C++" }, { "code": null, "e": 30116, "s": 30096, "text": "Polymorphism in C++" }, { "code": null, "e": 30140, "s": 30116, "text": "Copy Constructor in C++" }, { "code": null, "e": 30173, "s": 30140, "text": "Friend class and function in C++" } ]
Fzf - File Search From Linux Terminal - GeeksforGeeks
11 May, 2021 Fzf is a command-line general-purpose fuzzy finder tool. It is somewhat like grep. It is a cross-platform command-line tool, that helps you to search and open files quickly. Furthermore, it is open-sourced portable with no dependencies. It has supports for Vim/Neo vim plugin, key bindings, and fuzzy auto-completion. It can be used with any list; files, command history, processes, hostnames, bookmarks, git commits, etc. Installation on the various platform through package manager : Step 1: Open up the terminal and run the following command to see if git is installed on your machine or not. git --version If the output looks like this, then you are good to go, or else you need to install git first on your system. You can install git by running the following command: sudo apt install git-all Step 2: Clone the fzf repository using the following command: git clone --depth 1 https://github.com/junegunn/fzf.git cloning fzf repo Step 3: Navigate to the cloned folder. cd fzf Step 4: Run the installation script using the following command. ./install installing fzf nano is a text editor, and we are going to open the searched file in nano. And (fzf –height 40%) will open a fuzzy finder window within 40% of the screen. nano $(fzf --height 40% ) Note: we can replace nano with other utility commands like cat(used to view a file), rm(used to remove a file), kill(used to kill a running process), cd( to change directory),etc. In this example, we are opening a file called geeks.sh using a fuzzy finder prompt. We can use the keys to navigate through, or we can just type the name of the file that we are looking for. We can use the keyboard key to navigate through the list of items/files. CTRL-J / CTRL-N to the move cursor down and CTRL-K/ CTRL-P to move the cursor up. Use any of these CTRL-C / CTRL-G / ESC key combinations to exit from the finder. To select multiple files run fzf as fzf -m i.e. multi-select mode (-m), and use TAB to mark multiple items/files. Use Mouse: scroll to scroll through items/files, right-click to multi-select the file, left-click/double-click to open the file. To select multiple files in finder, we open fzf in multi-select mode using -m argument. The red triangle in front of the items/files shows that these files are selected. After selecting desired files hit ENTER to display their path location. fzf -m selecting multiple files Steps to Uninstall fzf: Step 1: Navigate to fzf directory using following command: cd fzf Step 2: Use ls command to list all the items in that directory. ls listing all files Step 3: Run the uninstallation file i.e. uninstall, from this fzf directory to remove the fuzzy finder from your system. ./uninstall Successfully uninstalled fzf Linux-Tools Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples chown command in Linux with Examples Docker - COPY Instruction nohup Command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples Thread functions in C/C++ Array Basics in Shell Scripting | Set 1
[ { "code": null, "e": 25761, "s": 25733, "text": "\n11 May, 2021" }, { "code": null, "e": 26184, "s": 25761, "text": "Fzf is a command-line general-purpose fuzzy finder tool. It is somewhat like grep. It is a cross-platform command-line tool, that helps you to search and open files quickly. Furthermore, it is open-sourced portable with no dependencies. It has supports for Vim/Neo vim plugin, key bindings, and fuzzy auto-completion. It can be used with any list; files, command history, processes, hostnames, bookmarks, git commits, etc." }, { "code": null, "e": 26247, "s": 26184, "text": "Installation on the various platform through package manager :" }, { "code": null, "e": 26357, "s": 26247, "text": "Step 1: Open up the terminal and run the following command to see if git is installed on your machine or not." }, { "code": null, "e": 26371, "s": 26357, "text": "git --version" }, { "code": null, "e": 26535, "s": 26371, "text": "If the output looks like this, then you are good to go, or else you need to install git first on your system. You can install git by running the following command:" }, { "code": null, "e": 26561, "s": 26535, "text": " sudo apt install git-all" }, { "code": null, "e": 26623, "s": 26561, "text": "Step 2: Clone the fzf repository using the following command:" }, { "code": null, "e": 26679, "s": 26623, "text": "git clone --depth 1 https://github.com/junegunn/fzf.git" }, { "code": null, "e": 26696, "s": 26679, "text": "cloning fzf repo" }, { "code": null, "e": 26735, "s": 26696, "text": "Step 3: Navigate to the cloned folder." }, { "code": null, "e": 26742, "s": 26735, "text": "cd fzf" }, { "code": null, "e": 26807, "s": 26742, "text": "Step 4: Run the installation script using the following command." }, { "code": null, "e": 26817, "s": 26807, "text": "./install" }, { "code": null, "e": 26832, "s": 26817, "text": "installing fzf" }, { "code": null, "e": 26987, "s": 26832, "text": "nano is a text editor, and we are going to open the searched file in nano. And (fzf –height 40%) will open a fuzzy finder window within 40% of the screen." }, { "code": null, "e": 27015, "s": 26987, "text": "nano $(fzf --height 40% ) " }, { "code": null, "e": 27196, "s": 27015, "text": "Note: we can replace nano with other utility commands like cat(used to view a file), rm(used to remove a file), kill(used to kill a running process), cd( to change directory),etc. " }, { "code": null, "e": 27388, "s": 27196, "text": "In this example, we are opening a file called geeks.sh using a fuzzy finder prompt. We can use the keys to navigate through, or we can just type the name of the file that we are looking for. " }, { "code": null, "e": 27461, "s": 27388, "text": "We can use the keyboard key to navigate through the list of items/files." }, { "code": null, "e": 27544, "s": 27461, "text": "CTRL-J / CTRL-N to the move cursor down and CTRL-K/ CTRL-P to move the cursor up." }, { "code": null, "e": 27626, "s": 27544, "text": "Use any of these CTRL-C / CTRL-G / ESC key combinations to exit from the finder." }, { "code": null, "e": 27741, "s": 27626, "text": "To select multiple files run fzf as fzf -m i.e. multi-select mode (-m), and use TAB to mark multiple items/files." }, { "code": null, "e": 27871, "s": 27741, "text": "Use Mouse: scroll to scroll through items/files, right-click to multi-select the file, left-click/double-click to open the file." }, { "code": null, "e": 28113, "s": 27871, "text": "To select multiple files in finder, we open fzf in multi-select mode using -m argument. The red triangle in front of the items/files shows that these files are selected. After selecting desired files hit ENTER to display their path location." }, { "code": null, "e": 28120, "s": 28113, "text": "fzf -m" }, { "code": null, "e": 28145, "s": 28120, "text": "selecting multiple files" }, { "code": null, "e": 28169, "s": 28145, "text": "Steps to Uninstall fzf:" }, { "code": null, "e": 28228, "s": 28169, "text": "Step 1: Navigate to fzf directory using following command:" }, { "code": null, "e": 28235, "s": 28228, "text": "cd fzf" }, { "code": null, "e": 28299, "s": 28235, "text": "Step 2: Use ls command to list all the items in that directory." }, { "code": null, "e": 28302, "s": 28299, "text": "ls" }, { "code": null, "e": 28320, "s": 28302, "text": "listing all files" }, { "code": null, "e": 28441, "s": 28320, "text": "Step 3: Run the uninstallation file i.e. uninstall, from this fzf directory to remove the fuzzy finder from your system." }, { "code": null, "e": 28453, "s": 28441, "text": "./uninstall" }, { "code": null, "e": 28482, "s": 28453, "text": "Successfully uninstalled fzf" }, { "code": null, "e": 28494, "s": 28482, "text": "Linux-Tools" }, { "code": null, "e": 28501, "s": 28494, "text": "Picked" }, { "code": null, "e": 28512, "s": 28501, "text": "Linux-Unix" }, { "code": null, "e": 28610, "s": 28512, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28645, "s": 28610, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28679, "s": 28645, "text": "mv command in Linux with examples" }, { "code": null, "e": 28716, "s": 28679, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28742, "s": 28716, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28779, "s": 28742, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 28808, "s": 28779, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28850, "s": 28808, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 28886, "s": 28850, "text": "uniq Command in LINUX with examples" }, { "code": null, "e": 28912, "s": 28886, "text": "Thread functions in C/C++" } ]
Big, fast human-in-the-loop NLP with Elasticsearch | by Joel Klinger | Towards Data Science
Part I: the keyword factory tl;dr: You could make one of these if you 1) store your data in Elasticsearch 2) use the clio_keywordsfunction from the clio-litepackage, pointing at your Elasticsearch endpoint 3) Host it in a Flask app, such as this. Part II: a contextual search engine tl;dr: You could make one of these if you 1) store your data in Elasticsearch 2) host a lambda API gateway using clio-lite 3) Interrogate it with your own front-end, or use something out-of-the-box like searchkit The current paradigm for day-to-day working of many NLP Data Scientists is to throw open a laptop, fire up Python or R, make some models and wrap up some conclusions. This can work very well for exploratory analysis, but if you need to put a human (such as an expert, your boss, or even yourself) in-the-loop, this can become prohibitively slow. In this two-part blog, I’ll try to convince you that there are bigger, faster ways to do NLP. In my day-to-day work at Nesta, I develop tools and infrastructures to enable people to make better decisions, and for people to be able to make those decisions with up-to-date data. We deliver tools to local, national and international policymakers and funders who rely on being kept abreast of the latest innovations in science, technology and society. Since these people are accountable for their decisions, this generally rules out tools which adopt black-box procedures. ‘Human-in-the-loop NLP’ is our way of addressing these needs, not least since unstructured text data is one of the richest, most available, and up-to-date forms of data. Data engineers, database admins and devops engineers should all be familiar with the ‘elastic stack’ (with Elasticsearch sitting at it’s core) as the go-to technology for storing and analysing log files or building search engines, though perhaps many of them aren’t so familiar with the vast potential for data science research. Meanwhile many data scientists have, at best, a basic familiarity with Elasticsearch as a data storage technology. In short: Elasticsearch is a database for search engines that is able to perform lightning-fast searches because of how the data is stored. In Elasticsearch, documents are stored as term-frequency vectors (a procedure known as ‘inverted indexing’) and the document-frequency is pre-calculated for each term. This means a couple of things: Term-by-term co-occurences are incredibly fast to extract on the fly.Important terms can be identified via the standard data science ‘tf-idf’ procedure on the fly. Term-by-term co-occurences are incredibly fast to extract on the fly. Important terms can be identified via the standard data science ‘tf-idf’ procedure on the fly. From a data scientist’s perspective an Elasticsearch database is a very basic (but powerful) pre-trained model for extracting keywords, synonyms, similar documents and outliers. In this two-part blog, I’ll touch on all of these using out-of-the-box functionality (although more sophisticated approaches could certainly be taken). Generating lists of keywords (or synonyms) is a common NLP task for data scientists. It can have applications from dimensionality reduction to topic modelling, and can also be useful for human-in-the-loop analysis by providing human analysts with a data-driven set of terms which can be used for more laborious tasks. Many data scientists would tackle this using appropriate python (or R) packages in order to produce fairly static outputs, which for reports or papers is fine. Most of the time we have the best intentions for our results to be accessible to non-experts, but in practice people end up getting what they’re given: static outputs. What are our options for a scalable and flexible tool which can be used by non-experts? The are tons of python-based approaches which can solve this problem, such as topic modelling (e.g. Latent Dirichlet Allocation or Correlation Explanation), clustering on word vectors (such as word embeddings or vanilla count vectors) or using co-occurence matrices or networks. All of these approaches can give very sensible results, and to be honest I’m not attempting to beat these approaches on perceived accuracy. If I was tasked with doing a one-off ad-hoc analysis, I could consider any of the above. However, I’m a fan of scalable, shareable and flexible solutions to problems: Scalability: all of my suggested python solutions require data and models to sit in memory. For large number of documents, or large vocabularies, the memory consumption will be heavy. One solution to this would be to sample the data at the expense of the ‘depth’ of your model. Shareability: how can you share results with a non-expert without installing python packages on their laptop, whilst hoping that your setup is compatible with their laptop? Two possibilities could be to host your machine learning models (which could be anything from a cluster model to a co-occurence matrix) on a remote server (but beware of that large memory overhead!), or alternatively you could pre-generate static sets of keywords (which is very simplistic). Flexibility: imagine you want to update your model with one more document, or decide to filter your data in-situ — it’s not trivial to do this with regular machine learning models. Your best approach would likely be to pre-generate one model per pre-defined filter, which is computationally expensive. Remembering that Elasticsearch is effectively a pre-trained model of term co-occurences, filterable by term significance, it is clear to see why it can natively generate lists of keywords on the fly. What’s more, any method we apply to Elasticsearch is inherently scalable, shareable and flexible: Scalability: Elasticsearch is performant up to the petabyte scale. Shareability: Elasticsearch exposes methods on the data via a simple REST API. To do sophisticated tasks you can simply string together some lightweight python code hosted on a remote server. Flexibility: updating your ‘model’ is as simple as adding a new document to the server. Filtering your data by any field is a bread-and-butter operation. In principle we could implement our own procedure from scratch for extracting keywords, however there are a couple of shortcuts you can employ just by using out-of-the-box features of Elasticsearch. The following python code wraps up a query to the Elasticsearch API (replace URL with your own endpoint and FIELD_NAME with the name of the field(s) in your database you would like to query): import requestsimport jsondef make_query(url, q, alg, field, shard_size=1000, size=25): """See this gist for docs""" query = {"query" : { "match" : {field : q } }, "size": 0, "aggregations" : { "my_sample" : { "sampler" : {"shard_size" : shard_size}, "aggregations": { "keywords" : { "significant_text" : { "size": size, "field" : field, alg:{} } } } } } } return [row['key'] for row in requests.post(f'{url}/_search', data=json.dumps(query), headers={'Content-Type':'application/json'}).json()['aggregations']['my_sample']['keywords']['buckets']] Under the hood, this query is doing the following: Finding all documents containing the text query in the field field.Extracting the size most significant terms from field, calculated according the the jlh algorithm. Finding all documents containing the text query in the field field. Extracting the size most significant terms from field, calculated according the the jlh algorithm. On top of that, increasing the size of shard_size will increase stability (and depth) of your ‘model’, at the expense of computational performance. In practice, you will only expect your model to become less stable for very rare terms — in which case you could build a workaround for this. I’ve got all of arXiv’s scientific publications in my Elasticsearch database, and this is how it performs on the abstract text for the following queries: python pandas['pandas', 'numpy', 'package', 'scipy', 'scikit', 'library', 'pypi', 'cython', 'github']-----------------------------elasticsearch['kibana', 'lucene', 'hadoop', 'retrieving', 'apache', 'engine', 'textual', 'documents', 'ranking']-----------------------------machine learning['learning', 'training', 'algorithms', 'neural', 'supervised', 'automl', 'intelligence', 'deep', 'tasks']----------------------------------------------------------drones and robots['robot', 'drones', 'robotics', 'robotic', 'humanoid', "robot's", 'drone', 'autonomous', 'mobile']----------------------------- ...and this is out-of-the-box functionality! Some easy criticisms would be: N-grams aren’t leveraged at all, neither in the query nor the results. For example machine learning is treated as {machine, learning} rather than {machine learning, machine, learning}.It is not impossible for stop-words to appear in the results.Out-of-sample misspellings aren’t dealt with at all.Plurals and possessive forms of nouns and all verb conjugations are listed separately. N-grams aren’t leveraged at all, neither in the query nor the results. For example machine learning is treated as {machine, learning} rather than {machine learning, machine, learning}. It is not impossible for stop-words to appear in the results. Out-of-sample misspellings aren’t dealt with at all. Plurals and possessive forms of nouns and all verb conjugations are listed separately. I’m not going to address the latter two points here, but dealing with them is fairly trivial. For example, misspellings can be dealt with in at least two ways, for example using: Elasticsearch’s n-gram tokenizer (beware that Elasticsearch’s defines n-grams at the character-level, not to be confused with the data scientist’s term-level n-gram) or using the phonetic tokenizer plug-in. In order to deal with n-gram queries (such as machine learning) I have created a field in my Elasticsearch database containing pre-tokenized abstracts, in which I have already identified n-grams. Note that the ‘schema’ for this field can be found here. If you want to know, I process my n-grams by using a look-up table based on n-grams from Wiktionary (but a more data-driven approach would also work). Although I haven’t implemented this myself, similar preprocessing can be done for plurals/possessives/conjugations, effectively by replacing all non-simple forms of terms by their simple form. Finally, to avoid the potential embarrassment of returning stop-words I have taken to generating them from the data using my make_query function: and of but yes with however[‘however’, ‘but’, ‘not’, ‘answer’, ‘with’, ‘the’, ‘is’, ‘of’, ‘to’, ‘a’, ‘in’, ‘and’, ‘that’, ‘no’, ‘this’, ‘we’, ‘only’, ‘for’, ‘are’, ‘be’, ‘it’, ‘can’, ‘by’, ‘on’, ‘an’, ‘question’, ‘also’, ‘have’, ‘has’, ‘which’, ‘there’, ‘as’, ‘or’, ‘such’, ‘if’, ‘whether’, ‘does’, ‘more’, ‘from’, ‘one’, ‘been’, ‘these’, ‘show’, ‘at’, ‘do’] and I simply exclude these from the returned results. Check out the keyword factory in action over on the arXlive website, featuring n-grams and stopword removal. You can make your own Flask app using the clio_keywordsfunction from the clio-litepackage. Have fun! Consider a very technical dataset such as that from arXiv, the world’s largest repository of physical, quantitative and computational science pre-prints. Assuming that you’re not polymath savant, what would be your strategy for finding the latest novel research on arXiv, relating to Big Data and Security? If you were to make that exact search on arXiv, you’d find yourself with a decent set of results, but the problem is that when you were searching for Big Data, you might not have realised that you also wanted to include tangentially-related terms such as {hadoop, spark, cloud-computing} in your query. What if there was some big breakthrough in Cloud Computing and Security that you’ve been missing out on? (TL;DR this is the same search with a ‘contextual’ search engine) I’m going to break this problem down into two pieces, and solve it by using some Elasticsearch functionality wrapped up in Python: Firstly, how do you make a decent search query without being a genius? Secondly, how can we define novelty? Back to the problem of making a decent search query. What approaches might a genius take? Well, they could go down the route of ‘keyword expansion’, for example by considering all of {hadoop, spark, cloud-computing} in addition to big data, and all of {attack, encryption, authentication} in addition to security. Potentially this is a promising way to go, and we’ve already written the tools to help do this in the previous blog. However, the main problem with the ‘keyword expansion’ approach is that it lacks context. A natural extension to this would instead be ‘document expansion’, and thankfully Elasticsearch has this feature built-in. Well, to be honest with you, Elasticsearch’s more-like-this query is really ‘keyword expansion++’ rather than a ‘document expansion’, as you might imagine it in a vector space. Under the hood, representative terms are selected from input documents (according to a highly configurable procedure) which you would like to ‘expand’ from. The advantage to doing this over a pure ‘keyword expansion’ approach, is that terms which co-occur with all input terms are deemed to be more important than those which only co-occur with a subset of the input terms. The upshot is that the expanded set of keywords which are used to seed the ‘document expansion’ can be assumed to have a high degree of contextual relevance. So here’s my strategy: Make a vanilla query to Elasticsearch and retrieve the 10–25 most relevant documents. These will be our ‘seed’ documents. Follow up with a more-like-this query, using the seed documents. and that strategy looks a little like this (in practice it’s a bit more code, so it actually looks like this): # Make the initial vanilla queryr = simple_query(url, old_query, event, fields)data, docs = extract_docs(r)# Formulate the MLT querytotal = data['hits']['total']max_doc_freq = int(max_doc_frac*total)min_doc_freq = int(min_doc_freq*total)mlt_query = {"query": {"more_like_this": {"fields": fields, # the fields to consider "like": docs, # the seed docs "min_term_freq": min_term_freq, "max_query_terms": max_query_terms, "min_doc_freq": min_doc_freq, "max_doc_freq": max_doc_freq, "boost_terms": 1., "minimum_should_match": minimum_should_match, "include": True # include the seed docs } } }# Make the MLT queryquery = json.dumps(dict(**query, **mlt_query))params = {"search_type":"dfs_query_then_fetch"}r_mlt = requests.post(url, data=query, headers=headers, params=params)# Extract the results_data, docs = extract_docs(r_mlt) Note, that I serve this functionality via AWS API Gateway in a Lambda function. The code for deploying the above function can also be found in the same repo. Novelty doesn’t have a particularly narrow definition, and I admit that my definition for this blog is going to be fairly narrow... Novelty generally could be defined as any (and more) of {new, original, unusual}, and my definition is going to straddle the {original, unusual} concept. More formally (but not very formally), I’m asking the following question of each document in Elasticsearch: How different are you from your nearest neighbours? Just to clarify the logic here: if the total sample of documents is unbalanced, then a document belonging to a minority topic will be very different from the average document. We can avoid this by only comparing to nearest neighbours. And how better to get the nearest neighbours, than by using more-like-this all over again (the full code is here): mlt_query = { "query": { "more_like_this": { "fields": fields, # field you want to query "like": [{'_id':doc_id, # the doc we're analysing '_index':index}], "min_term_freq": 1, "max_query_terms": max_query_terms, "min_doc_freq": 1, "max_doc_freq": max_doc_freq, "boost_terms": 1., "minimum_should_match": minimum_should_match, "include": True } }, "size":1000, # the number of nearest neighbours "_source":["_score"]}# Make the search and normalise the scoresr = es.search(index=index, body=mlt_query)scores = [h['_score']/r['hits']['max_score'] for h in r['hits']['hits']]# Calculate novelty as the distance to a low percentiledelta = np.percentile(scores, similar_perc)return 1 - delta Naturally, any decent a definition of novelty which encapsulates the concept of being “unusual” should capture bad data, since one would hope that these would be unusual. I found that by applying the above novelty scorer to arXiv data I was able to root out a whole bunch of bad data, such as plagiarised and ‘comment’ articles. I went on to assign these a novelty of zero, but I’m sure you can work out your own approach! One downside of this novelty-scoring method is that it’s relatively slow to implement (it must be calculated on a document-by-document basis), and for this reason I preprocessed all of the documents in my Elasticsearch database. So, with some overzealous use of Elasticsearch’s more-like-this query we’re able to make expansive searches whilst deriving a very lightweight measure of novelty. Check out clio-lite to understand the code better, and if you want to see this in action, check out the HierarXy search engine of arXiv data. Note that I’ve also used the same pre-processing as described in Part I, as well as the data cleaning described in this blog. Thanks for reading!
[ { "code": null, "e": 419, "s": 172, "text": "Part I: the keyword factory tl;dr: You could make one of these if you 1) store your data in Elasticsearch 2) use the clio_keywordsfunction from the clio-litepackage, pointing at your Elasticsearch endpoint 3) Host it in a Flask app, such as this." }, { "code": null, "e": 668, "s": 419, "text": "Part II: a contextual search engine tl;dr: You could make one of these if you 1) store your data in Elasticsearch 2) host a lambda API gateway using clio-lite 3) Interrogate it with your own front-end, or use something out-of-the-box like searchkit" }, { "code": null, "e": 1108, "s": 668, "text": "The current paradigm for day-to-day working of many NLP Data Scientists is to throw open a laptop, fire up Python or R, make some models and wrap up some conclusions. This can work very well for exploratory analysis, but if you need to put a human (such as an expert, your boss, or even yourself) in-the-loop, this can become prohibitively slow. In this two-part blog, I’ll try to convince you that there are bigger, faster ways to do NLP." }, { "code": null, "e": 1754, "s": 1108, "text": "In my day-to-day work at Nesta, I develop tools and infrastructures to enable people to make better decisions, and for people to be able to make those decisions with up-to-date data. We deliver tools to local, national and international policymakers and funders who rely on being kept abreast of the latest innovations in science, technology and society. Since these people are accountable for their decisions, this generally rules out tools which adopt black-box procedures. ‘Human-in-the-loop NLP’ is our way of addressing these needs, not least since unstructured text data is one of the richest, most available, and up-to-date forms of data." }, { "code": null, "e": 2198, "s": 1754, "text": "Data engineers, database admins and devops engineers should all be familiar with the ‘elastic stack’ (with Elasticsearch sitting at it’s core) as the go-to technology for storing and analysing log files or building search engines, though perhaps many of them aren’t so familiar with the vast potential for data science research. Meanwhile many data scientists have, at best, a basic familiarity with Elasticsearch as a data storage technology." }, { "code": null, "e": 2338, "s": 2198, "text": "In short: Elasticsearch is a database for search engines that is able to perform lightning-fast searches because of how the data is stored." }, { "code": null, "e": 2537, "s": 2338, "text": "In Elasticsearch, documents are stored as term-frequency vectors (a procedure known as ‘inverted indexing’) and the document-frequency is pre-calculated for each term. This means a couple of things:" }, { "code": null, "e": 2701, "s": 2537, "text": "Term-by-term co-occurences are incredibly fast to extract on the fly.Important terms can be identified via the standard data science ‘tf-idf’ procedure on the fly." }, { "code": null, "e": 2771, "s": 2701, "text": "Term-by-term co-occurences are incredibly fast to extract on the fly." }, { "code": null, "e": 2866, "s": 2771, "text": "Important terms can be identified via the standard data science ‘tf-idf’ procedure on the fly." }, { "code": null, "e": 3196, "s": 2866, "text": "From a data scientist’s perspective an Elasticsearch database is a very basic (but powerful) pre-trained model for extracting keywords, synonyms, similar documents and outliers. In this two-part blog, I’ll touch on all of these using out-of-the-box functionality (although more sophisticated approaches could certainly be taken)." }, { "code": null, "e": 3514, "s": 3196, "text": "Generating lists of keywords (or synonyms) is a common NLP task for data scientists. It can have applications from dimensionality reduction to topic modelling, and can also be useful for human-in-the-loop analysis by providing human analysts with a data-driven set of terms which can be used for more laborious tasks." }, { "code": null, "e": 3930, "s": 3514, "text": "Many data scientists would tackle this using appropriate python (or R) packages in order to produce fairly static outputs, which for reports or papers is fine. Most of the time we have the best intentions for our results to be accessible to non-experts, but in practice people end up getting what they’re given: static outputs. What are our options for a scalable and flexible tool which can be used by non-experts?" }, { "code": null, "e": 4209, "s": 3930, "text": "The are tons of python-based approaches which can solve this problem, such as topic modelling (e.g. Latent Dirichlet Allocation or Correlation Explanation), clustering on word vectors (such as word embeddings or vanilla count vectors) or using co-occurence matrices or networks." }, { "code": null, "e": 4438, "s": 4209, "text": "All of these approaches can give very sensible results, and to be honest I’m not attempting to beat these approaches on perceived accuracy. If I was tasked with doing a one-off ad-hoc analysis, I could consider any of the above." }, { "code": null, "e": 4516, "s": 4438, "text": "However, I’m a fan of scalable, shareable and flexible solutions to problems:" }, { "code": null, "e": 4794, "s": 4516, "text": "Scalability: all of my suggested python solutions require data and models to sit in memory. For large number of documents, or large vocabularies, the memory consumption will be heavy. One solution to this would be to sample the data at the expense of the ‘depth’ of your model." }, { "code": null, "e": 5259, "s": 4794, "text": "Shareability: how can you share results with a non-expert without installing python packages on their laptop, whilst hoping that your setup is compatible with their laptop? Two possibilities could be to host your machine learning models (which could be anything from a cluster model to a co-occurence matrix) on a remote server (but beware of that large memory overhead!), or alternatively you could pre-generate static sets of keywords (which is very simplistic)." }, { "code": null, "e": 5561, "s": 5259, "text": "Flexibility: imagine you want to update your model with one more document, or decide to filter your data in-situ — it’s not trivial to do this with regular machine learning models. Your best approach would likely be to pre-generate one model per pre-defined filter, which is computationally expensive." }, { "code": null, "e": 5859, "s": 5561, "text": "Remembering that Elasticsearch is effectively a pre-trained model of term co-occurences, filterable by term significance, it is clear to see why it can natively generate lists of keywords on the fly. What’s more, any method we apply to Elasticsearch is inherently scalable, shareable and flexible:" }, { "code": null, "e": 5926, "s": 5859, "text": "Scalability: Elasticsearch is performant up to the petabyte scale." }, { "code": null, "e": 6118, "s": 5926, "text": "Shareability: Elasticsearch exposes methods on the data via a simple REST API. To do sophisticated tasks you can simply string together some lightweight python code hosted on a remote server." }, { "code": null, "e": 6272, "s": 6118, "text": "Flexibility: updating your ‘model’ is as simple as adding a new document to the server. Filtering your data by any field is a bread-and-butter operation." }, { "code": null, "e": 6471, "s": 6272, "text": "In principle we could implement our own procedure from scratch for extracting keywords, however there are a couple of shortcuts you can employ just by using out-of-the-box features of Elasticsearch." }, { "code": null, "e": 6663, "s": 6471, "text": "The following python code wraps up a query to the Elasticsearch API (replace URL with your own endpoint and FIELD_NAME with the name of the field(s) in your database you would like to query):" }, { "code": null, "e": 7630, "s": 6663, "text": "import requestsimport jsondef make_query(url, q, alg, field, shard_size=1000, size=25): \"\"\"See this gist for docs\"\"\" query = {\"query\" : { \"match\" : {field : q } }, \"size\": 0, \"aggregations\" : { \"my_sample\" : { \"sampler\" : {\"shard_size\" : shard_size}, \"aggregations\": { \"keywords\" : { \"significant_text\" : { \"size\": size, \"field\" : field, alg:{} } } } } } } return [row['key'] for row in requests.post(f'{url}/_search', data=json.dumps(query), headers={'Content-Type':'application/json'}).json()['aggregations']['my_sample']['keywords']['buckets']]" }, { "code": null, "e": 7681, "s": 7630, "text": "Under the hood, this query is doing the following:" }, { "code": null, "e": 7847, "s": 7681, "text": "Finding all documents containing the text query in the field field.Extracting the size most significant terms from field, calculated according the the jlh algorithm." }, { "code": null, "e": 7915, "s": 7847, "text": "Finding all documents containing the text query in the field field." }, { "code": null, "e": 8014, "s": 7915, "text": "Extracting the size most significant terms from field, calculated according the the jlh algorithm." }, { "code": null, "e": 8304, "s": 8014, "text": "On top of that, increasing the size of shard_size will increase stability (and depth) of your ‘model’, at the expense of computational performance. In practice, you will only expect your model to become less stable for very rare terms — in which case you could build a workaround for this." }, { "code": null, "e": 8458, "s": 8304, "text": "I’ve got all of arXiv’s scientific publications in my Elasticsearch database, and this is how it performs on the abstract text for the following queries:" }, { "code": null, "e": 9053, "s": 8458, "text": "python pandas['pandas', 'numpy', 'package', 'scipy', 'scikit', 'library', 'pypi', 'cython', 'github']-----------------------------elasticsearch['kibana', 'lucene', 'hadoop', 'retrieving', 'apache', 'engine', 'textual', 'documents', 'ranking']-----------------------------machine learning['learning', 'training', 'algorithms', 'neural', 'supervised', 'automl', 'intelligence', 'deep', 'tasks']----------------------------------------------------------drones and robots['robot', 'drones', 'robotics', 'robotic', 'humanoid', \"robot's\", 'drone', 'autonomous', 'mobile']-----------------------------" }, { "code": null, "e": 9129, "s": 9053, "text": "...and this is out-of-the-box functionality! Some easy criticisms would be:" }, { "code": null, "e": 9513, "s": 9129, "text": "N-grams aren’t leveraged at all, neither in the query nor the results. For example machine learning is treated as {machine, learning} rather than {machine learning, machine, learning}.It is not impossible for stop-words to appear in the results.Out-of-sample misspellings aren’t dealt with at all.Plurals and possessive forms of nouns and all verb conjugations are listed separately." }, { "code": null, "e": 9698, "s": 9513, "text": "N-grams aren’t leveraged at all, neither in the query nor the results. For example machine learning is treated as {machine, learning} rather than {machine learning, machine, learning}." }, { "code": null, "e": 9760, "s": 9698, "text": "It is not impossible for stop-words to appear in the results." }, { "code": null, "e": 9813, "s": 9760, "text": "Out-of-sample misspellings aren’t dealt with at all." }, { "code": null, "e": 9900, "s": 9813, "text": "Plurals and possessive forms of nouns and all verb conjugations are listed separately." }, { "code": null, "e": 10079, "s": 9900, "text": "I’m not going to address the latter two points here, but dealing with them is fairly trivial. For example, misspellings can be dealt with in at least two ways, for example using:" }, { "code": null, "e": 10245, "s": 10079, "text": "Elasticsearch’s n-gram tokenizer (beware that Elasticsearch’s defines n-grams at the character-level, not to be confused with the data scientist’s term-level n-gram)" }, { "code": null, "e": 10286, "s": 10245, "text": "or using the phonetic tokenizer plug-in." }, { "code": null, "e": 10690, "s": 10286, "text": "In order to deal with n-gram queries (such as machine learning) I have created a field in my Elasticsearch database containing pre-tokenized abstracts, in which I have already identified n-grams. Note that the ‘schema’ for this field can be found here. If you want to know, I process my n-grams by using a look-up table based on n-grams from Wiktionary (but a more data-driven approach would also work)." }, { "code": null, "e": 10883, "s": 10690, "text": "Although I haven’t implemented this myself, similar preprocessing can be done for plurals/possessives/conjugations, effectively by replacing all non-simple forms of terms by their simple form." }, { "code": null, "e": 11029, "s": 10883, "text": "Finally, to avoid the potential embarrassment of returning stop-words I have taken to generating them from the data using my make_query function:" }, { "code": null, "e": 11388, "s": 11029, "text": "and of but yes with however[‘however’, ‘but’, ‘not’, ‘answer’, ‘with’, ‘the’, ‘is’, ‘of’, ‘to’, ‘a’, ‘in’, ‘and’, ‘that’, ‘no’, ‘this’, ‘we’, ‘only’, ‘for’, ‘are’, ‘be’, ‘it’, ‘can’, ‘by’, ‘on’, ‘an’, ‘question’, ‘also’, ‘have’, ‘has’, ‘which’, ‘there’, ‘as’, ‘or’, ‘such’, ‘if’, ‘whether’, ‘does’, ‘more’, ‘from’, ‘one’, ‘been’, ‘these’, ‘show’, ‘at’, ‘do’]" }, { "code": null, "e": 11442, "s": 11388, "text": "and I simply exclude these from the returned results." }, { "code": null, "e": 11652, "s": 11442, "text": "Check out the keyword factory in action over on the arXlive website, featuring n-grams and stopword removal. You can make your own Flask app using the clio_keywordsfunction from the clio-litepackage. Have fun!" }, { "code": null, "e": 12433, "s": 11652, "text": "Consider a very technical dataset such as that from arXiv, the world’s largest repository of physical, quantitative and computational science pre-prints. Assuming that you’re not polymath savant, what would be your strategy for finding the latest novel research on arXiv, relating to Big Data and Security? If you were to make that exact search on arXiv, you’d find yourself with a decent set of results, but the problem is that when you were searching for Big Data, you might not have realised that you also wanted to include tangentially-related terms such as {hadoop, spark, cloud-computing} in your query. What if there was some big breakthrough in Cloud Computing and Security that you’ve been missing out on? (TL;DR this is the same search with a ‘contextual’ search engine)" }, { "code": null, "e": 12564, "s": 12433, "text": "I’m going to break this problem down into two pieces, and solve it by using some Elasticsearch functionality wrapped up in Python:" }, { "code": null, "e": 12635, "s": 12564, "text": "Firstly, how do you make a decent search query without being a genius?" }, { "code": null, "e": 12672, "s": 12635, "text": "Secondly, how can we define novelty?" }, { "code": null, "e": 13316, "s": 12672, "text": "Back to the problem of making a decent search query. What approaches might a genius take? Well, they could go down the route of ‘keyword expansion’, for example by considering all of {hadoop, spark, cloud-computing} in addition to big data, and all of {attack, encryption, authentication} in addition to security. Potentially this is a promising way to go, and we’ve already written the tools to help do this in the previous blog. However, the main problem with the ‘keyword expansion’ approach is that it lacks context. A natural extension to this would instead be ‘document expansion’, and thankfully Elasticsearch has this feature built-in." }, { "code": null, "e": 14025, "s": 13316, "text": "Well, to be honest with you, Elasticsearch’s more-like-this query is really ‘keyword expansion++’ rather than a ‘document expansion’, as you might imagine it in a vector space. Under the hood, representative terms are selected from input documents (according to a highly configurable procedure) which you would like to ‘expand’ from. The advantage to doing this over a pure ‘keyword expansion’ approach, is that terms which co-occur with all input terms are deemed to be more important than those which only co-occur with a subset of the input terms. The upshot is that the expanded set of keywords which are used to seed the ‘document expansion’ can be assumed to have a high degree of contextual relevance." }, { "code": null, "e": 14048, "s": 14025, "text": "So here’s my strategy:" }, { "code": null, "e": 14170, "s": 14048, "text": "Make a vanilla query to Elasticsearch and retrieve the 10–25 most relevant documents. These will be our ‘seed’ documents." }, { "code": null, "e": 14235, "s": 14170, "text": "Follow up with a more-like-this query, using the seed documents." }, { "code": null, "e": 14346, "s": 14235, "text": "and that strategy looks a little like this (in practice it’s a bit more code, so it actually looks like this):" }, { "code": null, "e": 15392, "s": 14346, "text": "# Make the initial vanilla queryr = simple_query(url, old_query, event, fields)data, docs = extract_docs(r)# Formulate the MLT querytotal = data['hits']['total']max_doc_freq = int(max_doc_frac*total)min_doc_freq = int(min_doc_freq*total)mlt_query = {\"query\": {\"more_like_this\": {\"fields\": fields, # the fields to consider \"like\": docs, # the seed docs \"min_term_freq\": min_term_freq, \"max_query_terms\": max_query_terms, \"min_doc_freq\": min_doc_freq, \"max_doc_freq\": max_doc_freq, \"boost_terms\": 1., \"minimum_should_match\": minimum_should_match, \"include\": True # include the seed docs } } }# Make the MLT queryquery = json.dumps(dict(**query, **mlt_query))params = {\"search_type\":\"dfs_query_then_fetch\"}r_mlt = requests.post(url, data=query, headers=headers, params=params)# Extract the results_data, docs = extract_docs(r_mlt)" }, { "code": null, "e": 15550, "s": 15392, "text": "Note, that I serve this functionality via AWS API Gateway in a Lambda function. The code for deploying the above function can also be found in the same repo." }, { "code": null, "e": 15682, "s": 15550, "text": "Novelty doesn’t have a particularly narrow definition, and I admit that my definition for this blog is going to be fairly narrow..." }, { "code": null, "e": 15944, "s": 15682, "text": "Novelty generally could be defined as any (and more) of {new, original, unusual}, and my definition is going to straddle the {original, unusual} concept. More formally (but not very formally), I’m asking the following question of each document in Elasticsearch:" }, { "code": null, "e": 15996, "s": 15944, "text": "How different are you from your nearest neighbours?" }, { "code": null, "e": 16346, "s": 15996, "text": "Just to clarify the logic here: if the total sample of documents is unbalanced, then a document belonging to a minority topic will be very different from the average document. We can avoid this by only comparing to nearest neighbours. And how better to get the nearest neighbours, than by using more-like-this all over again (the full code is here):" }, { "code": null, "e": 17200, "s": 16346, "text": "mlt_query = { \"query\": { \"more_like_this\": { \"fields\": fields, # field you want to query \"like\": [{'_id':doc_id, # the doc we're analysing '_index':index}], \"min_term_freq\": 1, \"max_query_terms\": max_query_terms, \"min_doc_freq\": 1, \"max_doc_freq\": max_doc_freq, \"boost_terms\": 1., \"minimum_should_match\": minimum_should_match, \"include\": True } }, \"size\":1000, # the number of nearest neighbours \"_source\":[\"_score\"]}# Make the search and normalise the scoresr = es.search(index=index, body=mlt_query)scores = [h['_score']/r['hits']['max_score'] for h in r['hits']['hits']]# Calculate novelty as the distance to a low percentiledelta = np.percentile(scores, similar_perc)return 1 - delta" }, { "code": null, "e": 17623, "s": 17200, "text": "Naturally, any decent a definition of novelty which encapsulates the concept of being “unusual” should capture bad data, since one would hope that these would be unusual. I found that by applying the above novelty scorer to arXiv data I was able to root out a whole bunch of bad data, such as plagiarised and ‘comment’ articles. I went on to assign these a novelty of zero, but I’m sure you can work out your own approach!" }, { "code": null, "e": 17852, "s": 17623, "text": "One downside of this novelty-scoring method is that it’s relatively slow to implement (it must be calculated on a document-by-document basis), and for this reason I preprocessed all of the documents in my Elasticsearch database." } ]
How to add jQuery code to HTML file ? - GeeksforGeeks
22 Jul, 2021 In this article, we will see how to add jQuery code to HTML file. You can easily add jQuery to HTML by using several methods, like adding jQuery from CDN or directly downloading jQuery files and including them into your projects. Several methods are discussed in this article. Methods: Download and include the jQuery file Including jQuery from CDN. Approach1: Download and include the jQuery file Follow the information below to include jQuery in your HTML file. Use this link to download the jQuery file from the official JQuery website. ( download compressed or uncompressed files according to your need). After downloading, just move the downloaded file into the HTML file to which you want to add your jQuery. Finally, use the below syntax to include jQuery in the HTML file. i.e add jQuery file name between script tags. Use this link to download the jQuery file from the official JQuery website. ( download compressed or uncompressed files according to your need). After downloading, just move the downloaded file into the HTML file to which you want to add your jQuery. Finally, use the below syntax to include jQuery in the HTML file. i.e add jQuery file name between script tags. <script type="text/javascript" src="jquery-3.5.1.min.js"> </script> Example: HTML <!DOCTYPE html> <html> <head> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("button").click(function () { $("h2").html("Complete Portal for Geeks</b>"); }); }); </script> </head> <body> <center> <h2>GeeksforGeeks</h2> <button>Click here</button> </center> </body> </html> Output: Approach 2: Follow the step below to include Jquery in the HTML file. In this, you just need to add the link below with the script tag to your HTML file, whether CDN provided by Google or Microsoft. Google CDN <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script> Microsoft CDN <script src=’http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js’></script> In this, you just need to add the link below with the script tag to your HTML file, whether CDN provided by Google or Microsoft. Google CDN <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script> Microsoft CDN <script src=’http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js’></script> Google CDN <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script> <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script> Microsoft CDN <script src=’http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js’></script> <script src=’http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js’></script> Example: HTML <html> <head> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <title>Added Jquery into HTML</title> <style> h1 { color: green; } </style> </head> <body> <center> <h1>Welcome to GeeksforGeeks</h1> <button id="trigger">Click me</button> <h3 id="demo"></h3> <script type="text/javascript"> $(document).ready(function () { $("#trigger").click(function () { $("#demo").html("Complete portal for Geeks"); }); }); </script> </center> </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. HTML-Questions jQuery-Methods jQuery-Questions Picked HTML JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 26303, "s": 26272, "text": " \n22 Jul, 2021\n" }, { "code": null, "e": 26580, "s": 26303, "text": "In this article, we will see how to add jQuery code to HTML file. You can easily add jQuery to HTML by using several methods, like adding jQuery from CDN or directly downloading jQuery files and including them into your projects. Several methods are discussed in this article." }, { "code": null, "e": 26589, "s": 26580, "text": "Methods:" }, { "code": null, "e": 26626, "s": 26589, "text": "Download and include the jQuery file" }, { "code": null, "e": 26653, "s": 26626, "text": "Including jQuery from CDN." }, { "code": null, "e": 26701, "s": 26653, "text": "Approach1: Download and include the jQuery file" }, { "code": null, "e": 26767, "s": 26701, "text": "Follow the information below to include jQuery in your HTML file." }, { "code": null, "e": 27132, "s": 26767, "text": "\nUse this link to download the jQuery file from the official JQuery website. ( download compressed or uncompressed files according to your need).\nAfter downloading, just move the downloaded file into the HTML file to which you want to add your jQuery.\nFinally, use the below syntax to include jQuery in the HTML file. i.e add jQuery file name between script tags.\n" }, { "code": null, "e": 27277, "s": 27132, "text": "Use this link to download the jQuery file from the official JQuery website. ( download compressed or uncompressed files according to your need)." }, { "code": null, "e": 27383, "s": 27277, "text": "After downloading, just move the downloaded file into the HTML file to which you want to add your jQuery." }, { "code": null, "e": 27495, "s": 27383, "text": "Finally, use the below syntax to include jQuery in the HTML file. i.e add jQuery file name between script tags." }, { "code": null, "e": 27563, "s": 27495, "text": "<script type=\"text/javascript\" src=\"jquery-3.5.1.min.js\"> </script>" }, { "code": null, "e": 27574, "s": 27565, "text": "Example:" }, { "code": null, "e": 27579, "s": 27574, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html> \n <head> \n <script src= \n\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> \n </script> \n <script> \n $(document).ready(function () { \n $(\"button\").click(function () { \n $(\"h2\").html(\"Complete Portal for Geeks</b>\"); \n }); \n }); \n </script> \n </head> \n <body> \n <center> \n <h2>GeeksforGeeks</h2> \n <button>Click here</button> \n </center> \n </body> \n</html> \n\n\n\n\n\n", "e": 28065, "s": 27589, "text": null }, { "code": null, "e": 28073, "s": 28065, "text": "Output:" }, { "code": null, "e": 28143, "s": 28073, "text": "Approach 2: Follow the step below to include Jquery in the HTML file." }, { "code": null, "e": 28471, "s": 28143, "text": "\nIn this, you just need to add the link below with the script tag to your HTML file, whether CDN provided by Google or Microsoft.\n\nGoogle CDN\n<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>\n\nMicrosoft CDN\n<script src=’http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js’></script>\n\n\n\n" }, { "code": null, "e": 28797, "s": 28471, "text": "In this, you just need to add the link below with the script tag to your HTML file, whether CDN provided by Google or Microsoft.\n\nGoogle CDN\n<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>\n\nMicrosoft CDN\n<script src=’http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js’></script>\n\n\n" }, { "code": null, "e": 28898, "s": 28797, "text": "Google CDN\n<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>\n" }, { "code": null, "e": 28987, "s": 28898, "text": "<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>" }, { "code": null, "e": 29080, "s": 28987, "text": "Microsoft CDN\n<script src=’http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js’></script>\n" }, { "code": null, "e": 29158, "s": 29080, "text": "<script src=’http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js’></script>" }, { "code": null, "e": 29167, "s": 29158, "text": "Example:" }, { "code": null, "e": 29172, "s": 29167, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<html> \n <head> \n <script src= \n\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> \n </script> \n <title>Added Jquery into HTML</title> \n \n <style> \n h1 { \n color: green; \n } \n </style> \n </head> \n \n <body> \n <center> \n <h1>Welcome to GeeksforGeeks</h1> \n <button id=\"trigger\">Click me</button> \n <h3 id=\"demo\"></h3> \n \n <script type=\"text/javascript\"> \n $(document).ready(function () { \n $(\"#trigger\").click(function () { \n $(\"#demo\").html(\"Complete portal for Geeks\"); \n }); \n }); \n </script> \n </center> \n </body> \n</html>\n\n\n\n\n\n", "e": 29850, "s": 29182, "text": null }, { "code": null, "e": 29858, "s": 29850, "text": "Output:" }, { "code": null, "e": 29995, "s": 29858, "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": 30012, "s": 29995, "text": "\nHTML-Questions\n" }, { "code": null, "e": 30029, "s": 30012, "text": "\njQuery-Methods\n" }, { "code": null, "e": 30048, "s": 30029, "text": "\njQuery-Questions\n" }, { "code": null, "e": 30057, "s": 30048, "text": "\nPicked\n" }, { "code": null, "e": 30064, "s": 30057, "text": "\nHTML\n" }, { "code": null, "e": 30073, "s": 30064, "text": "\nJQuery\n" }, { "code": null, "e": 30092, "s": 30073, "text": "\nWeb Technologies\n" }, { "code": null, "e": 30297, "s": 30092, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 30321, "s": 30297, "text": "REST API (Introduction)" }, { "code": null, "e": 30362, "s": 30321, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 30399, "s": 30362, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30428, "s": 30399, "text": "Form validation using jQuery" }, { "code": null, "e": 30448, "s": 30428, "text": "Angular File Upload" }, { "code": null, "e": 30494, "s": 30448, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 30523, "s": 30494, "text": "Form validation using jQuery" }, { "code": null, "e": 30586, "s": 30523, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 30663, "s": 30586, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
Structuring Python Programs - GeeksforGeeks
02 Mar, 2020 In this article, you would come to know about proper structuring and formatting your python programs. Python Statements In general, the interpreter reads and executes the statements line by line i.e sequentially. Though, there are some statements that can alter this behavior like conditional statements. Mostly, python statements are written in such a format that one statement is only written in a single line. The interpreter considers the ‘new line character’ as the terminator of one instruction. But, writing multiple statements per line is also possible that you can find below.Examples: # Example 1 print('Welcome to Geeks for Geeks') Welcome to Geeks for Geeks # Example 2 x = [1, 2, 3, 4] # x[1:3] means that start from the index # 1 and go upto the index 2print(x[1:3]) """ In the above mentioned format, the first index is included, but the last index is notincluded.""" [2, 3] Multiple Statements per Line We can also write multiple statements per line, but it is not a good practice as it reduces the readability of the code. Try to avoid writing multiple statements in a single line. But, still you can write multiple lines by terminating one statement with the help of ‘;’. ‘;’ is used as the terminator of one statement in this case. For Example, consider the following code. # Example a = 10; b = 20; c = b + a print(a); print(b); print(c) 10 20 30 Line Continuation to avoid left and right scrollingSome statements may become very long and may force you to scroll the screen left and right frequently. You can fit your code in such a way that you do not have to scroll here and there. Python allows you to write a single statement in multiple lines, also known as line continuation. Line continuation enhances readability as well. # Bad Practice as width of this code is too much. #code x = 10 y = 20 z = 30 no_of_teachers = x no_of_male_students = y no_of_female_students = z if (no_of_teachers == 10 and no_of_female_students == 30 and no_of_male_students == 20 and (x + y) == 30): print('The course is valid') # This could be done instead: if (no_of_teachers == 10 and no_of_female_students == 30 and no_of_male_students == 20 and x + y == 30): print('The course is valid') Types of Line ContinuationIn general, there are two types of line continuation Implicit Line ContinuationThis is the most straightforward technique in writing a statement that spans multiple lines.Any statement containing opening parentheses (‘(‘), brackets (‘[‘), or curly braces (‘{‘) is presumed to be incomplete until all matching parentheses, square brackets, and curly braces have been encountered. Until then, the statement can be implicitly continued across lines without raising an error.Examples:# Example 1 # The following code is valida = [ [1, 2, 3], [3, 4, 5], [5, 6, 7] ] print(a)Output:[[1, 2, 3], [3, 4, 5], [5, 6, 7]] # Example 2# The following code is also valid person_1 = 18person_2 = 20person_3 = 12 if ( person_1 >= 18 and person_2 >= 18 and person_3 < 18 ): print('2 Persons should have ID Cards')Output:2 Persons should have ID Cards # Example 1 # The following code is valida = [ [1, 2, 3], [3, 4, 5], [5, 6, 7] ] print(a) [[1, 2, 3], [3, 4, 5], [5, 6, 7]] # Example 2# The following code is also valid person_1 = 18person_2 = 20person_3 = 12 if ( person_1 >= 18 and person_2 >= 18 and person_3 < 18 ): print('2 Persons should have ID Cards') 2 Persons should have ID Cards Explicit Line ContinuationExplicit Line joining is used mostly when implicit line joining is not applicable. In this method, you have to use a character that helps the interpreter to understand that the particular statement is spanning more than one lines. Backslash (\) is used to indicate that a statement spans more than one line. The point is to be noted that ” must be the last character in that line, even white-space is not allowed.See the following example for clarification# Example x = \ 1 + 2 \ + 5 + 6 \ + 10 print(x)Output:24 Comments in PythonWriting comments in the code are very important and they help in code readability and also tell more about the code. It helps you to write details against a statement or a chunk of code. Interpreter ignores the comments and does not count them in commands. In this section, we’ll learn how to write comments in Python. Symbols used for writing comments include Hash (#) or Triple Double Quotation marks(“””). Hash is used in writing single line comments that do not span multiple lines. Triple Quotation Marks are used to write multiple line comments. Three triple quotation marks to start the comment and again three quotation marks to end the comment.Consider the following examples:# Example 1 ####### This example will print Hello World ####### print('Hello World') # This is a comment# Example 2 """ This example will demonstrate multiple comments """ """ The following a variable contains the string 'How old are you?'"""a = 'How old are you?' """ The following statement prints what's inside the variable a """print(a)Note Do note that Hash (#) inside a string does not make it a comment. Consider the following example for demonstration.# Example """ The following statement prints the string stored in the variable """ a = 'This is # not a comment #'print(a) # Prints the string stored in aWhite spacesThe most common whitespace characters are the following:CharacterASCII CodeLiteral ExpressionSpace32 (0x20)‘ ‘tab9 (0x9)‘\t’newline10 (0xA)‘\n’* You can always refer to ASCII Table by clicking here.Whitespace is mostly ignored, and mostly not required, by the Python interpreter. When it is clear where one token ends and the next one starts, whitespace can be omitted. This is usually the case when special non-alphanumeric characters are involved.Examples:# Example 1 # This is correct but whitespace can improve readability a = 1-2 # Better way is a = 1 - 2 print(a)# Example 2 # This is correct# Whitespace here can improve readability.x = 10flag =(x == 10)and(x<12)print(flag) """ Readable form could be as followsx = 10flag = (x == 10) and (x < 12)print(flag)""" # Try the more readable code yourselfWhitespaces are necessary in separating the keywords from the variables or other keywords. Consider the following example.# Example x = [1, 2, 3]y = 2 """ Following is incorrect, and will generate syntax errora = yin x""" # Corrected version is written asa = y in xprint(a)Whitespaces as IndentationPython’s syntax is quite easy, but still you have to take some care in writing the code. Indentation is used in writing python codes. Whitespaces before a statement have significant role and are used in indentation. Whitespace before a statement can have a different meaning. Let’s try an example.# Example print('foo') # Correct print('foo') # This will generate an error # The error would be somewhat 'unexpected indent'Leading whitespaces are used to determine the grouping of the statements like in loops or control structures etc.Example:# Example x = 10 while(x != 0): if(x > 5): # Line 1 print('x > 5') # Line 2 else: # Line 3 print('x < 5') # Line 4 x -= 2 # Line 5 """Lines 1, 3, 5 are on same levelLine 2 will only be executed if if condition becomes true.Line 4 will only be executed if if condition becomes false."""Output:x > 5 x > 5 x > 5 x < 5 x < 5 My Personal Notes arrow_drop_upSave # Example x = \ 1 + 2 \ + 5 + 6 \ + 10 print(x) 24 Comments in PythonWriting comments in the code are very important and they help in code readability and also tell more about the code. It helps you to write details against a statement or a chunk of code. Interpreter ignores the comments and does not count them in commands. In this section, we’ll learn how to write comments in Python. Symbols used for writing comments include Hash (#) or Triple Double Quotation marks(“””). Hash is used in writing single line comments that do not span multiple lines. Triple Quotation Marks are used to write multiple line comments. Three triple quotation marks to start the comment and again three quotation marks to end the comment.Consider the following examples: # Example 1 ####### This example will print Hello World ####### print('Hello World') # This is a comment # Example 2 """ This example will demonstrate multiple comments """ """ The following a variable contains the string 'How old are you?'"""a = 'How old are you?' """ The following statement prints what's inside the variable a """print(a) Note Do note that Hash (#) inside a string does not make it a comment. Consider the following example for demonstration. # Example """ The following statement prints the string stored in the variable """ a = 'This is # not a comment #'print(a) # Prints the string stored in a White spacesThe most common whitespace characters are the following: * You can always refer to ASCII Table by clicking here.Whitespace is mostly ignored, and mostly not required, by the Python interpreter. When it is clear where one token ends and the next one starts, whitespace can be omitted. This is usually the case when special non-alphanumeric characters are involved.Examples: # Example 1 # This is correct but whitespace can improve readability a = 1-2 # Better way is a = 1 - 2 print(a) # Example 2 # This is correct# Whitespace here can improve readability.x = 10flag =(x == 10)and(x<12)print(flag) """ Readable form could be as followsx = 10flag = (x == 10) and (x < 12)print(flag)""" # Try the more readable code yourself Whitespaces are necessary in separating the keywords from the variables or other keywords. Consider the following example. # Example x = [1, 2, 3]y = 2 """ Following is incorrect, and will generate syntax errora = yin x""" # Corrected version is written asa = y in xprint(a) Whitespaces as IndentationPython’s syntax is quite easy, but still you have to take some care in writing the code. Indentation is used in writing python codes. Whitespaces before a statement have significant role and are used in indentation. Whitespace before a statement can have a different meaning. Let’s try an example. # Example print('foo') # Correct print('foo') # This will generate an error # The error would be somewhat 'unexpected indent' Leading whitespaces are used to determine the grouping of the statements like in loops or control structures etc.Example: # Example x = 10 while(x != 0): if(x > 5): # Line 1 print('x > 5') # Line 2 else: # Line 3 print('x < 5') # Line 4 x -= 2 # Line 5 """Lines 1, 3, 5 are on same levelLine 2 will only be executed if if condition becomes true.Line 4 will only be executed if if condition becomes false.""" x > 5 x > 5 x > 5 x < 5 x < 5 harlinseritt Picked python-basics Python School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 25782, "s": 25754, "text": "\n02 Mar, 2020" }, { "code": null, "e": 25884, "s": 25782, "text": "In this article, you would come to know about proper structuring and formatting your python programs." }, { "code": null, "e": 26388, "s": 25884, "text": "Python Statements In general, the interpreter reads and executes the statements line by line i.e sequentially. Though, there are some statements that can alter this behavior like conditional statements. Mostly, python statements are written in such a format that one statement is only written in a single line. The interpreter considers the ‘new line character’ as the terminator of one instruction. But, writing multiple statements per line is also possible that you can find below.Examples:" }, { "code": "# Example 1 print('Welcome to Geeks for Geeks') ", "e": 26438, "s": 26388, "text": null }, { "code": null, "e": 26466, "s": 26438, "text": "Welcome to Geeks for Geeks\n" }, { "code": "# Example 2 x = [1, 2, 3, 4] # x[1:3] means that start from the index # 1 and go upto the index 2print(x[1:3]) \"\"\" In the above mentioned format, the first index is included, but the last index is notincluded.\"\"\"", "e": 26684, "s": 26466, "text": null }, { "code": null, "e": 26692, "s": 26684, "text": "[2, 3]\n" }, { "code": null, "e": 27102, "s": 26692, "text": "Multiple Statements per Line We can also write multiple statements per line, but it is not a good practice as it reduces the readability of the code. Try to avoid writing multiple statements in a single line. But, still you can write multiple lines by terminating one statement with the help of ‘;’. ‘;’ is used as the terminator of one statement in this case. For Example, consider the following code." }, { "code": "# Example a = 10; b = 20; c = b + a print(a); print(b); print(c)", "e": 27169, "s": 27102, "text": null }, { "code": null, "e": 27179, "s": 27169, "text": "10\n20\n30\n" }, { "code": null, "e": 27562, "s": 27179, "text": "Line Continuation to avoid left and right scrollingSome statements may become very long and may force you to scroll the screen left and right frequently. You can fit your code in such a way that you do not have to scroll here and there. Python allows you to write a single statement in multiple lines, also known as line continuation. Line continuation enhances readability as well." }, { "code": null, "e": 28028, "s": 27562, "text": "# Bad Practice as width of this code is too much.\n \n#code\nx = 10\ny = 20\nz = 30\nno_of_teachers = x\nno_of_male_students = y\nno_of_female_students = z\n \nif (no_of_teachers == 10 and no_of_female_students == 30 and no_of_male_students == 20 and (x + y) == 30):\n print('The course is valid')\n \n# This could be done instead:\n \nif (no_of_teachers == 10 and no_of_female_students == 30\n and no_of_male_students == 20 and x + y == 30):\n print('The course is valid')" }, { "code": null, "e": 28107, "s": 28028, "text": "Types of Line ContinuationIn general, there are two types of line continuation" }, { "code": null, "e": 28915, "s": 28107, "text": "Implicit Line ContinuationThis is the most straightforward technique in writing a statement that spans multiple lines.Any statement containing opening parentheses (‘(‘), brackets (‘[‘), or curly braces (‘{‘) is presumed to be incomplete until all matching parentheses, square brackets, and curly braces have been encountered. Until then, the statement can be implicitly continued across lines without raising an error.Examples:# Example 1 # The following code is valida = [ [1, 2, 3], [3, 4, 5], [5, 6, 7] ] print(a)Output:[[1, 2, 3], [3, 4, 5], [5, 6, 7]]\n# Example 2# The following code is also valid person_1 = 18person_2 = 20person_3 = 12 if ( person_1 >= 18 and person_2 >= 18 and person_3 < 18 ): print('2 Persons should have ID Cards')Output:2 Persons should have ID Cards\n" }, { "code": "# Example 1 # The following code is valida = [ [1, 2, 3], [3, 4, 5], [5, 6, 7] ] print(a)", "e": 29019, "s": 28915, "text": null }, { "code": null, "e": 29054, "s": 29019, "text": "[[1, 2, 3], [3, 4, 5], [5, 6, 7]]\n" }, { "code": "# Example 2# The following code is also valid person_1 = 18person_2 = 20person_3 = 12 if ( person_1 >= 18 and person_2 >= 18 and person_3 < 18 ): print('2 Persons should have ID Cards')", "e": 29253, "s": 29054, "text": null }, { "code": null, "e": 29285, "s": 29253, "text": "2 Persons should have ID Cards\n" }, { "code": null, "e": 33254, "s": 29285, "text": "Explicit Line ContinuationExplicit Line joining is used mostly when implicit line joining is not applicable. In this method, you have to use a character that helps the interpreter to understand that the particular statement is spanning more than one lines. Backslash (\\) is used to indicate that a statement spans more than one line. The point is to be noted that ” must be the last character in that line, even white-space is not allowed.See the following example for clarification# Example x = \\ 1 + 2 \\ + 5 + 6 \\ + 10 print(x)Output:24\nComments in PythonWriting comments in the code are very important and they help in code readability and also tell more about the code. It helps you to write details against a statement or a chunk of code. Interpreter ignores the comments and does not count them in commands. In this section, we’ll learn how to write comments in Python. Symbols used for writing comments include Hash (#) or Triple Double Quotation marks(“””). Hash is used in writing single line comments that do not span multiple lines. Triple Quotation Marks are used to write multiple line comments. Three triple quotation marks to start the comment and again three quotation marks to end the comment.Consider the following examples:# Example 1 ####### This example will print Hello World ####### print('Hello World') # This is a comment# Example 2 \"\"\" This example will demonstrate multiple comments \"\"\" \"\"\" The following a variable contains the string 'How old are you?'\"\"\"a = 'How old are you?' \"\"\" The following statement prints what's inside the variable a \"\"\"print(a)Note Do note that Hash (#) inside a string does not make it a comment. Consider the following example for demonstration.# Example \"\"\" The following statement prints the string stored in the variable \"\"\" a = 'This is # not a comment #'print(a) # Prints the string stored in aWhite spacesThe most common whitespace characters are the following:CharacterASCII CodeLiteral ExpressionSpace32 (0x20)‘ ‘tab9 (0x9)‘\\t’newline10 (0xA)‘\\n’* You can always refer to ASCII Table by clicking here.Whitespace is mostly ignored, and mostly not required, by the Python interpreter. When it is clear where one token ends and the next one starts, whitespace can be omitted. This is usually the case when special non-alphanumeric characters are involved.Examples:# Example 1 # This is correct but whitespace can improve readability a = 1-2 # Better way is a = 1 - 2 print(a)# Example 2 # This is correct# Whitespace here can improve readability.x = 10flag =(x == 10)and(x<12)print(flag) \"\"\" Readable form could be as followsx = 10flag = (x == 10) and (x < 12)print(flag)\"\"\" # Try the more readable code yourselfWhitespaces are necessary in separating the keywords from the variables or other keywords. Consider the following example.# Example x = [1, 2, 3]y = 2 \"\"\" Following is incorrect, and will generate syntax errora = yin x\"\"\" # Corrected version is written asa = y in xprint(a)Whitespaces as IndentationPython’s syntax is quite easy, but still you have to take some care in writing the code. Indentation is used in writing python codes. Whitespaces before a statement have significant role and are used in indentation. Whitespace before a statement can have a different meaning. Let’s try an example.# Example print('foo') # Correct print('foo') # This will generate an error # The error would be somewhat 'unexpected indent'Leading whitespaces are used to determine the grouping of the statements like in loops or control structures etc.Example:# Example x = 10 while(x != 0): if(x > 5): # Line 1 print('x > 5') # Line 2 else: # Line 3 print('x < 5') # Line 4 x -= 2 # Line 5 \"\"\"Lines 1, 3, 5 are on same levelLine 2 will only be executed if if condition becomes true.Line 4 will only be executed if if condition becomes false.\"\"\"Output:x > 5\nx > 5\nx > 5\nx < 5\nx < 5\nMy Personal Notes\narrow_drop_upSave" }, { "code": "# Example x = \\ 1 + 2 \\ + 5 + 6 \\ + 10 print(x)", "e": 33313, "s": 33254, "text": null }, { "code": null, "e": 33317, "s": 33313, "text": "24\n" }, { "code": null, "e": 34028, "s": 33317, "text": "Comments in PythonWriting comments in the code are very important and they help in code readability and also tell more about the code. It helps you to write details against a statement or a chunk of code. Interpreter ignores the comments and does not count them in commands. In this section, we’ll learn how to write comments in Python. Symbols used for writing comments include Hash (#) or Triple Double Quotation marks(“””). Hash is used in writing single line comments that do not span multiple lines. Triple Quotation Marks are used to write multiple line comments. Three triple quotation marks to start the comment and again three quotation marks to end the comment.Consider the following examples:" }, { "code": "# Example 1 ####### This example will print Hello World ####### print('Hello World') # This is a comment", "e": 34135, "s": 34028, "text": null }, { "code": "# Example 2 \"\"\" This example will demonstrate multiple comments \"\"\" \"\"\" The following a variable contains the string 'How old are you?'\"\"\"a = 'How old are you?' \"\"\" The following statement prints what's inside the variable a \"\"\"print(a)", "e": 34389, "s": 34135, "text": null }, { "code": null, "e": 34510, "s": 34389, "text": "Note Do note that Hash (#) inside a string does not make it a comment. Consider the following example for demonstration." }, { "code": "# Example \"\"\" The following statement prints the string stored in the variable \"\"\" a = 'This is # not a comment #'print(a) # Prints the string stored in a", "e": 34670, "s": 34510, "text": null }, { "code": null, "e": 34739, "s": 34670, "text": "White spacesThe most common whitespace characters are the following:" }, { "code": null, "e": 35055, "s": 34739, "text": "* You can always refer to ASCII Table by clicking here.Whitespace is mostly ignored, and mostly not required, by the Python interpreter. When it is clear where one token ends and the next one starts, whitespace can be omitted. This is usually the case when special non-alphanumeric characters are involved.Examples:" }, { "code": "# Example 1 # This is correct but whitespace can improve readability a = 1-2 # Better way is a = 1 - 2 print(a)", "e": 35171, "s": 35055, "text": null }, { "code": "# Example 2 # This is correct# Whitespace here can improve readability.x = 10flag =(x == 10)and(x<12)print(flag) \"\"\" Readable form could be as followsx = 10flag = (x == 10) and (x < 12)print(flag)\"\"\" # Try the more readable code yourself", "e": 35412, "s": 35171, "text": null }, { "code": null, "e": 35535, "s": 35412, "text": "Whitespaces are necessary in separating the keywords from the variables or other keywords. Consider the following example." }, { "code": "# Example x = [1, 2, 3]y = 2 \"\"\" Following is incorrect, and will generate syntax errora = yin x\"\"\" # Corrected version is written asa = y in xprint(a)", "e": 35690, "s": 35535, "text": null }, { "code": null, "e": 36021, "s": 35690, "text": "Whitespaces as IndentationPython’s syntax is quite easy, but still you have to take some care in writing the code. Indentation is used in writing python codes. Whitespaces before a statement have significant role and are used in indentation. Whitespace before a statement can have a different meaning. Let’s try an example." }, { "code": "# Example print('foo') # Correct print('foo') # This will generate an error # The error would be somewhat 'unexpected indent'", "e": 36153, "s": 36021, "text": null }, { "code": null, "e": 36275, "s": 36153, "text": "Leading whitespaces are used to determine the grouping of the statements like in loops or control structures etc.Example:" }, { "code": "# Example x = 10 while(x != 0): if(x > 5): # Line 1 print('x > 5') # Line 2 else: # Line 3 print('x < 5') # Line 4 x -= 2 # Line 5 \"\"\"Lines 1, 3, 5 are on same levelLine 2 will only be executed if if condition becomes true.Line 4 will only be executed if if condition becomes false.\"\"\"", "e": 36584, "s": 36275, "text": null }, { "code": null, "e": 36615, "s": 36584, "text": "x > 5\nx > 5\nx > 5\nx < 5\nx < 5\n" }, { "code": null, "e": 36628, "s": 36615, "text": "harlinseritt" }, { "code": null, "e": 36635, "s": 36628, "text": "Picked" }, { "code": null, "e": 36649, "s": 36635, "text": "python-basics" }, { "code": null, "e": 36656, "s": 36649, "text": "Python" }, { "code": null, "e": 36675, "s": 36656, "text": "School Programming" }, { "code": null, "e": 36773, "s": 36675, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36791, "s": 36773, "text": "Python Dictionary" }, { "code": null, "e": 36826, "s": 36791, "text": "Read a file line by line in Python" }, { "code": null, "e": 36858, "s": 36826, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 36900, "s": 36858, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 36926, "s": 36900, "text": "Python String | replace()" }, { "code": null, "e": 36944, "s": 36926, "text": "Python Dictionary" }, { "code": null, "e": 36960, "s": 36944, "text": "Arrays in C/C++" }, { "code": null, "e": 36979, "s": 36960, "text": "Inheritance in C++" }, { "code": null, "e": 37004, "s": 36979, "text": "Reverse a string in Java" } ]
How can multiple plots be plotted in same figure using matplotlib and Python?
Matplotlib is a popular Python package that is used for data visualization. Visualizing data is a key step since it helps understand what is going on in the data without actually looking at the numbers and performing complicated computations. It helps in communicating the quantitative insights to the audience effectively. Matplotlib is used to create 2 dimensional plots with the data. It comes with an object oriented API that helps in embedding the plots in Python applications. Matplotlib can be used with IPython shells, Jupyter notebook, Spyder IDE and so on. It is written in Python. It is created using Numpy, which is the Numerical Python package in Python. Python can be installed on Windows using the below command − pip install matplotlib The dependencies of Matplotlib are − Python ( greater than or equal to version 3.4) NumPy Setuptools Pyparsing Libpng Pytz Free type Six Cycler Dateutil Sometimes, it may be required to understand two different data sets, one with respect to other. This is when such multiple plots can be plotted. Let us understand how Matplotlib can be used to plot multiple plots − import numpy as np import matplotlib.pyplot as plt x1_val = np.linspace(0.0, 6.0) x2_val = np.linspace(0.0, 3.0) y1_val = np.cos(2.3 * np.pi * x1_val) * np.exp(−x1_val) y2_val = np.cos(2.4 * np.pi * x2_val) fig, (ax1, ax2) = plt.subplots(2, 1) fig.suptitle('Two plots') ax1.plot(x1_val, y1_val ,'o−') ax1.set_ylabel('Plot 1') ax2.plot(x2_val, y2_val, '.−') ax2.set_xlabel('x-axis') ax2.set_ylabel('Plot 2') plt.show() The required packages are imported and its alias is defined for ease of use. The required packages are imported and its alias is defined for ease of use. The data is created using the ‘Numpy’ library for two different data sets. The data is created using the ‘Numpy’ library for two different data sets. An empty figure is created using the ‘figure’ function. An empty figure is created using the ‘figure’ function. The data is plotted using the ‘plot’ function. The data is plotted using the ‘plot’ function. The set_xlabel, set_ylabel and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis and title. The set_xlabel, set_ylabel and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis and title. It is shown on the console using the ‘show’ function. It is shown on the console using the ‘show’ function.
[ { "code": null, "e": 1138, "s": 1062, "text": "Matplotlib is a popular Python package that is used for data visualization." }, { "code": null, "e": 1305, "s": 1138, "text": "Visualizing data is a key step since it helps understand what is going on in the data without actually looking at the numbers and performing complicated computations." }, { "code": null, "e": 1386, "s": 1305, "text": "It helps in communicating the quantitative insights to the audience effectively." }, { "code": null, "e": 1629, "s": 1386, "text": "Matplotlib is used to create 2 dimensional plots with the data. It comes with an object oriented API that helps in embedding the plots in Python applications. Matplotlib can be used with IPython shells, Jupyter notebook, Spyder IDE and so on." }, { "code": null, "e": 1730, "s": 1629, "text": "It is written in Python. It is created using Numpy, which is the Numerical Python package in Python." }, { "code": null, "e": 1791, "s": 1730, "text": "Python can be installed on Windows using the below command −" }, { "code": null, "e": 1814, "s": 1791, "text": "pip install matplotlib" }, { "code": null, "e": 1851, "s": 1814, "text": "The dependencies of Matplotlib are −" }, { "code": null, "e": 1967, "s": 1851, "text": "Python ( greater than or equal to version 3.4)\nNumPy\nSetuptools\nPyparsing\nLibpng\nPytz\nFree type\nSix\nCycler\nDateutil" }, { "code": null, "e": 2112, "s": 1967, "text": "Sometimes, it may be required to understand two different data sets, one with respect to other. This is when such multiple plots can be plotted." }, { "code": null, "e": 2182, "s": 2112, "text": "Let us understand how Matplotlib can be used to plot multiple plots −" }, { "code": null, "e": 2600, "s": 2182, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nx1_val = np.linspace(0.0, 6.0)\nx2_val = np.linspace(0.0, 3.0)\ny1_val = np.cos(2.3 * np.pi * x1_val) * np.exp(−x1_val)\ny2_val = np.cos(2.4 * np.pi * x2_val)\nfig, (ax1, ax2) = plt.subplots(2, 1)\nfig.suptitle('Two plots')\nax1.plot(x1_val, y1_val ,'o−')\nax1.set_ylabel('Plot 1')\nax2.plot(x2_val, y2_val, '.−')\nax2.set_xlabel('x-axis')\nax2.set_ylabel('Plot 2')\nplt.show()" }, { "code": null, "e": 2677, "s": 2600, "text": "The required packages are imported and its alias is defined for ease of use." }, { "code": null, "e": 2754, "s": 2677, "text": "The required packages are imported and its alias is defined for ease of use." }, { "code": null, "e": 2829, "s": 2754, "text": "The data is created using the ‘Numpy’ library for two different data sets." }, { "code": null, "e": 2904, "s": 2829, "text": "The data is created using the ‘Numpy’ library for two different data sets." }, { "code": null, "e": 2960, "s": 2904, "text": "An empty figure is created using the ‘figure’ function." }, { "code": null, "e": 3016, "s": 2960, "text": "An empty figure is created using the ‘figure’ function." }, { "code": null, "e": 3063, "s": 3016, "text": "The data is plotted using the ‘plot’ function." }, { "code": null, "e": 3110, "s": 3063, "text": "The data is plotted using the ‘plot’ function." }, { "code": null, "e": 3222, "s": 3110, "text": "The set_xlabel, set_ylabel and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis and title." }, { "code": null, "e": 3334, "s": 3222, "text": "The set_xlabel, set_ylabel and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis and title." }, { "code": null, "e": 3388, "s": 3334, "text": "It is shown on the console using the ‘show’ function." }, { "code": null, "e": 3442, "s": 3388, "text": "It is shown on the console using the ‘show’ function." } ]
How can we show a popup menu when the user right-clicks on a JComboBox in Java?
A JComboBox is a subclass of JComponent class that displays a drop-down list and gives users options that we can select one and only one item at a time. A JComboBox can be editable or read-only. A getSelectedItem() method can be used to get the selected or entered item from a combo box. We can invoke a popup menu from a JComboxBox when the user right-clicks on it by implementing a MouseListener interface and need to override the mouseReleased() method. The method isPopupTrigger() of MouseEvent class can be used to show a popup menu. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JComboBoxPopupTest extends JFrame { private JComboBox jcb; private JPopupMenu jpm; private JMenuItem mItem1, mItem2; public JComboBoxPopupTest() { setTitle("JComboBoxPopup Test"); setLayout(new FlowLayout()); jcb = new JComboBox(new String[] {"Item 1", "Item 2", "Item 3"}); jpm = new JPopupMenu(); mItem1 = new JMenuItem("Popup Item 1"); mItem2 = new JMenuItem("Popup Item 2"); jpm.add(mItem1); jpm.add(mItem2); ((JButton)jcb.getComponent(0)).addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent me) { if (me.isPopupTrigger()) { jpm.show(jcb, me.getX(), me.getY()); } } }); add(jcb); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) throws Exception { new JComboBoxPopupTest(); } }
[ { "code": null, "e": 1601, "s": 1062, "text": "A JComboBox is a subclass of JComponent class that displays a drop-down list and gives users options that we can select one and only one item at a time. A JComboBox can be editable or read-only. A getSelectedItem()\nmethod can be used to get the selected or entered item from a combo box. We can invoke a popup menu from a JComboxBox when the user right-clicks on it by implementing a MouseListener interface and need to override the mouseReleased() method. The method isPopupTrigger() of MouseEvent class can be used to show a popup menu." }, { "code": null, "e": 2669, "s": 1601, "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\npublic class JComboBoxPopupTest extends JFrame {\n private JComboBox jcb;\n private JPopupMenu jpm;\n private JMenuItem mItem1, mItem2;\n public JComboBoxPopupTest() {\n setTitle(\"JComboBoxPopup Test\");\n setLayout(new FlowLayout());\n jcb = new JComboBox(new String[] {\"Item 1\", \"Item 2\", \"Item 3\"});\n jpm = new JPopupMenu();\n mItem1 = new JMenuItem(\"Popup Item 1\");\n mItem2 = new JMenuItem(\"Popup Item 2\"); \n jpm.add(mItem1);\n jpm.add(mItem2);\n ((JButton)jcb.getComponent(0)).addMouseListener(new MouseAdapter() {\n public void mouseReleased(MouseEvent me) {\n if (me.isPopupTrigger()) {\n jpm.show(jcb, me.getX(), me.getY());\n }\n }\n });\n add(jcb);\n setSize(400, 300);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String[] args) throws Exception {\n new JComboBoxPopupTest();\n }\n}" } ]
Difference between Preemptive Priority based and Non-preemptive Priority based CPU scheduling algorithms - GeeksforGeeks
01 Jun, 2021 Prerequisite – CPU Scheduling Priority Scheduling : In priority scheduling, each process has a priority which is an integer value assigned to it. The smallest integer is considered as the highest priority and the largest integer is considered as the lowest priority. The process with the highest priority gets the CPU first. In rare systems, the largest number might be treated as the highest priority also so it all depends on the implementation. If priorities are internally defined then some measurable quantities such as time limits, memory requirements, the number of open files and the ratio of average I/O burst to average CPU burst are used to compute priorities. External priorities are assigned on the basis of factors such as the importance of process, the type and amount of funds been paid for computer use, the department sponsoring of the work, etc. Preemptive and non-preemptive SJF is a priority scheduling where priority is the shortest execution time of job. In this algorithm, low priority processes may never execute. This is called starvation. The solution to this starvation problem is aging. In aging, as time progresses, increase the priority of the process so that the lowest priority process gets converted to the highest priority gradually. Priority Preemptive Scheduling : Sometimes it is important to execute higher priority tasks immediately even when a task is currently being executed. For example, when a phone call is received, the CPU is immediately assigned to this task even if some other application is currently being used. This is because the incoming phone call has a higher priority than other tasks. This is a perfect example of priority preemptive scheduling. If a task with higher priority than the current task being executed arrives then the control of the CPU is taken from the current task and given to the higher priority task. Priority Non-Preemptive Scheduling : Unlike priority preemptive scheduling, even if a task with higher priority does arrive, it has to wait for the current task to release the CPU before it can be executed. It is often used in various hardware procedures such as timers, etc. Priority Preemptive Scheduling : Sometimes it is important to execute higher priority tasks immediately even when a task is currently being executed. For example, when a phone call is received, the CPU is immediately assigned to this task even if some other application is currently being used. This is because the incoming phone call has a higher priority than other tasks. This is a perfect example of priority preemptive scheduling. If a task with higher priority than the current task being executed arrives then the control of the CPU is taken from the current task and given to the higher priority task. Priority Non-Preemptive Scheduling : Unlike priority preemptive scheduling, even if a task with higher priority does arrive, it has to wait for the current task to release the CPU before it can be executed. It is often used in various hardware procedures such as timers, etc. Note: If all the processes arrive at the same time then priority preemptive scheduling and priority non-preemptive scheduling work in the same manner. Now let’s do a comparative study of preemptive priority scheduling and non-preemptive priority scheduling. Example: Let’s try and solve this problem using both algorithms to do a comparative study. 1. Priority Non-preemptive scheduling : The Gantt chart will look like: Average waiting time (AWT), = ((0-0) + (8-1) + (9-2) + (12-3) + (14-4)) / 5 = 33 / 5 = 6.6 Average turnaround time (TAT), = ((8-0) + (9-1) + (12-2) + (14-3) + (20-4)) / 4 = 53 / 5 = 10.6 2. Priority Preemptive scheduling : The Gantt chart will look like: Average waiting time (AWT), = ((5-1) + (1-1) + (2-2) + (12-3) + (14-4)) / 5 = 23/5 = 4.6 Average turnaround time (TAT), = ((12-0) + (2-1) + (5-2) + (14-3) + (20-4)) / 5 = 43 / 5 = 8.6 serjeelranjan Picked Difference Between GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference Between Spark DataFrame and Pandas DataFrame Difference between Internal and External fragmentation Difference between Prim's and Kruskal's algorithm for MST Layers of OSI Model ACID Properties in DBMS Normal Forms in DBMS Types of Operating Systems Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 24802, "s": 24774, "text": "\n01 Jun, 2021" }, { "code": null, "e": 25128, "s": 24802, "text": "Prerequisite – CPU Scheduling Priority Scheduling : In priority scheduling, each process has a priority which is an integer value assigned to it. The smallest integer is considered as the highest priority and the largest integer is considered as the lowest priority. The process with the highest priority gets the CPU first. " }, { "code": null, "e": 25252, "s": 25128, "text": "In rare systems, the largest number might be treated as the highest priority also so it all depends on the implementation. " }, { "code": null, "e": 25670, "s": 25252, "text": "If priorities are internally defined then some measurable quantities such as time limits, memory requirements, the number of open files and the ratio of average I/O burst to average CPU burst are used to compute priorities. External priorities are assigned on the basis of factors such as the importance of process, the type and amount of funds been paid for computer use, the department sponsoring of the work, etc. " }, { "code": null, "e": 25872, "s": 25670, "text": "Preemptive and non-preemptive SJF is a priority scheduling where priority is the shortest execution time of job. In this algorithm, low priority processes may never execute. This is called starvation. " }, { "code": null, "e": 26076, "s": 25872, "text": "The solution to this starvation problem is aging. In aging, as time progresses, increase the priority of the process so that the lowest priority process gets converted to the highest priority gradually. " }, { "code": null, "e": 26966, "s": 26078, "text": "Priority Preemptive Scheduling : Sometimes it is important to execute higher priority tasks immediately even when a task is currently being executed. For example, when a phone call is received, the CPU is immediately assigned to this task even if some other application is currently being used. This is because the incoming phone call has a higher priority than other tasks. This is a perfect example of priority preemptive scheduling. If a task with higher priority than the current task being executed arrives then the control of the CPU is taken from the current task and given to the higher priority task. Priority Non-Preemptive Scheduling : Unlike priority preemptive scheduling, even if a task with higher priority does arrive, it has to wait for the current task to release the CPU before it can be executed. It is often used in various hardware procedures such as timers, etc. " }, { "code": null, "e": 27578, "s": 26966, "text": "Priority Preemptive Scheduling : Sometimes it is important to execute higher priority tasks immediately even when a task is currently being executed. For example, when a phone call is received, the CPU is immediately assigned to this task even if some other application is currently being used. This is because the incoming phone call has a higher priority than other tasks. This is a perfect example of priority preemptive scheduling. If a task with higher priority than the current task being executed arrives then the control of the CPU is taken from the current task and given to the higher priority task. " }, { "code": null, "e": 27857, "s": 27580, "text": "Priority Non-Preemptive Scheduling : Unlike priority preemptive scheduling, even if a task with higher priority does arrive, it has to wait for the current task to release the CPU before it can be executed. It is often used in various hardware procedures such as timers, etc. " }, { "code": null, "e": 28009, "s": 27857, "text": "Note: If all the processes arrive at the same time then priority preemptive scheduling and priority non-preemptive scheduling work in the same manner. " }, { "code": null, "e": 28117, "s": 28009, "text": "Now let’s do a comparative study of preemptive priority scheduling and non-preemptive priority scheduling. " }, { "code": null, "e": 28129, "s": 28119, "text": "Example: " }, { "code": null, "e": 28214, "s": 28131, "text": "Let’s try and solve this problem using both algorithms to do a comparative study. " }, { "code": null, "e": 28287, "s": 28214, "text": "1. Priority Non-preemptive scheduling : The Gantt chart will look like: " }, { "code": null, "e": 28318, "s": 28289, "text": "Average waiting time (AWT), " }, { "code": null, "e": 28384, "s": 28318, "text": "= ((0-0) + (8-1) + (9-2) + (12-3) + (14-4)) / 5 \n= 33 / 5 \n= 6.6 " }, { "code": null, "e": 28417, "s": 28384, "text": "Average turnaround time (TAT), " }, { "code": null, "e": 28485, "s": 28417, "text": "= ((8-0) + (9-1) + (12-2) + (14-3) + (20-4)) / 4 \n= 53 / 5 \n= 10.6 " }, { "code": null, "e": 28554, "s": 28485, "text": "2. Priority Preemptive scheduling : The Gantt chart will look like: " }, { "code": null, "e": 28585, "s": 28556, "text": "Average waiting time (AWT), " }, { "code": null, "e": 28649, "s": 28585, "text": "= ((5-1) + (1-1) + (2-2) + (12-3) + (14-4)) / 5 \n= 23/5 \n= 4.6 " }, { "code": null, "e": 28681, "s": 28649, "text": "Average turnaround time (TAT), " }, { "code": null, "e": 28748, "s": 28681, "text": "= ((12-0) + (2-1) + (5-2) + (14-3) + (20-4)) / 5 \n= 43 / 5 \n= 8.6 " }, { "code": null, "e": 28762, "s": 28748, "text": "serjeelranjan" }, { "code": null, "e": 28769, "s": 28762, "text": "Picked" }, { "code": null, "e": 28788, "s": 28769, "text": "Difference Between" }, { "code": null, "e": 28796, "s": 28788, "text": "GATE CS" }, { "code": null, "e": 28814, "s": 28796, "text": "Operating Systems" }, { "code": null, "e": 28832, "s": 28814, "text": "Operating Systems" }, { "code": null, "e": 28930, "s": 28832, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28939, "s": 28930, "text": "Comments" }, { "code": null, "e": 28952, "s": 28939, "text": "Old Comments" }, { "code": null, "e": 29013, "s": 28952, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29081, "s": 29013, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 29137, "s": 29081, "text": "Difference Between Spark DataFrame and Pandas DataFrame" }, { "code": null, "e": 29192, "s": 29137, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 29250, "s": 29192, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 29270, "s": 29250, "text": "Layers of OSI Model" }, { "code": null, "e": 29294, "s": 29270, "text": "ACID Properties in DBMS" }, { "code": null, "e": 29315, "s": 29294, "text": "Normal Forms in DBMS" }, { "code": null, "e": 29342, "s": 29315, "text": "Types of Operating Systems" } ]
Introduction to the Probabilistic Data Structure - GeeksforGeeks
28 Apr, 2020 Based on different properties such as speed, cost, and ease of use(as a developer), etc. the below information represents different ways of storing stuff in the computer machine. Tape------->HDD------->SSD------->Memory It means memory is faster than SSD than HDD than Tape and the same goes with cost and ease of use as a developer. Storage and its limitations Now let’s discuss the scenario with the context of the developer. If we want to store some stuff in memory then we may use Set(of course one can use other in-memory data structure as well like Arrays, List, Map, etc) and if we want to store some data on SSD then we may use something like a relational database or elastic search. Similarly for a hard drive(HDD) we can use Hadoop(HDFS).Now suppose we want to store data in memory using deterministic in-memory data structure but the problem is the amount of memory we have on servers in terms of GB or TB for memory is less than SSD and SSD might have memory lesser than a hard drive(HDD), and also one should remember than deterministic data structure is good and popular to use but these data structures are not efficient in term of consuming memory. HDD<-------SSD<-------Memory //Storage per node Now the question is how can we do more stuff at the memory side, with less amount of memory consumption? HDD-------SSD-------Memory ^ | How can we do more stuff here? Thus this is the place where probabilistic data structure comes into the picture which can do almost the same job as a deterministic data structure but with a lot less memory. Deterministic Vs Probabilistic Data Structure Being an IT professional, we might have come across many deterministic data structures such as Array, List, Set, HashTable, HashSet, etc. These in-memory data structures are the most typical data structures on which various operations such as insert, find and delete could be performed with specific key values. As a result of operation what we get is the deterministic(accurate) result. But this is not in the case of a probabilistic data structure, Here the result of operation could be probabilistic(may not give you a definite answer, always results in approximate), and hence named as a probabilistic data structure. We will see and prove this in the coming sections. But for now let’s dig into more detail of its definition, types, and uses. How does it work?Probabilistic data structure works with large data set, where we want to perform some operations such as finding some unique items in given data set or it could be finding the most frequent item or if some items exist or not. To do such an operation probabilistic data structure uses more and more hash functions to randomize and represent a set of data. The more number of hash function the more accurate result. Things to rememberA deterministic data structure can also perform all the operations that a probabilistic data structure does but only with low data sets. As stated earlier, if the data set is too big and couldn’t fit into the memory, then the deterministic data structure fails and is simply not feasible. Also in case of a streaming application where data is required to be processed in one go and perform incremental updates, it is very difficult to manage with the deterministic data structure. Use Cases Analyze big data setStatistical analysisMining tera-bytes of data sets, etc Analyze big data set Statistical analysis Mining tera-bytes of data sets, etc Popular probabilistic data structures Bloom filterCount-Min SketchHyperLogLog Bloom filter Count-Min Sketch HyperLogLog Advanced Computer Subject Advanced Data Structure Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Copying Files to and from Docker Containers Fuzzy Logic | Introduction Basics of API Testing Using Postman Principal Component Analysis with Python Markov Decision Process AVL Tree | Set 1 (Insertion) Trie | (Insert and Search) Red-Black Tree | Set 1 (Introduction) LRU Cache Implementation Agents in Artificial Intelligence
[ { "code": null, "e": 24404, "s": 24376, "text": "\n28 Apr, 2020" }, { "code": null, "e": 24583, "s": 24404, "text": "Based on different properties such as speed, cost, and ease of use(as a developer), etc. the below information represents different ways of storing stuff in the computer machine." }, { "code": null, "e": 24625, "s": 24583, "text": "Tape------->HDD------->SSD------->Memory\n" }, { "code": null, "e": 24739, "s": 24625, "text": "It means memory is faster than SSD than HDD than Tape and the same goes with cost and ease of use as a developer." }, { "code": null, "e": 24767, "s": 24739, "text": "Storage and its limitations" }, { "code": null, "e": 25570, "s": 24767, "text": "Now let’s discuss the scenario with the context of the developer. If we want to store some stuff in memory then we may use Set(of course one can use other in-memory data structure as well like Arrays, List, Map, etc) and if we want to store some data on SSD then we may use something like a relational database or elastic search. Similarly for a hard drive(HDD) we can use Hadoop(HDFS).Now suppose we want to store data in memory using deterministic in-memory data structure but the problem is the amount of memory we have on servers in terms of GB or TB for memory is less than SSD and SSD might have memory lesser than a hard drive(HDD), and also one should remember than deterministic data structure is good and popular to use but these data structures are not efficient in term of consuming memory." }, { "code": null, "e": 25621, "s": 25570, "text": "HDD<-------SSD<-------Memory //Storage per node\n" }, { "code": null, "e": 25726, "s": 25621, "text": "Now the question is how can we do more stuff at the memory side, with less amount of memory consumption?" }, { "code": null, "e": 25848, "s": 25726, "text": "HDD-------SSD-------Memory\n ^\n |\n How can we do more stuff here? \n" }, { "code": null, "e": 26024, "s": 25848, "text": "Thus this is the place where probabilistic data structure comes into the picture which can do almost the same job as a deterministic data structure but with a lot less memory." }, { "code": null, "e": 26070, "s": 26024, "text": "Deterministic Vs Probabilistic Data Structure" }, { "code": null, "e": 26818, "s": 26070, "text": "Being an IT professional, we might have come across many deterministic data structures such as Array, List, Set, HashTable, HashSet, etc. These in-memory data structures are the most typical data structures on which various operations such as insert, find and delete could be performed with specific key values. As a result of operation what we get is the deterministic(accurate) result. But this is not in the case of a probabilistic data structure, Here the result of operation could be probabilistic(may not give you a definite answer, always results in approximate), and hence named as a probabilistic data structure. We will see and prove this in the coming sections. But for now let’s dig into more detail of its definition, types, and uses." }, { "code": null, "e": 27190, "s": 26818, "text": "How does it work?Probabilistic data structure works with large data set, where we want to perform some operations such as finding some unique items in given data set or it could be finding the most frequent item or if some items exist or not. To do such an operation probabilistic data structure uses more and more hash functions to randomize and represent a set of data." }, { "code": null, "e": 27251, "s": 27190, "text": "The more number of hash function the more accurate result. \n" }, { "code": null, "e": 27750, "s": 27251, "text": "Things to rememberA deterministic data structure can also perform all the operations that a probabilistic data structure does but only with low data sets. As stated earlier, if the data set is too big and couldn’t fit into the memory, then the deterministic data structure fails and is simply not feasible. Also in case of a streaming application where data is required to be processed in one go and perform incremental updates, it is very difficult to manage with the deterministic data structure." }, { "code": null, "e": 27760, "s": 27750, "text": "Use Cases" }, { "code": null, "e": 27836, "s": 27760, "text": "Analyze big data setStatistical analysisMining tera-bytes of data sets, etc" }, { "code": null, "e": 27857, "s": 27836, "text": "Analyze big data set" }, { "code": null, "e": 27878, "s": 27857, "text": "Statistical analysis" }, { "code": null, "e": 27914, "s": 27878, "text": "Mining tera-bytes of data sets, etc" }, { "code": null, "e": 27952, "s": 27914, "text": "Popular probabilistic data structures" }, { "code": null, "e": 27992, "s": 27952, "text": "Bloom filterCount-Min SketchHyperLogLog" }, { "code": null, "e": 28005, "s": 27992, "text": "Bloom filter" }, { "code": null, "e": 28022, "s": 28005, "text": "Count-Min Sketch" }, { "code": null, "e": 28034, "s": 28022, "text": "HyperLogLog" }, { "code": null, "e": 28060, "s": 28034, "text": "Advanced Computer Subject" }, { "code": null, "e": 28084, "s": 28060, "text": "Advanced Data Structure" }, { "code": null, "e": 28182, "s": 28084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28226, "s": 28182, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 28253, "s": 28226, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 28289, "s": 28253, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 28330, "s": 28289, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 28354, "s": 28330, "text": "Markov Decision Process" }, { "code": null, "e": 28383, "s": 28354, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 28410, "s": 28383, "text": "Trie | (Insert and Search)" }, { "code": null, "e": 28448, "s": 28410, "text": "Red-Black Tree | Set 1 (Introduction)" }, { "code": null, "e": 28473, "s": 28448, "text": "LRU Cache Implementation" } ]
PHP - Function eregi()
int eregi(string pattern, string string, [array regs]); The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive. Eregi() can be particularly useful when checking the validity of strings, such as passwords. The optional input parameter regs contains an array of all matched expressions that were grouped by parentheses in the regular expression. It returns true if the pattern is validated, and false otherwise. Following is the piece of code, copy and paste this code into a file and verify the result. <?php $password = "abc"; if (! eregi ("[[:alnum:]]{8,10}", $password)) { print "Invalid password! Passwords must be from 8 - 10 chars"; } else { print "Valid password"; } ?> This will produce the following result − Invalid password! Passwords must be from 8 - 10 chars 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": 2814, "s": 2757, "text": "int eregi(string pattern, string string, [array regs]);\n" }, { "code": null, "e": 3046, "s": 2814, "text": "The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive. Eregi() can be particularly useful when checking the validity of strings, such as passwords." }, { "code": null, "e": 3185, "s": 3046, "text": "The optional input parameter regs contains an array of all matched expressions that were grouped by parentheses in the regular expression." }, { "code": null, "e": 3251, "s": 3185, "text": "It returns true if the pattern is validated, and false otherwise." }, { "code": null, "e": 3343, "s": 3251, "text": "Following is the piece of code, copy and paste this code into a file and verify the result." }, { "code": null, "e": 3548, "s": 3343, "text": "<?php\n $password = \"abc\";\n \n if (! eregi (\"[[:alnum:]]{8,10}\", $password))\n {\n print \"Invalid password! Passwords must be from 8 - 10 chars\";\n } else {\n print \"Valid password\";\n }\n?>" }, { "code": null, "e": 3589, "s": 3548, "text": "This will produce the following result −" }, { "code": null, "e": 3644, "s": 3589, "text": "Invalid password! Passwords must be from 8 - 10 chars\n" }, { "code": null, "e": 3677, "s": 3644, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 3693, "s": 3677, "text": " Malhar Lathkar" }, { "code": null, "e": 3726, "s": 3693, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 3737, "s": 3726, "text": " Syed Raza" }, { "code": null, "e": 3772, "s": 3737, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3789, "s": 3772, "text": " Frahaan Hussain" }, { "code": null, "e": 3822, "s": 3789, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 3837, "s": 3822, "text": " Nivedita Jain" }, { "code": null, "e": 3872, "s": 3837, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 3884, "s": 3872, "text": " Azaz Patel" }, { "code": null, "e": 3919, "s": 3884, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3947, "s": 3919, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 3954, "s": 3947, "text": " Print" }, { "code": null, "e": 3965, "s": 3954, "text": " Add Notes" } ]
Node.js - REPL Terminal
REPL stands for Read Eval Print Loop and it represents a computer environment like a Windows console or Unix/Linux shell where a command is entered and the system responds with an output in an interactive mode. Node.js or Node comes bundled with a REPL environment. It performs the following tasks − Read − Reads user's input, parses the input into JavaScript data-structure, and stores in memory. Read − Reads user's input, parses the input into JavaScript data-structure, and stores in memory. Eval − Takes and evaluates the data structure. Eval − Takes and evaluates the data structure. Print − Prints the result. Print − Prints the result. Loop − Loops the above command until the user presses ctrl-c twice. Loop − Loops the above command until the user presses ctrl-c twice. The REPL feature of Node is very useful in experimenting with Node.js codes and to debug JavaScript codes. To simplify your learning, we have set up an easy to use Node.js REPL environment online, where you can practice Node.js syntax − Launch Node.js REPL Terminal REPL can be started by simply running node on shell/console without any arguments as follows. $ node You will see the REPL Command prompt > where you can type any Node.js command − $ node > Let's try a simple mathematics at the Node.js REPL command prompt − $ node > 1 + 3 4 > 1 + ( 2 * 3 ) - 4 3 > You can make use variables to store values and print later like any conventional script. If var keyword is not used, then the value is stored in the variable and printed. Whereas if var keyword is used, then the value is stored but not printed. You can print variables using console.log(). $ node > x = 10 10 > var y = 10 undefined > x + y 20 > console.log("Hello World") Hello World undefined Node REPL supports multiline expression similar to JavaScript. Let's check the following do-while loop in action − $ node > var x = 0 undefined > do { ... x++; ... console.log("x: " + x); ... } while ( x < 5 ); x: 1 x: 2 x: 3 x: 4 x: 5 undefined > ... comes automatically when you press Enter after the opening bracket. Node automatically checks the continuity of expressions. You can use underscore (_) to get the last result − $ node > var x = 10 undefined > var y = 20 undefined > x + y 30 > var sum = _ undefined > console.log(sum) 30 undefined > ctrl + c − terminate the current command. ctrl + c − terminate the current command. ctrl + c twice − terminate the Node REPL. ctrl + c twice − terminate the Node REPL. ctrl + d − terminate the Node REPL. ctrl + d − terminate the Node REPL. Up/Down Keys − see command history and modify previous commands. Up/Down Keys − see command history and modify previous commands. tab Keys − list of current commands. tab Keys − list of current commands. .help − list of all commands. .help − list of all commands. .break − exit from multiline expression. .break − exit from multiline expression. .clear − exit from multiline expression. .clear − exit from multiline expression. .save filename − save the current Node REPL session to a file. .save filename − save the current Node REPL session to a file. .load filename − load file content in current Node REPL session. .load filename − load file content in current Node REPL session. As mentioned above, you will need to use ctrl-c twice to come out of Node.js REPL. $ node > (^C again to quit) > 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": 2318, "s": 2018, "text": "REPL stands for Read Eval Print Loop and it represents a computer environment like a Windows console or Unix/Linux shell where a command is entered and the system responds with an output in an interactive mode. Node.js or Node comes bundled with a REPL environment. It performs the following tasks −" }, { "code": null, "e": 2416, "s": 2318, "text": "Read − Reads user's input, parses the input into JavaScript data-structure, and stores in memory." }, { "code": null, "e": 2514, "s": 2416, "text": "Read − Reads user's input, parses the input into JavaScript data-structure, and stores in memory." }, { "code": null, "e": 2561, "s": 2514, "text": "Eval − Takes and evaluates the data structure." }, { "code": null, "e": 2608, "s": 2561, "text": "Eval − Takes and evaluates the data structure." }, { "code": null, "e": 2635, "s": 2608, "text": "Print − Prints the result." }, { "code": null, "e": 2662, "s": 2635, "text": "Print − Prints the result." }, { "code": null, "e": 2730, "s": 2662, "text": "Loop − Loops the above command until the user presses ctrl-c twice." }, { "code": null, "e": 2798, "s": 2730, "text": "Loop − Loops the above command until the user presses ctrl-c twice." }, { "code": null, "e": 2905, "s": 2798, "text": "The REPL feature of Node is very useful in experimenting with Node.js codes and to debug JavaScript codes." }, { "code": null, "e": 3065, "s": 2905, "text": "To simplify your learning, we have set up an easy to use Node.js REPL environment online, where you can practice Node.js syntax − Launch Node.js REPL Terminal " }, { "code": null, "e": 3159, "s": 3065, "text": "REPL can be started by simply running node on shell/console without any arguments as follows." }, { "code": null, "e": 3167, "s": 3159, "text": "$ node\n" }, { "code": null, "e": 3247, "s": 3167, "text": "You will see the REPL Command prompt > where you can type any Node.js command −" }, { "code": null, "e": 3257, "s": 3247, "text": "$ node\n>\n" }, { "code": null, "e": 3325, "s": 3257, "text": "Let's try a simple mathematics at the Node.js REPL command prompt −" }, { "code": null, "e": 3367, "s": 3325, "text": "$ node\n> 1 + 3\n4\n> 1 + ( 2 * 3 ) - 4\n3\n>\n" }, { "code": null, "e": 3657, "s": 3367, "text": "You can make use variables to store values and print later like any conventional script. If var keyword is not used, then the value is stored in the variable and printed. Whereas if var keyword is used, then the value is stored but not printed. You can print variables using console.log()." }, { "code": null, "e": 3762, "s": 3657, "text": "$ node\n> x = 10\n10\n> var y = 10\nundefined\n> x + y\n20\n> console.log(\"Hello World\")\nHello World\nundefined\n" }, { "code": null, "e": 3877, "s": 3762, "text": "Node REPL supports multiline expression similar to JavaScript. Let's check the following do-while loop in action −" }, { "code": null, "e": 4021, "s": 3877, "text": "$ node\n> var x = 0\nundefined\n> do {\n ... x++;\n ... console.log(\"x: \" + x);\n ... } \nwhile ( x < 5 );\nx: 1\nx: 2\nx: 3\nx: 4\nx: 5\nundefined\n>\n" }, { "code": null, "e": 4150, "s": 4021, "text": "... comes automatically when you press Enter after the opening bracket. Node automatically checks the continuity of expressions." }, { "code": null, "e": 4202, "s": 4150, "text": "You can use underscore (_) to get the last result −" }, { "code": null, "e": 4325, "s": 4202, "text": "$ node\n> var x = 10\nundefined\n> var y = 20\nundefined\n> x + y\n30\n> var sum = _\nundefined\n> console.log(sum)\n30\nundefined\n>\n" }, { "code": null, "e": 4367, "s": 4325, "text": "ctrl + c − terminate the current command." }, { "code": null, "e": 4409, "s": 4367, "text": "ctrl + c − terminate the current command." }, { "code": null, "e": 4451, "s": 4409, "text": "ctrl + c twice − terminate the Node REPL." }, { "code": null, "e": 4493, "s": 4451, "text": "ctrl + c twice − terminate the Node REPL." }, { "code": null, "e": 4529, "s": 4493, "text": "ctrl + d − terminate the Node REPL." }, { "code": null, "e": 4565, "s": 4529, "text": "ctrl + d − terminate the Node REPL." }, { "code": null, "e": 4630, "s": 4565, "text": "Up/Down Keys − see command history and modify previous commands." }, { "code": null, "e": 4695, "s": 4630, "text": "Up/Down Keys − see command history and modify previous commands." }, { "code": null, "e": 4732, "s": 4695, "text": "tab Keys − list of current commands." }, { "code": null, "e": 4769, "s": 4732, "text": "tab Keys − list of current commands." }, { "code": null, "e": 4799, "s": 4769, "text": ".help − list of all commands." }, { "code": null, "e": 4829, "s": 4799, "text": ".help − list of all commands." }, { "code": null, "e": 4870, "s": 4829, "text": ".break − exit from multiline expression." }, { "code": null, "e": 4911, "s": 4870, "text": ".break − exit from multiline expression." }, { "code": null, "e": 4952, "s": 4911, "text": ".clear − exit from multiline expression." }, { "code": null, "e": 4993, "s": 4952, "text": ".clear − exit from multiline expression." }, { "code": null, "e": 5056, "s": 4993, "text": ".save filename − save the current Node REPL session to a file." }, { "code": null, "e": 5119, "s": 5056, "text": ".save filename − save the current Node REPL session to a file." }, { "code": null, "e": 5184, "s": 5119, "text": ".load filename − load file content in current Node REPL session." }, { "code": null, "e": 5249, "s": 5184, "text": ".load filename − load file content in current Node REPL session." }, { "code": null, "e": 5332, "s": 5249, "text": "As mentioned above, you will need to use ctrl-c twice to come out of Node.js REPL." }, { "code": null, "e": 5363, "s": 5332, "text": "$ node\n>\n(^C again to quit)\n>\n" }, { "code": null, "e": 5398, "s": 5363, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5426, "s": 5398, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5460, "s": 5426, "text": "\n 88 Lectures \n 17 hours \n" }, { "code": null, "e": 5488, "s": 5460, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5523, "s": 5488, "text": "\n 32 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5538, "s": 5523, "text": " Richard Wells" }, { "code": null, "e": 5569, "s": 5538, "text": "\n 8 Lectures \n 33 mins\n" }, { "code": null, "e": 5583, "s": 5569, "text": " Anant Rungta" }, { "code": null, "e": 5617, "s": 5583, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5637, "s": 5617, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 5670, "s": 5637, "text": "\n 97 Lectures \n 6 hours \n" }, { "code": null, "e": 5690, "s": 5670, "text": " Skillbakerystudios" }, { "code": null, "e": 5697, "s": 5690, "text": " Print" }, { "code": null, "e": 5708, "s": 5697, "text": " Add Notes" } ]
Java ResultSet insertRow() method with example
When we execute certain SQL queries (SELECT query in general) they return tabular data. The java.sql.ResultSet interface represents such tabular data returned by the SQL statements. i.e. the ResultSet object holds the tabular data returned by the methods that execute the statements which quires the database (executeQuery() method of the Statement interface in general). The ResultSet object has a cursor/pointer which points to the current row. Initially this cursor is positioned before first row. The insertRow() method of the ResultSet interface inserts the contents of the row into the ResultSet object (and into the table as well). rs.moveToInsertRow(); rs.updateInt("ID", id); rs.updateString("First_Name", "Ishant"); rs.updateString("Last_Name", "Sharma"); rs.updateDate("Date_Of_Birth", new Date(904694400000L)); rs.updateString("Place_Of_Birth", "Delhi"); rs.updateString("Country", "India"); rs.insertRow(); To insert a record into a ResultSet using the insertRow() method − Create the ResultSet object as − Create the ResultSet object as − Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); The moveToInsertRow() method of the ResultSet interface navigates the cursor to the position where you need to insert the next record. Therefore, move the cursor to the appropriate position to insert a row using this method. The moveToInsertRow() method of the ResultSet interface navigates the cursor to the position where you need to insert the next record. Therefore, move the cursor to the appropriate position to insert a row using this method. The updateXXX() methods of the ResultSet interface allows you to insert/update values in to the ResultSet object add values to the new row using these methods for example if you need to insert an integer value at 1st column and, String value at 2nd column you can do so using the updateInt() and updateString() methods as − The updateXXX() methods of the ResultSet interface allows you to insert/update values in to the ResultSet object add values to the new row using these methods for example if you need to insert an integer value at 1st column and, String value at 2nd column you can do so using the updateInt() and updateString() methods as − rs.updateInt(1, integerValue); rs.updateString(2, "stringValue"); Finally, insert the row into the table and the ResultSet using the insertRow() method. Finally, insert the row into the table and the ResultSet using the insertRow() method. rs.insertRow(); Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below − CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) ); Now, we will insert 7 records in MyPlayers table using INSERT statements − insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England'); Following example retrieves the contents of the MyPlayers table as a ResultSet object and, inserts a new record into it, as well as the table, using the insertRow() method. import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ResultSet_insertRow { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating the Statement Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); //Query to retrieve records String query = "Select * from MyPlayers"; //Executing the query ResultSet rs = stmt.executeQuery(query); rs.last(); int id = rs.getInt("ID")+1; rs.moveToInsertRow(); rs.updateInt("ID", id); rs.updateString("First_Name", "Ishant"); rs.updateString("Last_Name", "Sharma"); rs.updateDate("Date_Of_Birth", new Date(904694400000L)); rs.updateString("Place_Of_Birth", "Delhi"); rs.updateString("Country", "India"); rs.insertRow(); rs.beforeFirst(); System.out.println("Contents of the table after inserting a new row: "); while(rs.next()) { System.out.print("ID: "+rs.getInt("ID")+", "); System.out.print("Name: "+rs.getString("First_Name")+", "); System.out.print("Age: "+rs.getString("Last_Name")+", "); System.out.print("Salary: "+rs.getDate("Date_Of_Birth")+", "); System.out.print("Country: "+rs.getString("Place_Of_Birth")+", "); System.out.print("Address: "+rs.getString("Country")); System.out.println(); } } } Connection established...... Contents of the table after inserting a new row: ID: 1, Name: Shikhar, Age: Dhawan, Salary: 1981-12-05, Country: Delhi, Address: India ID: 2, Name: Jonathan, Age: Trott, Salary: 1981-04-22, Country: CapeTown, Address: SouthAfrica ID: 3, Name: Kumara, Age: Sangakkara, Salary: 1977-10-27, Country: Matale, Address: Srilanka ID: 4, Name: Virat, Age: Kohli, Salary: 1988-11-05, Country: Mumbai, Address: India ID: 5, Name: Rohit, Age: Sharma, Salary: 1987-04-30, Country: Nagpur, Address: India ID: 6, Name: Ravindra, Age: Jadeja, Salary: 1988-12-06, Country: Nagpur, Address: India ID: 7, Name: James, Age: Anderson, Salary: 1982-06-30, Country: Burnley , Address: England ID: 8, Name: Ishant, Age: Sharma, Salary: 1998-09-02, Country: Delhi, Address: India
[ { "code": null, "e": 1150, "s": 1062, "text": "When we execute certain SQL queries (SELECT query in general) they return tabular data." }, { "code": null, "e": 1244, "s": 1150, "text": "The java.sql.ResultSet interface represents such tabular data returned by the SQL statements." }, { "code": null, "e": 1434, "s": 1244, "text": "i.e. the ResultSet object holds the tabular data returned by the methods that execute the statements which quires the database (executeQuery() method of the Statement interface in general)." }, { "code": null, "e": 1563, "s": 1434, "text": "The ResultSet object has a cursor/pointer which points to the current row. Initially this cursor is positioned before first row." }, { "code": null, "e": 1701, "s": 1563, "text": "The insertRow() method of the ResultSet interface inserts the contents of the row into the ResultSet object (and into the table as well)." }, { "code": null, "e": 1982, "s": 1701, "text": "rs.moveToInsertRow();\nrs.updateInt(\"ID\", id);\nrs.updateString(\"First_Name\", \"Ishant\");\nrs.updateString(\"Last_Name\", \"Sharma\");\nrs.updateDate(\"Date_Of_Birth\", new Date(904694400000L));\nrs.updateString(\"Place_Of_Birth\", \"Delhi\");\nrs.updateString(\"Country\", \"India\");\nrs.insertRow();" }, { "code": null, "e": 2049, "s": 1982, "text": "To insert a record into a ResultSet using the insertRow() method −" }, { "code": null, "e": 2082, "s": 2049, "text": "Create the ResultSet object as −" }, { "code": null, "e": 2115, "s": 2082, "text": "Create the ResultSet object as −" }, { "code": null, "e": 2221, "s": 2115, "text": "Statement stmt = con.createStatement(\n ResultSet.TYPE_SCROLL_SENSITIVE,\n ResultSet.CONCUR_UPDATABLE);" }, { "code": null, "e": 2446, "s": 2221, "text": "The moveToInsertRow() method of the ResultSet interface navigates the cursor to the position where you need to insert the next record. Therefore, move the cursor to the appropriate position to insert a row using this method." }, { "code": null, "e": 2671, "s": 2446, "text": "The moveToInsertRow() method of the ResultSet interface navigates the cursor to the position where you need to insert the next record. Therefore, move the cursor to the appropriate position to insert a row using this method." }, { "code": null, "e": 2995, "s": 2671, "text": "The updateXXX() methods of the ResultSet interface allows you to insert/update values in to the ResultSet object add values to the new row using these methods for example if you need to insert an integer value at 1st column and, String value at 2nd column you can do so using the updateInt() and updateString() methods as −" }, { "code": null, "e": 3319, "s": 2995, "text": "The updateXXX() methods of the ResultSet interface allows you to insert/update values in to the ResultSet object add values to the new row using these methods for example if you need to insert an integer value at 1st column and, String value at 2nd column you can do so using the updateInt() and updateString() methods as −" }, { "code": null, "e": 3385, "s": 3319, "text": "rs.updateInt(1, integerValue);\nrs.updateString(2, \"stringValue\");" }, { "code": null, "e": 3472, "s": 3385, "text": "Finally, insert the row into the table and the ResultSet using the insertRow() method." }, { "code": null, "e": 3559, "s": 3472, "text": "Finally, insert the row into the table and the ResultSet using the insertRow() method." }, { "code": null, "e": 3575, "s": 3559, "text": "rs.insertRow();" }, { "code": null, "e": 3675, "s": 3575, "text": "Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below −" }, { "code": null, "e": 3871, "s": 3675, "text": "CREATE TABLE MyPlayers(\n ID INT,\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Date_Of_Birth date,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255),\n PRIMARY KEY (ID)\n );" }, { "code": null, "e": 3946, "s": 3871, "text": "Now, we will insert 7 records in MyPlayers table using INSERT statements −" }, { "code": null, "e": 4608, "s": 3946, "text": "insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\ninsert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\ninsert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\ninsert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\ninsert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');\ninsert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');\ninsert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');" }, { "code": null, "e": 4781, "s": 4608, "text": "Following example retrieves the contents of the MyPlayers table as a ResultSet object and, inserts a new record into it, as well as the table, using the insertRow() method." }, { "code": null, "e": 6624, "s": 4781, "text": "import java.sql.Connection;\nimport java.sql.Date;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class ResultSet_insertRow {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);\n //Query to retrieve records\n String query = \"Select * from MyPlayers\";\n //Executing the query\n ResultSet rs = stmt.executeQuery(query);\n rs.last();\n int id = rs.getInt(\"ID\")+1;\n rs.moveToInsertRow();\n rs.updateInt(\"ID\", id);\n rs.updateString(\"First_Name\", \"Ishant\");\n rs.updateString(\"Last_Name\", \"Sharma\");\n rs.updateDate(\"Date_Of_Birth\", new Date(904694400000L));\n rs.updateString(\"Place_Of_Birth\", \"Delhi\");\n rs.updateString(\"Country\", \"India\");\n rs.insertRow();\n rs.beforeFirst();\n System.out.println(\"Contents of the table after inserting a new row: \");\n while(rs.next()) {\n System.out.print(\"ID: \"+rs.getInt(\"ID\")+\", \");\n System.out.print(\"Name: \"+rs.getString(\"First_Name\")+\", \");\n System.out.print(\"Age: \"+rs.getString(\"Last_Name\")+\", \");\n System.out.print(\"Salary: \"+rs.getDate(\"Date_Of_Birth\")+\", \");\n System.out.print(\"Country: \"+rs.getString(\"Place_Of_Birth\")+\", \");\n System.out.print(\"Address: \"+rs.getString(\"Country\"));\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 7409, "s": 6624, "text": "Connection established......\nContents of the table after inserting a new row:\nID: 1, Name: Shikhar, Age: Dhawan, Salary: 1981-12-05, Country: Delhi, Address: India\nID: 2, Name: Jonathan, Age: Trott, Salary: 1981-04-22, Country: CapeTown, Address: SouthAfrica\nID: 3, Name: Kumara, Age: Sangakkara, Salary: 1977-10-27, Country: Matale, Address: Srilanka\nID: 4, Name: Virat, Age: Kohli, Salary: 1988-11-05, Country: Mumbai, Address: India\nID: 5, Name: Rohit, Age: Sharma, Salary: 1987-04-30, Country: Nagpur, Address: India\nID: 6, Name: Ravindra, Age: Jadeja, Salary: 1988-12-06, Country: Nagpur, Address: India\nID: 7, Name: James, Age: Anderson, Salary: 1982-06-30, Country: Burnley , Address: England\nID: 8, Name: Ishant, Age: Sharma, Salary: 1998-09-02, Country: Delhi, Address: India" } ]
Big Data Analytics - Logistic Regression
Logistic regression is a classification model in which the response variable is categorical. It is an algorithm that comes from statistics and is used for supervised classification problems. In logistic regression we seek to find the vector β of parameters in the following equation that minimize the cost function. logit(pi)=ln(pi1−pi)=β0+β1x1,i+...+βkxk,i The following code demonstrates how to fit a logistic regression model in R. We will use here the spam dataset to demonstrate logistic regression, the same that was used for Naive Bayes. From the predictions results in terms of accuracy, we find that the regression model achieves a 92.5% accuracy in the test set, compared to the 72% achieved by the Naive Bayes classifier. library(ElemStatLearn) head(spam) # Split dataset in training and testing inx = sample(nrow(spam), round(nrow(spam) * 0.8)) train = spam[inx,] test = spam[-inx,] # Fit regression model fit = glm(spam ~ ., data = train, family = binomial()) summary(fit) # Call: # glm(formula = spam ~ ., family = binomial(), data = train) # # Deviance Residuals: # Min 1Q Median 3Q Max # -4.5172 -0.2039 0.0000 0.1111 5.4944 # Coefficients: # Estimate Std. Error z value Pr(>|z|) # (Intercept) -1.511e+00 1.546e-01 -9.772 < 2e-16 *** # A.1 -4.546e-01 2.560e-01 -1.776 0.075720 . # A.2 -1.630e-01 7.731e-02 -2.108 0.035043 * # A.3 1.487e-01 1.261e-01 1.179 0.238591 # A.4 2.055e+00 1.467e+00 1.401 0.161153 # A.5 6.165e-01 1.191e-01 5.177 2.25e-07 *** # A.6 7.156e-01 2.768e-01 2.585 0.009747 ** # A.7 2.606e+00 3.917e-01 6.652 2.88e-11 *** # A.8 6.750e-01 2.284e-01 2.955 0.003127 ** # A.9 1.197e+00 3.362e-01 3.559 0.000373 *** # Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1 ### Make predictions preds = predict(fit, test, type = ’response’) preds = ifelse(preds > 0.5, 1, 0) tbl = table(target = test$spam, preds) tbl # preds # target 0 1 # email 535 23 # spam 46 316 sum(diag(tbl)) / sum(tbl) # 0.925 65 Lectures 6 hours Arnab Chakraborty 18 Lectures 1.5 hours Pranjal Srivastava, Harshit Srivastava 23 Lectures 2 hours John Shea 18 Lectures 1.5 hours Pranjal Srivastava 46 Lectures 3.5 hours Pranjal Srivastava 37 Lectures 3.5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2870, "s": 2554, "text": "Logistic regression is a classification model in which the response variable is categorical. It is an algorithm that comes from statistics and is used for supervised classification problems. In logistic regression we seek to find the vector β of parameters in the following equation that minimize the cost function." }, { "code": null, "e": 2912, "s": 2870, "text": "logit(pi)=ln(pi1−pi)=β0+β1x1,i+...+βkxk,i" }, { "code": null, "e": 3099, "s": 2912, "text": "The following code demonstrates how to fit a logistic regression model in R. We will use here the spam dataset to demonstrate logistic regression, the same that was used for Naive Bayes." }, { "code": null, "e": 3287, "s": 3099, "text": "From the predictions results in terms of accuracy, we find that the regression model achieves a 92.5% accuracy in the test set, compared to the 72% achieved by the Naive Bayes classifier." }, { "code": null, "e": 4706, "s": 3287, "text": "library(ElemStatLearn)\nhead(spam) \n\n# Split dataset in training and testing \ninx = sample(nrow(spam), round(nrow(spam) * 0.8)) \ntrain = spam[inx,] \ntest = spam[-inx,] \n\n# Fit regression model \nfit = glm(spam ~ ., data = train, family = binomial()) \nsummary(fit) \n\n# Call: \n# glm(formula = spam ~ ., family = binomial(), data = train) \n# \n\n# Deviance Residuals: \n# Min 1Q Median 3Q Max \n# -4.5172 -0.2039 0.0000 0.1111 5.4944\n# Coefficients: \n# Estimate Std. Error z value Pr(>|z|) \n# (Intercept) -1.511e+00 1.546e-01 -9.772 < 2e-16 *** \n# A.1 -4.546e-01 2.560e-01 -1.776 0.075720 . \n# A.2 -1.630e-01 7.731e-02 -2.108 0.035043 * \n# A.3 1.487e-01 1.261e-01 1.179 0.238591 \n# A.4 2.055e+00 1.467e+00 1.401 0.161153 \n# A.5 6.165e-01 1.191e-01 5.177 2.25e-07 *** \n# A.6 7.156e-01 2.768e-01 2.585 0.009747 ** \n# A.7 2.606e+00 3.917e-01 6.652 2.88e-11 *** \n# A.8 6.750e-01 2.284e-01 2.955 0.003127 ** \n# A.9 1.197e+00 3.362e-01 3.559 0.000373 *** \n# Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1 \n\n### Make predictions \npreds = predict(fit, test, type = ’response’) \npreds = ifelse(preds > 0.5, 1, 0) \ntbl = table(target = test$spam, preds) \ntbl \n\n# preds \n# target 0 1 \n# email 535 23 \n# spam 46 316 \nsum(diag(tbl)) / sum(tbl) \n# 0.925\n" }, { "code": null, "e": 4739, "s": 4706, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 4758, "s": 4739, "text": " Arnab Chakraborty" }, { "code": null, "e": 4793, "s": 4758, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4833, "s": 4793, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 4866, "s": 4833, "text": "\n 23 Lectures \n 2 hours \n" }, { "code": null, "e": 4877, "s": 4866, "text": " John Shea" }, { "code": null, "e": 4912, "s": 4877, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4932, "s": 4912, "text": " Pranjal Srivastava" }, { "code": null, "e": 4967, "s": 4932, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4987, "s": 4967, "text": " Pranjal Srivastava" }, { "code": null, "e": 5022, "s": 4987, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5062, "s": 5022, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 5069, "s": 5062, "text": " Print" }, { "code": null, "e": 5080, "s": 5069, "text": " Add Notes" } ]
Check if two vectors are collinear or not - GeeksforGeeks
22 Apr, 2021 Given six integers representing the x, y, and z coordinates of two vectors, the task is to check if the two given vectors are collinear or not. Examples: Input: x1 = 4, y1 = 8, z1 = 12, x2 = 8, y2 = 16, z2 = 24Output: YesExplanation: The given vectors: 4i + 8j + 12k and 8i + 16j + 24k are collinear. Input: x1 = 2, y1 = 8, z1 = -4, x2 = 4, y2 = 16, z2 = 8Output: NoExplanation: The given vectors: 2i + 8j – 4k and 4i + 16j + 8k are not collinear. Approach: The problem can be solved based on the idea that two vectors are collinear if any of the following conditions are satisfied: Two vectors A and B are collinear if there exists a number n, such that A = n · b. Two vectors are collinear if relations of their coordinates are equal, i.e. x1 / x2 = y1 / y2 = z1 / z2. Note: This condition is not valid if one of the components of the vector is zero. Two vectors are collinear if their cross product is equal to the NULL Vector. Therefore, to solve the problem, the idea is to check if the cross-product of the two given vectors is equal to the NULL Vector or not. If found to be true, then print Yes. Otherwise, print No. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate cross// product of two vectorsvoid crossProduct(int vect_A[], int vect_B[], int cross_P[]){ // Update cross_P[0] cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; // Update cross_P[1] cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; // Update cross_P[2] cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0];} // Function to check if two given// vectors are collinear or notvoid checkCollinearity(int x1, int y1, int z1, int x2, int y2, int z2){ // Store the first and second vectors int A[3] = { x1, y1, z1 }; int B[3] = { x2, y2, z2 }; // Store their cross product int cross_P[3]; // Calculate their cross product crossProduct(A, B, cross_P); // Check if their cross product // is a NULL Vector or not if (cross_P[0] == 0 && cross_P[1] == 0 && cross_P[2] == 0) cout << "Yes"; else cout << "No";} // Driver Codeint main(){ // Given coordinates // of the two vectors int x1 = 4, y1 = 8, z1 = 12; int x2 = 8, y2 = 16, z2 = 24; checkCollinearity(x1, y1, z1, x2, y2, z2); return 0;} // Java program for the above approachclass GFG{ // Function to calculate cross// product of two vectorsstatic void crossProduct(int vect_A[], int vect_B[], int cross_P[]){ // Update cross_P[0] cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; // Update cross_P[1] cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; // Update cross_P[2] cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0];} // Function to check if two given// vectors are collinear or notstatic void checkCollinearity(int x1, int y1, int z1, int x2, int y2, int z2){ // Store the first and second vectors int A[] = { x1, y1, z1 }; int B[] = { x2, y2, z2 }; // Store their cross product int cross_P[] = new int[3]; // Calculate their cross product crossProduct(A, B, cross_P); // Check if their cross product // is a NULL Vector or not if (cross_P[0] == 0 && cross_P[1] == 0 && cross_P[2] == 0) System.out.print("Yes"); else System.out.print("No");} // Driver Codepublic static void main (String[] args){ // Given coordinates // of the two vectors int x1 = 4, y1 = 8, z1 = 12; int x2 = 8, y2 = 16, z2 = 24; checkCollinearity(x1, y1, z1, x2, y2, z2);}} // This code is contributed by AnkThon # Python3 program for the above approach # Function to calculate cross# product of two vectorsdef crossProduct(vect_A, vect_B, cross_P): # Update cross_P[0] cross_P[0] = (vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]) # Update cross_P[1] cross_P[1] = (vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]) # Update cross_P[2] cross_P[2] = (vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0]) # Function to check if two given# vectors are collinear or notdef checkCollinearity(x1, y1, z1, x2, y2, z2): # Store the first and second vectors A = [x1, y1, z1] B = [x2, y2, z2] # Store their cross product cross_P = [0 for i in range(3)] # Calculate their cross product crossProduct(A, B, cross_P) # Check if their cross product # is a NULL Vector or not if (cross_P[0] == 0 and cross_P[1] == 0 and cross_P[2] == 0): print("Yes") else: print("No") # Driver Codeif __name__ == '__main__': # Given coordinates # of the two vectors x1 = 4 y1 = 8 z1 = 12 x2 = 8 y2 = 16 z2 = 24 checkCollinearity(x1, y1, z1, x2, y2, z2) # This code is contributed by bgangwar59 // C# program for the above approachusing System; class GFG{ // Function to calculate cross// product of two vectorsstatic void crossProduct(int []vect_A, int []vect_B, int []cross_P){ // Update cross_P[0] cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; // Update cross_P[1] cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; // Update cross_P[2] cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0];} // Function to check if two given// vectors are collinear or notstatic void checkCollinearity(int x1, int y1, int z1, int x2, int y2, int z2){ // Store the first and second vectors int []A = { x1, y1, z1 }; int []B = { x2, y2, z2 }; // Store their cross product int []cross_P = new int[3]; // Calculate their cross product crossProduct(A, B, cross_P); // Check if their cross product // is a NULL Vector or not if (cross_P[0] == 0 && cross_P[1] == 0 && cross_P[2] == 0) Console.Write("Yes"); else Console.Write("No");} // Driver Codepublic static void Main (string[] args){ // Given coordinates // of the two vectors int x1 = 4, y1 = 8, z1 = 12; int x2 = 8, y2 = 16, z2 = 24; checkCollinearity(x1, y1, z1, x2, y2, z2);}} // This code is contributed by AnkThon <script> // Javascript program for the // above approach // Function to calculate cross // product of two vectors function crossProduct(vect_A, vect_B, cross_P) { // Update cross_P[0] cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; // Update cross_P[1] cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; // Update cross_P[2] cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0]; } // Function to check if two given // vectors are collinear or not function checkCollinearity(x1, y1, z1, x2, y2, z2) { // Store the first and second vectors let A = [x1, y1, z1]; let B = [x2, y2, z2]; // Store their cross product let cross_P = []; // Calculate their cross product crossProduct(A, B, cross_P); // Check if their cross product // is a NULL Vector or not if (cross_P[0] == 0 && cross_P[1] == 0 && cross_P[2] == 0) document.write("Yes") else document.write("No") } // Driver Code // Given coordinates // of the two vectors let x1 = 4, y1 = 8, z1 = 12; let x2 = 8, y2 = 16, z2 = 24; checkCollinearity(x1, y1, z1, x2, y2, z2); // This code is contributed by Hritik </script> Yes Time Complexity: O(1)Auxiliary Space: O(1) bgangwar59 ankthon hritikrommie Geometric-Lines Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Program to multiply two matrices Fizz Buzz Implementation Modular multiplicative inverse Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24717, "s": 24689, "text": "\n22 Apr, 2021" }, { "code": null, "e": 24861, "s": 24717, "text": "Given six integers representing the x, y, and z coordinates of two vectors, the task is to check if the two given vectors are collinear or not." }, { "code": null, "e": 24871, "s": 24861, "text": "Examples:" }, { "code": null, "e": 25018, "s": 24871, "text": "Input: x1 = 4, y1 = 8, z1 = 12, x2 = 8, y2 = 16, z2 = 24Output: YesExplanation: The given vectors: 4i + 8j + 12k and 8i + 16j + 24k are collinear." }, { "code": null, "e": 25165, "s": 25018, "text": "Input: x1 = 2, y1 = 8, z1 = -4, x2 = 4, y2 = 16, z2 = 8Output: NoExplanation: The given vectors: 2i + 8j – 4k and 4i + 16j + 8k are not collinear." }, { "code": null, "e": 25300, "s": 25165, "text": "Approach: The problem can be solved based on the idea that two vectors are collinear if any of the following conditions are satisfied:" }, { "code": null, "e": 25383, "s": 25300, "text": "Two vectors A and B are collinear if there exists a number n, such that A = n · b." }, { "code": null, "e": 25570, "s": 25383, "text": "Two vectors are collinear if relations of their coordinates are equal, i.e. x1 / x2 = y1 / y2 = z1 / z2. Note: This condition is not valid if one of the components of the vector is zero." }, { "code": null, "e": 25648, "s": 25570, "text": "Two vectors are collinear if their cross product is equal to the NULL Vector." }, { "code": null, "e": 25843, "s": 25648, "text": "Therefore, to solve the problem, the idea is to check if the cross-product of the two given vectors is equal to the NULL Vector or not. If found to be true, then print Yes. Otherwise, print No. " }, { "code": null, "e": 25894, "s": 25843, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25900, "s": 25894, "text": "C++14" }, { "code": null, "e": 25905, "s": 25900, "text": "Java" }, { "code": null, "e": 25913, "s": 25905, "text": "Python3" }, { "code": null, "e": 25916, "s": 25913, "text": "C#" }, { "code": null, "e": 25927, "s": 25916, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate cross// product of two vectorsvoid crossProduct(int vect_A[], int vect_B[], int cross_P[]){ // Update cross_P[0] cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; // Update cross_P[1] cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; // Update cross_P[2] cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0];} // Function to check if two given// vectors are collinear or notvoid checkCollinearity(int x1, int y1, int z1, int x2, int y2, int z2){ // Store the first and second vectors int A[3] = { x1, y1, z1 }; int B[3] = { x2, y2, z2 }; // Store their cross product int cross_P[3]; // Calculate their cross product crossProduct(A, B, cross_P); // Check if their cross product // is a NULL Vector or not if (cross_P[0] == 0 && cross_P[1] == 0 && cross_P[2] == 0) cout << \"Yes\"; else cout << \"No\";} // Driver Codeint main(){ // Given coordinates // of the two vectors int x1 = 4, y1 = 8, z1 = 12; int x2 = 8, y2 = 16, z2 = 24; checkCollinearity(x1, y1, z1, x2, y2, z2); return 0;}", "e": 27284, "s": 25927, "text": null }, { "code": "// Java program for the above approachclass GFG{ // Function to calculate cross// product of two vectorsstatic void crossProduct(int vect_A[], int vect_B[], int cross_P[]){ // Update cross_P[0] cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; // Update cross_P[1] cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; // Update cross_P[2] cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0];} // Function to check if two given// vectors are collinear or notstatic void checkCollinearity(int x1, int y1, int z1, int x2, int y2, int z2){ // Store the first and second vectors int A[] = { x1, y1, z1 }; int B[] = { x2, y2, z2 }; // Store their cross product int cross_P[] = new int[3]; // Calculate their cross product crossProduct(A, B, cross_P); // Check if their cross product // is a NULL Vector or not if (cross_P[0] == 0 && cross_P[1] == 0 && cross_P[2] == 0) System.out.print(\"Yes\"); else System.out.print(\"No\");} // Driver Codepublic static void main (String[] args){ // Given coordinates // of the two vectors int x1 = 4, y1 = 8, z1 = 12; int x2 = 8, y2 = 16, z2 = 24; checkCollinearity(x1, y1, z1, x2, y2, z2);}} // This code is contributed by AnkThon", "e": 28754, "s": 27284, "text": null }, { "code": "# Python3 program for the above approach # Function to calculate cross# product of two vectorsdef crossProduct(vect_A, vect_B, cross_P): # Update cross_P[0] cross_P[0] = (vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]) # Update cross_P[1] cross_P[1] = (vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]) # Update cross_P[2] cross_P[2] = (vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0]) # Function to check if two given# vectors are collinear or notdef checkCollinearity(x1, y1, z1, x2, y2, z2): # Store the first and second vectors A = [x1, y1, z1] B = [x2, y2, z2] # Store their cross product cross_P = [0 for i in range(3)] # Calculate their cross product crossProduct(A, B, cross_P) # Check if their cross product # is a NULL Vector or not if (cross_P[0] == 0 and cross_P[1] == 0 and cross_P[2] == 0): print(\"Yes\") else: print(\"No\") # Driver Codeif __name__ == '__main__': # Given coordinates # of the two vectors x1 = 4 y1 = 8 z1 = 12 x2 = 8 y2 = 16 z2 = 24 checkCollinearity(x1, y1, z1, x2, y2, z2) # This code is contributed by bgangwar59", "e": 29966, "s": 28754, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to calculate cross// product of two vectorsstatic void crossProduct(int []vect_A, int []vect_B, int []cross_P){ // Update cross_P[0] cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; // Update cross_P[1] cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; // Update cross_P[2] cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0];} // Function to check if two given// vectors are collinear or notstatic void checkCollinearity(int x1, int y1, int z1, int x2, int y2, int z2){ // Store the first and second vectors int []A = { x1, y1, z1 }; int []B = { x2, y2, z2 }; // Store their cross product int []cross_P = new int[3]; // Calculate their cross product crossProduct(A, B, cross_P); // Check if their cross product // is a NULL Vector or not if (cross_P[0] == 0 && cross_P[1] == 0 && cross_P[2] == 0) Console.Write(\"Yes\"); else Console.Write(\"No\");} // Driver Codepublic static void Main (string[] args){ // Given coordinates // of the two vectors int x1 = 4, y1 = 8, z1 = 12; int x2 = 8, y2 = 16, z2 = 24; checkCollinearity(x1, y1, z1, x2, y2, z2);}} // This code is contributed by AnkThon", "e": 31442, "s": 29966, "text": null }, { "code": "<script> // Javascript program for the // above approach // Function to calculate cross // product of two vectors function crossProduct(vect_A, vect_B, cross_P) { // Update cross_P[0] cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; // Update cross_P[1] cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; // Update cross_P[2] cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0]; } // Function to check if two given // vectors are collinear or not function checkCollinearity(x1, y1, z1, x2, y2, z2) { // Store the first and second vectors let A = [x1, y1, z1]; let B = [x2, y2, z2]; // Store their cross product let cross_P = []; // Calculate their cross product crossProduct(A, B, cross_P); // Check if their cross product // is a NULL Vector or not if (cross_P[0] == 0 && cross_P[1] == 0 && cross_P[2] == 0) document.write(\"Yes\") else document.write(\"No\") } // Driver Code // Given coordinates // of the two vectors let x1 = 4, y1 = 8, z1 = 12; let x2 = 8, y2 = 16, z2 = 24; checkCollinearity(x1, y1, z1, x2, y2, z2); // This code is contributed by Hritik </script>", "e": 33054, "s": 31442, "text": null }, { "code": null, "e": 33058, "s": 33054, "text": "Yes" }, { "code": null, "e": 33103, "s": 33060, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 33116, "s": 33105, "text": "bgangwar59" }, { "code": null, "e": 33124, "s": 33116, "text": "ankthon" }, { "code": null, "e": 33137, "s": 33124, "text": "hritikrommie" }, { "code": null, "e": 33153, "s": 33137, "text": "Geometric-Lines" }, { "code": null, "e": 33166, "s": 33153, "text": "Mathematical" }, { "code": null, "e": 33185, "s": 33166, "text": "School Programming" }, { "code": null, "e": 33198, "s": 33185, "text": "Mathematical" }, { "code": null, "e": 33296, "s": 33198, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33328, "s": 33296, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 33372, "s": 33328, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 33405, "s": 33372, "text": "Program to multiply two matrices" }, { "code": null, "e": 33430, "s": 33405, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 33461, "s": 33430, "text": "Modular multiplicative inverse" }, { "code": null, "e": 33479, "s": 33461, "text": "Python Dictionary" }, { "code": null, "e": 33495, "s": 33479, "text": "Arrays in C/C++" }, { "code": null, "e": 33514, "s": 33495, "text": "Inheritance in C++" }, { "code": null, "e": 33539, "s": 33514, "text": "Reverse a string in Java" } ]
Python - Calculate the minimum of column values of a Pandas DataFrame
To get the minimum of column values, use the min() function. At first, import the required Pandas library − import pandas as pd Now, create a DataFrame with two columns − dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90] } ) Finding the minimum value of a single column “Units” using min() − print"Minimum Units from DataFrame1 = ",dataFrame1['Units'].min() In the same way, we have calculated the minimum value from the 2nd DataFrame. Following is the complete code − import pandas as pd # Create DataFrame1 dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90] } ) print"DataFrame1 ...\n",dataFrame1 # Finding minimum value of a single column "Units" print"Minimum Units from DataFrame1 = ",dataFrame1['Units'].min() # Create DataFrame2 dataFrame2 = pd.DataFrame( { "Product": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD', 'SSD'],"Price": [8000, 500, 3000, 1500, 3000, 4000] } ) print"\nDataFrame2 ...\n",dataFrame2 # Finding minimum value of a single column "Price" print"Minimum Price from DataFrame2 = ",dataFrame2['Price'].min() This will produce the following output − DataFrame1 ... Car Units 0 BMW 100 1 Lexus 150 2 Audi 110 3 Tesla 80 4 Bentley 110 5 Jaguar 90 Minimum Units from DataFrame1 = 80 DataFrame2 ... Price Product 0 8000 TV 1 500 PenDrive 2 3000 HeadPhone 3 1500 EarPhone 4 3000 HDD 5 4000 SSD Minimum Price from DataFrame2 = 500
[ { "code": null, "e": 1170, "s": 1062, "text": "To get the minimum of column values, use the min() function. At first, import the required Pandas library −" }, { "code": null, "e": 1190, "s": 1170, "text": "import pandas as pd" }, { "code": null, "e": 1233, "s": 1190, "text": "Now, create a DataFrame with two columns −" }, { "code": null, "e": 1375, "s": 1233, "text": "dataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],\"Units\": [100, 150, 110, 80, 110, 90] }\n)" }, { "code": null, "e": 1442, "s": 1375, "text": "Finding the minimum value of a single column “Units” using min() −" }, { "code": null, "e": 1509, "s": 1442, "text": "print\"Minimum Units from DataFrame1 = \",dataFrame1['Units'].min()\n" }, { "code": null, "e": 1587, "s": 1509, "text": "In the same way, we have calculated the minimum value from the 2nd DataFrame." }, { "code": null, "e": 1620, "s": 1587, "text": "Following is the complete code −" }, { "code": null, "e": 2293, "s": 1620, "text": "import pandas as pd\n\n# Create DataFrame1\ndataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],\"Units\": [100, 150, 110, 80, 110, 90] }\n)\n\nprint\"DataFrame1 ...\\n\",dataFrame1\n\n# Finding minimum value of a single column \"Units\"\nprint\"Minimum Units from DataFrame1 = \",dataFrame1['Units'].min()\n\n# Create DataFrame2\ndataFrame2 = pd.DataFrame(\n {\n \"Product\": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD', 'SSD'],\"Price\": [8000, 500, 3000, 1500, 3000, 4000]\n }\n)\n\nprint\"\\nDataFrame2 ...\\n\",dataFrame2\n\n# Finding minimum value of a single column \"Price\"\nprint\"Minimum Price from DataFrame2 = \",dataFrame2['Price'].min()" }, { "code": null, "e": 2334, "s": 2293, "text": "This will produce the following output −" }, { "code": null, "e": 2709, "s": 2334, "text": "DataFrame1 ...\n Car Units\n0 BMW 100\n1 Lexus 150\n2 Audi 110\n3 Tesla 80\n4 Bentley 110\n5 Jaguar 90\nMinimum Units from DataFrame1 = 80\n\nDataFrame2 ...\n Price Product\n0 8000 TV\n1 500 PenDrive\n2 3000 HeadPhone\n3 1500 EarPhone\n4 3000 HDD\n5 4000 SSD\nMinimum Price from DataFrame2 = 500" } ]
Explain project operation in relational algebra (DBMS)?
Query is a question or requesting information. Query language is a language which is used to retrieve information from a database. Query language is divided into two types − Procedural language Procedural language Non-procedural language Non-procedural language Information is retrieved from the database by specifying the sequence of operations to be performed. For Example − Relational algebra. Structure Query language (SQL) is based on relational algebra. Relational algebra consists of a set of operations that take one or two relations as an input and produces a new relation as output. The different types of relational algebra operations are as follows − Select operation Select operation Project operation Project operation Rename operation Rename operation Union operation Union operation Intersection operation Intersection operation Difference operation Difference operation Cartesian product operation Cartesian product operation Join operation Join operation Division operation Division operation Select, project, rename comes under unary operation (operate on one table). It displays the specific column of a table. It is denoted by pie (∏). It is a vertical subset of the original relation. It eliminates duplicate tuples. The syntax is as follows − ∏regno(student) Consider the student table: To display regno column of student table, we can use the following command − ∏regno(student) To display branch, section column of student table, use the following command − ∏branch,section(student) The result is as follows − To display regno, section of ECE students, use the following command − ∏regno,section(σbranch=ECE(student)) Note: Conditions can be written in select operation but not in projection operation. Consider the employee table to know more about projection. If no condition is specified in the query then, Π empid, ename, salary, address, dno (emp). If no condition is specified in the query then, Π empid, ename, salary, address, dno (emp). If condition is specified then, the composition of the select and projection is as follows − If condition is specified then, the composition of the select and projection is as follows − ∏ empid, ename, salary, address, dno (σ salary >20,00 ^ LOC = HOD ^ dno=20) (emp)
[ { "code": null, "e": 1193, "s": 1062, "text": "Query is a question or requesting information. Query language is a language which is used to retrieve information from a database." }, { "code": null, "e": 1236, "s": 1193, "text": "Query language is divided into two types −" }, { "code": null, "e": 1256, "s": 1236, "text": "Procedural language" }, { "code": null, "e": 1276, "s": 1256, "text": "Procedural language" }, { "code": null, "e": 1300, "s": 1276, "text": "Non-procedural language" }, { "code": null, "e": 1324, "s": 1300, "text": "Non-procedural language" }, { "code": null, "e": 1425, "s": 1324, "text": "Information is retrieved from the database by specifying the sequence of operations to be performed." }, { "code": null, "e": 1459, "s": 1425, "text": "For Example − Relational algebra." }, { "code": null, "e": 1522, "s": 1459, "text": "Structure Query language (SQL) is based on relational algebra." }, { "code": null, "e": 1655, "s": 1522, "text": "Relational algebra consists of a set of operations that take one or two relations as an input and produces a new relation as output." }, { "code": null, "e": 1725, "s": 1655, "text": "The different types of relational algebra operations are as follows −" }, { "code": null, "e": 1742, "s": 1725, "text": "Select operation" }, { "code": null, "e": 1759, "s": 1742, "text": "Select operation" }, { "code": null, "e": 1777, "s": 1759, "text": "Project operation" }, { "code": null, "e": 1795, "s": 1777, "text": "Project operation" }, { "code": null, "e": 1812, "s": 1795, "text": "Rename operation" }, { "code": null, "e": 1829, "s": 1812, "text": "Rename operation" }, { "code": null, "e": 1845, "s": 1829, "text": "Union operation" }, { "code": null, "e": 1861, "s": 1845, "text": "Union operation" }, { "code": null, "e": 1884, "s": 1861, "text": "Intersection operation" }, { "code": null, "e": 1907, "s": 1884, "text": "Intersection operation" }, { "code": null, "e": 1928, "s": 1907, "text": "Difference operation" }, { "code": null, "e": 1949, "s": 1928, "text": "Difference operation" }, { "code": null, "e": 1977, "s": 1949, "text": "Cartesian product operation" }, { "code": null, "e": 2005, "s": 1977, "text": "Cartesian product operation" }, { "code": null, "e": 2020, "s": 2005, "text": "Join operation" }, { "code": null, "e": 2035, "s": 2020, "text": "Join operation" }, { "code": null, "e": 2054, "s": 2035, "text": "Division operation" }, { "code": null, "e": 2073, "s": 2054, "text": "Division operation" }, { "code": null, "e": 2149, "s": 2073, "text": "Select, project, rename comes under unary operation (operate on one table)." }, { "code": null, "e": 2301, "s": 2149, "text": "It displays the specific column of a table. It is denoted by pie (∏). It is a vertical subset of the original relation. It eliminates duplicate tuples." }, { "code": null, "e": 2328, "s": 2301, "text": "The syntax is as follows −" }, { "code": null, "e": 2344, "s": 2328, "text": "∏regno(student)" }, { "code": null, "e": 2372, "s": 2344, "text": "Consider the student table:" }, { "code": null, "e": 2449, "s": 2372, "text": "To display regno column of student table, we can use the following command −" }, { "code": null, "e": 2465, "s": 2449, "text": "∏regno(student)" }, { "code": null, "e": 2545, "s": 2465, "text": "To display branch, section column of student table, use the following command −" }, { "code": null, "e": 2570, "s": 2545, "text": "∏branch,section(student)" }, { "code": null, "e": 2597, "s": 2570, "text": "The result is as follows −" }, { "code": null, "e": 2668, "s": 2597, "text": "To display regno, section of ECE students, use the following command −" }, { "code": null, "e": 2705, "s": 2668, "text": "∏regno,section(σbranch=ECE(student))" }, { "code": null, "e": 2790, "s": 2705, "text": "Note: Conditions can be written in select operation but not in projection operation." }, { "code": null, "e": 2849, "s": 2790, "text": "Consider the employee table to know more about projection." }, { "code": null, "e": 2941, "s": 2849, "text": "If no condition is specified in the query then, Π empid, ename, salary, address, dno (emp)." }, { "code": null, "e": 3033, "s": 2941, "text": "If no condition is specified in the query then, Π empid, ename, salary, address, dno (emp)." }, { "code": null, "e": 3126, "s": 3033, "text": "If condition is specified then, the composition of the select and projection is as follows −" }, { "code": null, "e": 3219, "s": 3126, "text": "If condition is specified then, the composition of the select and projection is as follows −" }, { "code": null, "e": 3301, "s": 3219, "text": "∏ empid, ename, salary, address, dno (σ salary >20,00 ^ LOC = HOD ^ dno=20) (emp)" } ]
How to horizontally center a div using CSS? - GeeksforGeeks
08 Nov, 2021 In this article, we will know how to how to center the div horizontally using CSS. To Horizontally centered the <div> element: We can use the property of margin set to auto i.e margin: auto;. The <div> element takes up its specified width and divides equally the remaining space by the left and right margins. We can set the width of an element that will prevent it from stretching to the container’s edge. In that case, the element will take the specified width & the rest of the space will be split equally between the two margins. If the width is set to 0 or 100% then the center aligning will not be applicable to the element. Example: This example describes the use of the margin: auto to horizontally center a block element. HTML <!DOCTYPE html><html> <head> <title> How to horizontally center a div using CSS </title> <style> div { width: 300px; margin: auto; padding: 5px; border: 3px solid green; color: red; } h1, h2 { text-align: center; color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>margin:auto</h2> <div> It is a computer science portal for Geeks. GeeksforGeeks ia a good website for learning computer science. </div></body> </html> Output: Example: This example describes the use of the text-align: center to position the text to the center. HTML <!DOCTYPE html><html> <head> <title> How to horizontally center a div using CSS </title> <style> div { width: 300px; padding: 5px; border: 3px solid green; color: red; text-align: center; } h1, h2 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>text-align:center</h2> <div> It is a computer science portal for Geeks. GeeksforGeeks ia a good website for learning computer science; </div></body> </html> Output: We can use the CSS position property to align horizontally center a div. Example: This example describes the use of the position property to align the horizontal center. HTML <!DOCTYPE html><html> <head> <title> How to horizontally center a div using CSS </title> <style> div { width: 300px; padding: 5px; border: 3px solid green; color: red; position: absolute; } h1, h2 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>position: absolute</h2> <div> It is a computer science portal for Geeks. GeeksforGeeks ia a good website for learning computer science; </div></body> </html> Output: For horizontal aligning the content or element to the left & right, we can use the float property by specifying its value as left for aligning to the left or right to align the element to the right. Example: This example describes the float property & assigned its value as left. HTML <!DOCTYPE html><html> <head> <title> How to horizontally center a div using CSS </title> <style> div { width: 300px; padding: 5px; border: 3px solid green; color: red; float: left; } h1, h2 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>float: left</h2> <div> It is a computer science portal for Geeks. GeeksforGeeks ia a good website for learning computer science; </div></body> </html> Output: Note: For Microsoft Edge & Internet Explorer, The auto value is not supported in quirks mode. ysachin2314 bhaskargeeksforgeeks CSS-Misc Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24678, "s": 24650, "text": "\n08 Nov, 2021" }, { "code": null, "e": 24761, "s": 24678, "text": "In this article, we will know how to how to center the div horizontally using CSS." }, { "code": null, "e": 24805, "s": 24761, "text": "To Horizontally centered the <div> element:" }, { "code": null, "e": 24870, "s": 24805, "text": "We can use the property of margin set to auto i.e margin: auto;." }, { "code": null, "e": 24988, "s": 24870, "text": "The <div> element takes up its specified width and divides equally the remaining space by the left and right margins." }, { "code": null, "e": 25309, "s": 24988, "text": "We can set the width of an element that will prevent it from stretching to the container’s edge. In that case, the element will take the specified width & the rest of the space will be split equally between the two margins. If the width is set to 0 or 100% then the center aligning will not be applicable to the element." }, { "code": null, "e": 25409, "s": 25309, "text": "Example: This example describes the use of the margin: auto to horizontally center a block element." }, { "code": null, "e": 25414, "s": 25409, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to horizontally center a div using CSS </title> <style> div { width: 300px; margin: auto; padding: 5px; border: 3px solid green; color: red; } h1, h2 { text-align: center; color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>margin:auto</h2> <div> It is a computer science portal for Geeks. GeeksforGeeks ia a good website for learning computer science. </div></body> </html>", "e": 25959, "s": 25414, "text": null }, { "code": null, "e": 25967, "s": 25959, "text": "Output:" }, { "code": null, "e": 26069, "s": 25967, "text": "Example: This example describes the use of the text-align: center to position the text to the center." }, { "code": null, "e": 26074, "s": 26069, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to horizontally center a div using CSS </title> <style> div { width: 300px; padding: 5px; border: 3px solid green; color: red; text-align: center; } h1, h2 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>text-align:center</h2> <div> It is a computer science portal for Geeks. GeeksforGeeks ia a good website for learning computer science; </div></body> </html>", "e": 26604, "s": 26074, "text": null }, { "code": null, "e": 26612, "s": 26604, "text": "Output:" }, { "code": null, "e": 26685, "s": 26612, "text": "We can use the CSS position property to align horizontally center a div." }, { "code": null, "e": 26782, "s": 26685, "text": "Example: This example describes the use of the position property to align the horizontal center." }, { "code": null, "e": 26787, "s": 26782, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to horizontally center a div using CSS </title> <style> div { width: 300px; padding: 5px; border: 3px solid green; color: red; position: absolute; } h1, h2 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>position: absolute</h2> <div> It is a computer science portal for Geeks. GeeksforGeeks ia a good website for learning computer science; </div></body> </html>", "e": 27318, "s": 26787, "text": null }, { "code": null, "e": 27326, "s": 27318, "text": "Output:" }, { "code": null, "e": 27525, "s": 27326, "text": "For horizontal aligning the content or element to the left & right, we can use the float property by specifying its value as left for aligning to the left or right to align the element to the right." }, { "code": null, "e": 27606, "s": 27525, "text": "Example: This example describes the float property & assigned its value as left." }, { "code": null, "e": 27611, "s": 27606, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to horizontally center a div using CSS </title> <style> div { width: 300px; padding: 5px; border: 3px solid green; color: red; float: left; } h1, h2 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>float: left</h2> <div> It is a computer science portal for Geeks. GeeksforGeeks ia a good website for learning computer science; </div></body> </html>", "e": 28128, "s": 27611, "text": null }, { "code": null, "e": 28136, "s": 28128, "text": "Output:" }, { "code": null, "e": 28230, "s": 28136, "text": "Note: For Microsoft Edge & Internet Explorer, The auto value is not supported in quirks mode." }, { "code": null, "e": 28242, "s": 28230, "text": "ysachin2314" }, { "code": null, "e": 28263, "s": 28242, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 28272, "s": 28263, "text": "CSS-Misc" }, { "code": null, "e": 28279, "s": 28272, "text": "Picked" }, { "code": null, "e": 28283, "s": 28279, "text": "CSS" }, { "code": null, "e": 28300, "s": 28283, "text": "Web Technologies" }, { "code": null, "e": 28398, "s": 28300, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28407, "s": 28398, "text": "Comments" }, { "code": null, "e": 28420, "s": 28407, "text": "Old Comments" }, { "code": null, "e": 28482, "s": 28420, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28532, "s": 28482, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28580, "s": 28532, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28638, "s": 28580, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28688, "s": 28638, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 28730, "s": 28688, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28763, "s": 28730, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28806, "s": 28763, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28868, "s": 28806, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
EDA(Exploratory Data Analysis) on Haberman’s Survival Data Set make you diagnose Cancer? | by pratik mirjapure | Towards Data Science
Haberman’s data set contains data from the study conducted in University of Chicago’s Billings Hospital between year 1958 to 1970 for the patients who undergone surgery of breast cancer. Source :https://www.kaggle.com/gilsousa/habermans-survival-data-set) I would like to explain the various data analysis operation, I have done on this data set and how to conclude or predict survival status of patients who undergone from surgery. First of all for any data analysis task or for performing operation on data we should have good domain knowledge so that we can relate the data features and also can give accurate conclusion. So, I would like to explain the features of data set and how it affects other feature. There are 4 attribute in this data set out of which 3 are features and 1 class attribute as below. Also, there are 306 instances of data. Number of Axillary nodes(Lymph Nodes)AgeOperation YearSurvival Status Number of Axillary nodes(Lymph Nodes) Age Operation Year Survival Status Lymph Node: Lymph nodes are small, bean-shaped organs that act as filters along the lymph fluid channels. As lymph fluid leaves the breast and eventually goes back into the bloodstream, the lymph nodes try to catch and trap cancer cells before they reach other parts of the body. Having cancer cells in the lymph nodes under your arm suggests an increased risk of the cancer spreading.In our data it is axillary nodes detected(0–52) (Source: https://www.breastcancer.org/symptoms/diagnosis/lymph_nodes) Age: It represent the age of patient at which they undergone surgery (age from 30 to 83) Operation year: Year in which patient was undergone surgery(1958–1969) Survival Status: It represent whether patient survive more than 5 years or less after undergone through surgery.Here if patients survived 5 years or more is represented as 1 and patients who survived less than 5 years is represented as 2. So, lets get started to play with the data set and get the conclusion. I had used python for this purpose as it has the rich collection of machine learning libraries and mathematical operation. I will mostly use common packages as Pandas, Numpy, Matplotlib and seaborn which help me for mathematical operations and also plotting, importing and exporting of files. import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport numpy as nphaberman= pd.read_csv(“haberman.csv”) In above snippet using the function read_csv from pandas packages you can import the data from csv file format .So, after importing the data set you need to check if data imported properly. Below code snippet will show the shape of data that is the number of columns and rows present in data. print(haberman.shape) Here you can get confidence that the data you want get successfully imported which shows 306 instances of data and 4 attributes present as we see previously in introduction. You can even see the labels of columns present using a single line of code as follows. print(haberman.columns) Here the dtype means data type which is object type for all columns present in data. Similarly you can also find the dtype of feature and class attribute and can find how many number of data points belongs to 1 class and how many to other just with simple line of code as below. haberman[“Survival_Status”].value_counts() From above piece of code you can conclude that there are 225 patients out of 306 were survived more than 5 years and only 81 patients survived less than 5 years Now lets plot some plots which give us more clarification of data so that we can easily come to the conclusion. haberman.plot(kind=’scatter’, x=’Axillary_Nodes’, y=’Age’) plt.grid()plt.show() These above snippet will given me the scatter plot w.r.t the Nodes on x-axis and Age on y-axis.Our matplotlib library functions grid and show help me to plot data in grid and also to display it on console. Above scatter plot shows all data in overlap fashion and also in same colour due to which we are unable to distinguish between data and also there are possibilities that you may miss some of my data which may lead to wrong conclusion. So, to distinguish between the data we can use seaborn packages function which simply to distinguish data visually by allocating different colours to every classification feature. sns.set_style(‘whitegrid’)sns.FacetGrid(haberman, hue=”Survival_Status”, size=4) \ .map(plt.scatter, “Axillary_Nodes”, “Age”) \ .add_legend();plt.show(); In above snippet, I import functions from seaborn library like FacetGrid due to which we are able to distinguish between the data classification.Here blue dots represent survival more than 5 years and orange dots represent survival less than 5 years. As there are 3 features from which we can conclude our classification so how can we select any feature from all so that we can get output with less error rate. To do so we can use pairplots from seaborn to plot of various combination from which we can select best pair for our further operation and final conclusion. hue=”Survival_Status” will give on which feature you need to do classification. Below image shows the plotting of pairplots combination and code snippet for it. plt.close();sns.set_style(“whitegrid”);sns.pairplot(haberman, hue=”Survival_Status”, size=3, vars=[‘Age’,’Operation_Age’, ‘Axillary_Nodes’])plt.show() Above image is the combinations plot of all features in data. These types of plot is know as pairplots. Plot 1,Plot 5 and Plot 9 are the histograms of all combinations of features which explain you the density of data by considering different features of data. Now lets take plot 1 by 1 and I will explain you that which data feature I will take for my further data analysis. I will take such a data which can show me distinguishable difference than any other data feature. So,lets start analysing each plot except plot 1,5,9 as it is a histogram of features in pairplots. Plot 2:-In this plot you can see that there is Operation Age on X-axis and Age on Y-axis and the plot of there data is mostly overlapping on each other data so we cannot distinguish if there is any orange point present below blue point or vice versa.So I am rejecting these 2 data feature combination for further analysis. Plot 3:-In this plot there are some points which is distinguishable but still it is better from other plot as we can provide conclusion more precisely by histogram and CDF which you will learn after a while. In this plot the overlap of points are there but still it is better than all other plots comparatively. So I will select the data feature of this plot ie. Age and Axillary nodes. Plot 4:- It is plotted using the data feature Operation Age and Age which shows similar type of plot like Plot 2 but it just rotated by 90 degree. So I also reject this feature Plot 6:-It plot on the feature Operation Age and Axillary nodes which is somewhat similar to the Plot 2 but overlapping of points seems to be more in this plot comparative to other. So, I will also reject this combination Plot 7:- This plot is similar as Plot 3 only feature interchange its axis so the plot will rotate by 90 degree. Also, I will accept this combination for further operations Plot 8:- It is same as Plot 6 only feature on axis interchange. So, I consider the feature Age and Axillary nodes plotting in the Plot 3 and 7 for my all further data operations 1D-Scatter Plots Lets plot 1D scatter plot and see if I can distinguish data by using below code snippet. import numpy as nphaberman_Long_Survive = haberman.loc[haberman[“Survival_Status”] == 1];haberman_Short_Survive = haberman.loc[haberman[“Survival_Status”] == 2];plt.plot(haberman_Long_Survive[“Axillary_Nodes”], np.zeros_like(haberman_Long_Survive[‘Axillary_Nodes’]), ‘o’)plt.plot(haberman_Short_Survive[“Axillary_Nodes”], np.zeros_like(haberman_Short_Survive[‘Axillary_Nodes’]), ‘o’)plt.show() I used the Numpy library function to plot 1D scatter plot individually for every classified data. Below you can see the 1D scatter plot using data feature Age and Axillary nodes Here you can observe the data of short survival status are mostly overlap on long survival status due to which you will not able to conclude on this data. You can get better clarification if you use PDF or CDF of data for plotting. Let me explain you concept of PDF and CDF in high level. PDF (Probability Density Function):- It shows the density of that data or number of data present on that point. PDF will be a peak like structure represents high peak if more number of data present or else it will be flat/ small peak if number of data present is less.It is smooth graph plot using the edges of histogram CDF (Cumulative Distribution Function):- It is representation of cumulative data of PDF ie. it will plot a graph by considering PDF for every data point cumulatively. Seaborn library will help you to plot PDF and CDF of any data so that you can easily visualise the density of data present on specific point.Below code snippet will plot the PDF sns.FacetGrid(haberman,hue=”Survival_Status”, size=8)\.map(sns.distplot,”Axillary_Nodes”)\.add_legend() Lets try to plot PDF of each data feature and see which data give us maximum precision. PDF of Age Observation: In above plot it is observed that at the age range from 30–75 the status of survival and death is same. So, using this datapoint we cannot predict anything PDF of Operation Age Observation: Similar here we cannot predict anything with these histograms as there is equal number of density in each data point. Even the PDF of both classification overlap on each other. PDF of Axillary Nodes Observation: It has been observed that people survive long if they have less axillary nodes detected and vice versa but still it is hard to classify but this is the best data you can choose among all. So, I accept the PDF of Axillary nodes and can conclude below result if(AxillaryNodes≤0) Patient= Long survival else if(AxillaryNodes≥0 && Axillary nodes≤3.5(approx)) Patient= Long survival chances are high else if(Axillary nodes ≥3.5) Patient = Short survival So from above PDF we can say the patients survival status, but we cannot exactly say what percentage of patient will actually short survive or long survive. To know that we have another distribution that is CDF. CDF will give the cumulative plot of PDF so that you can calculate what are the exact percentage of patient survival status Let’s plot CDF for our selected feature which is Axillary nodes counts, bin_edges = np.histogram(haberman_Long_Survive[‘Axillary_Nodes’], bins=10, density = True)pdf = counts/(sum(counts))print(pdf);print(bin_edges);cdf = np.cumsum(pdf)plt.plot(bin_edges[1:],pdf);plt.plot(bin_edges[1:], cdf) Above code will give me the CDF of Long survival status. Here we only use cumsum function from Numpy which will cumulative sum up PDF of that feature. The CDF will of Long survival status is shown on plot in orange colour. From above CDF you can observe that orange line shows there is a 85% chance of long survival if number of axillary nodes detected are < 5. Also you can see as number of axillary nodes increases survival chances also reduces means it is clearly observed that 80% — 85% of people have good chances of survival if they have less no of auxillary nodes detected and as nodes increases the survival status also decreases as a result 100% of people have less chances of survival if nodes increases >40 Let’s try to plot CDF for both feature in a single plot. To do so just add below code in existing code written for Long Survival counts, bin_edges = np.histogram(haberman_Short_Survive['Axillary_Nodes'], bins=10, density = True)pdf = counts/(sum(counts))print(pdf);print(bin_edges)cdf = np.cumsum(pdf)plt.plot(bin_edges[1:],pdf)plt.plot(bin_edges[1:], cdf)plt.show(); Below image shows the CDF for short survival in Red line You can observe in above combine CDF for Long survival observation is same but in Short survival nearly 55% of people who have nodes less than 5 and there are nearly 100% of people in short survival if nodes are > 40 We can also predict patients status by applying mathematical formulae like Standard Deviation and Mean. Mean is the average of all data and Standard deviation is the spread of data means how much wide the data is spread along the data set. Python have Numpy library which can perform this operation in a single line. print(“Means:”)print (np.mean(haberman_Long_Survive[“Axillary_Nodes”]))print (np.mean(np.append(haberman_Long_Survive[“Axillary_Nodes”],50)))print (np.mean(haberman_Short_Survive[“Axillary_Nodes”]))print(“\nStandard Deviation:”)print(np.mean(haberman_Long_Survive[“Axillary_Nodes”]))print(np.mean(haberman_Short_Survive[“Axillary_Nodes”])) Here we can see in line 3, I have added outlier(data which is very large or small compare to respective data. It may be an error or exception case while collecting data) even though the mean of data is not much affected. You can observe that for Long survive mean is 2.79 and including outlier it is 3 that is almost same, but the mean of Short survive is 7.4 which is comparatively much higher than Long survive. So the probability for short survive is more in data set. If you observe the standard deviation Long survive has standard deviation of only 2.79 and Short survive has 7.45, means the spread of data for short survive is more. Some more mathematical operation you can do like Median, Quantiles, Percentile print(“Medians:”)print(np.median(haberman_Long_Survive[“Axillary_Nodes”]))print(np.median(np.append(haberman_Long_Survive[“Axillary_Nodes”],50)))print(np.median(haberman_Short_Survive[“Axillary_Nodes”]))print(“\nQuantiles:”)print(np.percentile(haberman_Long_Survive[“Axillary_Nodes”],np.arange(0,100,25)))print(np.percentile(haberman_Short_Survive[“Axillary_Nodes”],np.arange(0,100,25)))print(“\n90th percentile:”)print(np.percentile(haberman_Long_Survive[“Axillary_Nodes”],90))print(np.percentile(haberman_Short_Survive[“Axillary_Nodes”],90))from statsmodels import robustprint (“\nMedian Absolute Deviation”)print(robust.mad(haberman_Long_Survive[“Axillary_Nodes”]))print(robust.mad(haberman_Short_Survive[“Axillary_Nodes”])) Above code snippet will give you the Median Quantiles and nth Percentiles Median is the centre value of data and Quantiles are the value of specific feature on nth Percentage n= 25,50,75 and nth Percentile is similar to Quantiles but n could be any number from 1 to 100. So, for our data set we have values of these terms as follows Observation: From above observation it is clear that average axillary nodes in long survival is 0 and for short survival it is 4. ie, Patients who have average 4 auxillary nodes have short survival status.Quantiles shows that nearly 50th% of axillary nodes are 0 in long survival and 75th% of patients have nodes less than 3 that is 25% patients are having nodes more than 3.Similarly, In short survival 75th% of patients have minimum 11 nodes detected.At 90th% there if nodes detected is >8 then it has long survival status and if nodes are >20 then patients will have short survival status From above observation it is clear that average axillary nodes in long survival is 0 and for short survival it is 4. ie, Patients who have average 4 auxillary nodes have short survival status. Quantiles shows that nearly 50th% of axillary nodes are 0 in long survival and 75th% of patients have nodes less than 3 that is 25% patients are having nodes more than 3. Similarly, In short survival 75th% of patients have minimum 11 nodes detected. At 90th% there if nodes detected is >8 then it has long survival status and if nodes are >20 then patients will have short survival status You can also analysis data using plot like Box plot Contour and more, Seaborn library has wide variety of data plotting module. Let’s take some of them Box Plot and Whiskers sns.boxplot(x=”Survival_Status”,y=”Axillary_Nodes”, data=haberman)plt.show() Here you can read this plot by observing it’s box height and width and T like structure. height of box represents all data between 25th percentile to 75th percentile and that horizontal bar represents maximum range of that data and width of box represents spread of that data in data set. Also, the small point above that vertical bar are outliers Observation:In above box whiskers 25th percentile and 50th percentile are nearly same for Long survive and threshold for it is 0 to 7. Also, for short survival there are 50th percentile of nodes are nearly same as long survive 75th percentile. Threshold for the Short survival us 0 to 25 nodes and 75th% is 12 and 25th% is 1 or 2 So,if nodes between 0–7 have chances of error as short survival plot is also lies in it. That is 50% error for Short survival status There are most of point above 12 lies in Short survival Violin Plot sns.violinplot(x=”Survival_Status”, y=”Axillary_Nodes”,data=haberman)plt.legendplt.show() It is same as Box whiskers plot only difference is instead of box histogram will represents spread of data. Observation: In above violin plot we observe that For long survive density for it is more near the 0 nodes and also it has whiskers in range o-7 and in violin 2 it shows the short survival density more from 0–20 ans threshold from 0–12 Contour Plot Contour plots are like density plot means if the number of data is more on specific point that area will get darker and if you visualise it will make hill like structure where hill top has maximum density of point and density decreases as hill slope getting decreases. You can refer below plot how actually contour plot looks in 3D In above image the yellow point has maximum density. Below is the contour plot for our data set sns.jointplot(x=”Age”,y=”Axillary_Nodes”,data=haberman_Long_Survive,kind=”kde”)plt.grid()plt.show() Observation: Above is the 2D density plot for long survival using feature age and axillary nodes, it is observed the density of point for long survival is more from age range 47–60 and axillary nodes from 0–3. The dark area have major density which is hill top in 3D and density is getting low as graph get lighter. Each shade represent 1 contour plot. Yes, you can diagnose the Cancer using Haberman’s Data set by applying various data analysis techniques and using various Python libraries.
[ { "code": null, "e": 427, "s": 171, "text": "Haberman’s data set contains data from the study conducted in University of Chicago’s Billings Hospital between year 1958 to 1970 for the patients who undergone surgery of breast cancer. Source :https://www.kaggle.com/gilsousa/habermans-survival-data-set)" }, { "code": null, "e": 604, "s": 427, "text": "I would like to explain the various data analysis operation, I have done on this data set and how to conclude or predict survival status of patients who undergone from surgery." }, { "code": null, "e": 883, "s": 604, "text": "First of all for any data analysis task or for performing operation on data we should have good domain knowledge so that we can relate the data features and also can give accurate conclusion. So, I would like to explain the features of data set and how it affects other feature." }, { "code": null, "e": 1021, "s": 883, "text": "There are 4 attribute in this data set out of which 3 are features and 1 class attribute as below. Also, there are 306 instances of data." }, { "code": null, "e": 1091, "s": 1021, "text": "Number of Axillary nodes(Lymph Nodes)AgeOperation YearSurvival Status" }, { "code": null, "e": 1129, "s": 1091, "text": "Number of Axillary nodes(Lymph Nodes)" }, { "code": null, "e": 1133, "s": 1129, "text": "Age" }, { "code": null, "e": 1148, "s": 1133, "text": "Operation Year" }, { "code": null, "e": 1164, "s": 1148, "text": "Survival Status" }, { "code": null, "e": 1597, "s": 1164, "text": "Lymph Node: Lymph nodes are small, bean-shaped organs that act as filters along the lymph fluid channels. As lymph fluid leaves the breast and eventually goes back into the bloodstream, the lymph nodes try to catch and trap cancer cells before they reach other parts of the body. Having cancer cells in the lymph nodes under your arm suggests an increased risk of the cancer spreading.In our data it is axillary nodes detected(0–52)" }, { "code": null, "e": 1667, "s": 1597, "text": "(Source: https://www.breastcancer.org/symptoms/diagnosis/lymph_nodes)" }, { "code": null, "e": 1756, "s": 1667, "text": "Age: It represent the age of patient at which they undergone surgery (age from 30 to 83)" }, { "code": null, "e": 1827, "s": 1756, "text": "Operation year: Year in which patient was undergone surgery(1958–1969)" }, { "code": null, "e": 2066, "s": 1827, "text": "Survival Status: It represent whether patient survive more than 5 years or less after undergone through surgery.Here if patients survived 5 years or more is represented as 1 and patients who survived less than 5 years is represented as 2." }, { "code": null, "e": 2137, "s": 2066, "text": "So, lets get started to play with the data set and get the conclusion." }, { "code": null, "e": 2430, "s": 2137, "text": "I had used python for this purpose as it has the rich collection of machine learning libraries and mathematical operation. I will mostly use common packages as Pandas, Numpy, Matplotlib and seaborn which help me for mathematical operations and also plotting, importing and exporting of files." }, { "code": null, "e": 2557, "s": 2430, "text": "import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport numpy as nphaberman= pd.read_csv(“haberman.csv”)" }, { "code": null, "e": 2850, "s": 2557, "text": "In above snippet using the function read_csv from pandas packages you can import the data from csv file format .So, after importing the data set you need to check if data imported properly. Below code snippet will show the shape of data that is the number of columns and rows present in data." }, { "code": null, "e": 2872, "s": 2850, "text": "print(haberman.shape)" }, { "code": null, "e": 3133, "s": 2872, "text": "Here you can get confidence that the data you want get successfully imported which shows 306 instances of data and 4 attributes present as we see previously in introduction. You can even see the labels of columns present using a single line of code as follows." }, { "code": null, "e": 3157, "s": 3133, "text": "print(haberman.columns)" }, { "code": null, "e": 3436, "s": 3157, "text": "Here the dtype means data type which is object type for all columns present in data. Similarly you can also find the dtype of feature and class attribute and can find how many number of data points belongs to 1 class and how many to other just with simple line of code as below." }, { "code": null, "e": 3479, "s": 3436, "text": "haberman[“Survival_Status”].value_counts()" }, { "code": null, "e": 3640, "s": 3479, "text": "From above piece of code you can conclude that there are 225 patients out of 306 were survived more than 5 years and only 81 patients survived less than 5 years" }, { "code": null, "e": 3752, "s": 3640, "text": "Now lets plot some plots which give us more clarification of data so that we can easily come to the conclusion." }, { "code": null, "e": 3832, "s": 3752, "text": "haberman.plot(kind=’scatter’, x=’Axillary_Nodes’, y=’Age’) plt.grid()plt.show()" }, { "code": null, "e": 4038, "s": 3832, "text": "These above snippet will given me the scatter plot w.r.t the Nodes on x-axis and Age on y-axis.Our matplotlib library functions grid and show help me to plot data in grid and also to display it on console." }, { "code": null, "e": 4453, "s": 4038, "text": "Above scatter plot shows all data in overlap fashion and also in same colour due to which we are unable to distinguish between data and also there are possibilities that you may miss some of my data which may lead to wrong conclusion. So, to distinguish between the data we can use seaborn packages function which simply to distinguish data visually by allocating different colours to every classification feature." }, { "code": null, "e": 4607, "s": 4453, "text": "sns.set_style(‘whitegrid’)sns.FacetGrid(haberman, hue=”Survival_Status”, size=4) \\ .map(plt.scatter, “Axillary_Nodes”, “Age”) \\ .add_legend();plt.show();" }, { "code": null, "e": 4858, "s": 4607, "text": "In above snippet, I import functions from seaborn library like FacetGrid due to which we are able to distinguish between the data classification.Here blue dots represent survival more than 5 years and orange dots represent survival less than 5 years." }, { "code": null, "e": 5336, "s": 4858, "text": "As there are 3 features from which we can conclude our classification so how can we select any feature from all so that we can get output with less error rate. To do so we can use pairplots from seaborn to plot of various combination from which we can select best pair for our further operation and final conclusion. hue=”Survival_Status” will give on which feature you need to do classification. Below image shows the plotting of pairplots combination and code snippet for it." }, { "code": null, "e": 5487, "s": 5336, "text": "plt.close();sns.set_style(“whitegrid”);sns.pairplot(haberman, hue=”Survival_Status”, size=3, vars=[‘Age’,’Operation_Age’, ‘Axillary_Nodes’])plt.show()" }, { "code": null, "e": 5748, "s": 5487, "text": "Above image is the combinations plot of all features in data. These types of plot is know as pairplots. Plot 1,Plot 5 and Plot 9 are the histograms of all combinations of features which explain you the density of data by considering different features of data." }, { "code": null, "e": 6060, "s": 5748, "text": "Now lets take plot 1 by 1 and I will explain you that which data feature I will take for my further data analysis. I will take such a data which can show me distinguishable difference than any other data feature. So,lets start analysing each plot except plot 1,5,9 as it is a histogram of features in pairplots." }, { "code": null, "e": 6383, "s": 6060, "text": "Plot 2:-In this plot you can see that there is Operation Age on X-axis and Age on Y-axis and the plot of there data is mostly overlapping on each other data so we cannot distinguish if there is any orange point present below blue point or vice versa.So I am rejecting these 2 data feature combination for further analysis." }, { "code": null, "e": 6770, "s": 6383, "text": "Plot 3:-In this plot there are some points which is distinguishable but still it is better from other plot as we can provide conclusion more precisely by histogram and CDF which you will learn after a while. In this plot the overlap of points are there but still it is better than all other plots comparatively. So I will select the data feature of this plot ie. Age and Axillary nodes." }, { "code": null, "e": 6947, "s": 6770, "text": "Plot 4:- It is plotted using the data feature Operation Age and Age which shows similar type of plot like Plot 2 but it just rotated by 90 degree. So I also reject this feature" }, { "code": null, "e": 7169, "s": 6947, "text": "Plot 6:-It plot on the feature Operation Age and Axillary nodes which is somewhat similar to the Plot 2 but overlapping of points seems to be more in this plot comparative to other. So, I will also reject this combination" }, { "code": null, "e": 7341, "s": 7169, "text": "Plot 7:- This plot is similar as Plot 3 only feature interchange its axis so the plot will rotate by 90 degree. Also, I will accept this combination for further operations" }, { "code": null, "e": 7405, "s": 7341, "text": "Plot 8:- It is same as Plot 6 only feature on axis interchange." }, { "code": null, "e": 7519, "s": 7405, "text": "So, I consider the feature Age and Axillary nodes plotting in the Plot 3 and 7 for my all further data operations" }, { "code": null, "e": 7536, "s": 7519, "text": "1D-Scatter Plots" }, { "code": null, "e": 7625, "s": 7536, "text": "Lets plot 1D scatter plot and see if I can distinguish data by using below code snippet." }, { "code": null, "e": 8019, "s": 7625, "text": "import numpy as nphaberman_Long_Survive = haberman.loc[haberman[“Survival_Status”] == 1];haberman_Short_Survive = haberman.loc[haberman[“Survival_Status”] == 2];plt.plot(haberman_Long_Survive[“Axillary_Nodes”], np.zeros_like(haberman_Long_Survive[‘Axillary_Nodes’]), ‘o’)plt.plot(haberman_Short_Survive[“Axillary_Nodes”], np.zeros_like(haberman_Short_Survive[‘Axillary_Nodes’]), ‘o’)plt.show()" }, { "code": null, "e": 8197, "s": 8019, "text": "I used the Numpy library function to plot 1D scatter plot individually for every classified data. Below you can see the 1D scatter plot using data feature Age and Axillary nodes" }, { "code": null, "e": 8352, "s": 8197, "text": "Here you can observe the data of short survival status are mostly overlap on long survival status due to which you will not able to conclude on this data." }, { "code": null, "e": 8429, "s": 8352, "text": "You can get better clarification if you use PDF or CDF of data for plotting." }, { "code": null, "e": 8486, "s": 8429, "text": "Let me explain you concept of PDF and CDF in high level." }, { "code": null, "e": 8807, "s": 8486, "text": "PDF (Probability Density Function):- It shows the density of that data or number of data present on that point. PDF will be a peak like structure represents high peak if more number of data present or else it will be flat/ small peak if number of data present is less.It is smooth graph plot using the edges of histogram" }, { "code": null, "e": 8974, "s": 8807, "text": "CDF (Cumulative Distribution Function):- It is representation of cumulative data of PDF ie. it will plot a graph by considering PDF for every data point cumulatively." }, { "code": null, "e": 9152, "s": 8974, "text": "Seaborn library will help you to plot PDF and CDF of any data so that you can easily visualise the density of data present on specific point.Below code snippet will plot the PDF" }, { "code": null, "e": 9256, "s": 9152, "text": "sns.FacetGrid(haberman,hue=”Survival_Status”, size=8)\\.map(sns.distplot,”Axillary_Nodes”)\\.add_legend()" }, { "code": null, "e": 9344, "s": 9256, "text": "Lets try to plot PDF of each data feature and see which data give us maximum precision." }, { "code": null, "e": 9355, "s": 9344, "text": "PDF of Age" }, { "code": null, "e": 9524, "s": 9355, "text": "Observation: In above plot it is observed that at the age range from 30–75 the status of survival and death is same. So, using this datapoint we cannot predict anything" }, { "code": null, "e": 9545, "s": 9524, "text": "PDF of Operation Age" }, { "code": null, "e": 9735, "s": 9545, "text": "Observation: Similar here we cannot predict anything with these histograms as there is equal number of density in each data point. Even the PDF of both classification overlap on each other." }, { "code": null, "e": 9757, "s": 9735, "text": "PDF of Axillary Nodes" }, { "code": null, "e": 10027, "s": 9757, "text": "Observation: It has been observed that people survive long if they have less axillary nodes detected and vice versa but still it is hard to classify but this is the best data you can choose among all. So, I accept the PDF of Axillary nodes and can conclude below result" }, { "code": null, "e": 10047, "s": 10027, "text": "if(AxillaryNodes≤0)" }, { "code": null, "e": 10070, "s": 10047, "text": "Patient= Long survival" }, { "code": null, "e": 10125, "s": 10070, "text": "else if(AxillaryNodes≥0 && Axillary nodes≤3.5(approx))" }, { "code": null, "e": 10165, "s": 10125, "text": "Patient= Long survival chances are high" }, { "code": null, "e": 10194, "s": 10165, "text": "else if(Axillary nodes ≥3.5)" }, { "code": null, "e": 10219, "s": 10194, "text": "Patient = Short survival" }, { "code": null, "e": 10431, "s": 10219, "text": "So from above PDF we can say the patients survival status, but we cannot exactly say what percentage of patient will actually short survive or long survive. To know that we have another distribution that is CDF." }, { "code": null, "e": 10555, "s": 10431, "text": "CDF will give the cumulative plot of PDF so that you can calculate what are the exact percentage of patient survival status" }, { "code": null, "e": 10619, "s": 10555, "text": "Let’s plot CDF for our selected feature which is Axillary nodes" }, { "code": null, "e": 10849, "s": 10619, "text": "counts, bin_edges = np.histogram(haberman_Long_Survive[‘Axillary_Nodes’], bins=10, density = True)pdf = counts/(sum(counts))print(pdf);print(bin_edges);cdf = np.cumsum(pdf)plt.plot(bin_edges[1:],pdf);plt.plot(bin_edges[1:], cdf)" }, { "code": null, "e": 11000, "s": 10849, "text": "Above code will give me the CDF of Long survival status. Here we only use cumsum function from Numpy which will cumulative sum up PDF of that feature." }, { "code": null, "e": 11072, "s": 11000, "text": "The CDF will of Long survival status is shown on plot in orange colour." }, { "code": null, "e": 11567, "s": 11072, "text": "From above CDF you can observe that orange line shows there is a 85% chance of long survival if number of axillary nodes detected are < 5. Also you can see as number of axillary nodes increases survival chances also reduces means it is clearly observed that 80% — 85% of people have good chances of survival if they have less no of auxillary nodes detected and as nodes increases the survival status also decreases as a result 100% of people have less chances of survival if nodes increases >40" }, { "code": null, "e": 11696, "s": 11567, "text": "Let’s try to plot CDF for both feature in a single plot. To do so just add below code in existing code written for Long Survival" }, { "code": null, "e": 11968, "s": 11696, "text": "counts, bin_edges = np.histogram(haberman_Short_Survive['Axillary_Nodes'], bins=10, density = True)pdf = counts/(sum(counts))print(pdf);print(bin_edges)cdf = np.cumsum(pdf)plt.plot(bin_edges[1:],pdf)plt.plot(bin_edges[1:], cdf)plt.show();" }, { "code": null, "e": 12025, "s": 11968, "text": "Below image shows the CDF for short survival in Red line" }, { "code": null, "e": 12242, "s": 12025, "text": "You can observe in above combine CDF for Long survival observation is same but in Short survival nearly 55% of people who have nodes less than 5 and there are nearly 100% of people in short survival if nodes are > 40" }, { "code": null, "e": 12346, "s": 12242, "text": "We can also predict patients status by applying mathematical formulae like Standard Deviation and Mean." }, { "code": null, "e": 12559, "s": 12346, "text": "Mean is the average of all data and Standard deviation is the spread of data means how much wide the data is spread along the data set. Python have Numpy library which can perform this operation in a single line." }, { "code": null, "e": 12899, "s": 12559, "text": "print(“Means:”)print (np.mean(haberman_Long_Survive[“Axillary_Nodes”]))print (np.mean(np.append(haberman_Long_Survive[“Axillary_Nodes”],50)))print (np.mean(haberman_Short_Survive[“Axillary_Nodes”]))print(“\\nStandard Deviation:”)print(np.mean(haberman_Long_Survive[“Axillary_Nodes”]))print(np.mean(haberman_Short_Survive[“Axillary_Nodes”]))" }, { "code": null, "e": 13120, "s": 12899, "text": "Here we can see in line 3, I have added outlier(data which is very large or small compare to respective data. It may be an error or exception case while collecting data) even though the mean of data is not much affected." }, { "code": null, "e": 13371, "s": 13120, "text": "You can observe that for Long survive mean is 2.79 and including outlier it is 3 that is almost same, but the mean of Short survive is 7.4 which is comparatively much higher than Long survive. So the probability for short survive is more in data set." }, { "code": null, "e": 13538, "s": 13371, "text": "If you observe the standard deviation Long survive has standard deviation of only 2.79 and Short survive has 7.45, means the spread of data for short survive is more." }, { "code": null, "e": 13617, "s": 13538, "text": "Some more mathematical operation you can do like Median, Quantiles, Percentile" }, { "code": null, "e": 14345, "s": 13617, "text": "print(“Medians:”)print(np.median(haberman_Long_Survive[“Axillary_Nodes”]))print(np.median(np.append(haberman_Long_Survive[“Axillary_Nodes”],50)))print(np.median(haberman_Short_Survive[“Axillary_Nodes”]))print(“\\nQuantiles:”)print(np.percentile(haberman_Long_Survive[“Axillary_Nodes”],np.arange(0,100,25)))print(np.percentile(haberman_Short_Survive[“Axillary_Nodes”],np.arange(0,100,25)))print(“\\n90th percentile:”)print(np.percentile(haberman_Long_Survive[“Axillary_Nodes”],90))print(np.percentile(haberman_Short_Survive[“Axillary_Nodes”],90))from statsmodels import robustprint (“\\nMedian Absolute Deviation”)print(robust.mad(haberman_Long_Survive[“Axillary_Nodes”]))print(robust.mad(haberman_Short_Survive[“Axillary_Nodes”]))" }, { "code": null, "e": 14419, "s": 14345, "text": "Above code snippet will give you the Median Quantiles and nth Percentiles" }, { "code": null, "e": 14616, "s": 14419, "text": "Median is the centre value of data and Quantiles are the value of specific feature on nth Percentage n= 25,50,75 and nth Percentile is similar to Quantiles but n could be any number from 1 to 100." }, { "code": null, "e": 14678, "s": 14616, "text": "So, for our data set we have values of these terms as follows" }, { "code": null, "e": 14691, "s": 14678, "text": "Observation:" }, { "code": null, "e": 15270, "s": 14691, "text": "From above observation it is clear that average axillary nodes in long survival is 0 and for short survival it is 4. ie, Patients who have average 4 auxillary nodes have short survival status.Quantiles shows that nearly 50th% of axillary nodes are 0 in long survival and 75th% of patients have nodes less than 3 that is 25% patients are having nodes more than 3.Similarly, In short survival 75th% of patients have minimum 11 nodes detected.At 90th% there if nodes detected is >8 then it has long survival status and if nodes are >20 then patients will have short survival status" }, { "code": null, "e": 15463, "s": 15270, "text": "From above observation it is clear that average axillary nodes in long survival is 0 and for short survival it is 4. ie, Patients who have average 4 auxillary nodes have short survival status." }, { "code": null, "e": 15634, "s": 15463, "text": "Quantiles shows that nearly 50th% of axillary nodes are 0 in long survival and 75th% of patients have nodes less than 3 that is 25% patients are having nodes more than 3." }, { "code": null, "e": 15713, "s": 15634, "text": "Similarly, In short survival 75th% of patients have minimum 11 nodes detected." }, { "code": null, "e": 15852, "s": 15713, "text": "At 90th% there if nodes detected is >8 then it has long survival status and if nodes are >20 then patients will have short survival status" }, { "code": null, "e": 16004, "s": 15852, "text": "You can also analysis data using plot like Box plot Contour and more, Seaborn library has wide variety of data plotting module. Let’s take some of them" }, { "code": null, "e": 16026, "s": 16004, "text": "Box Plot and Whiskers" }, { "code": null, "e": 16103, "s": 16026, "text": "sns.boxplot(x=”Survival_Status”,y=”Axillary_Nodes”, data=haberman)plt.show()" }, { "code": null, "e": 16451, "s": 16103, "text": "Here you can read this plot by observing it’s box height and width and T like structure. height of box represents all data between 25th percentile to 75th percentile and that horizontal bar represents maximum range of that data and width of box represents spread of that data in data set. Also, the small point above that vertical bar are outliers" }, { "code": null, "e": 16781, "s": 16451, "text": "Observation:In above box whiskers 25th percentile and 50th percentile are nearly same for Long survive and threshold for it is 0 to 7. Also, for short survival there are 50th percentile of nodes are nearly same as long survive 75th percentile. Threshold for the Short survival us 0 to 25 nodes and 75th% is 12 and 25th% is 1 or 2" }, { "code": null, "e": 16914, "s": 16781, "text": "So,if nodes between 0–7 have chances of error as short survival plot is also lies in it. That is 50% error for Short survival status" }, { "code": null, "e": 16970, "s": 16914, "text": "There are most of point above 12 lies in Short survival" }, { "code": null, "e": 16982, "s": 16970, "text": "Violin Plot" }, { "code": null, "e": 17072, "s": 16982, "text": "sns.violinplot(x=”Survival_Status”, y=”Axillary_Nodes”,data=haberman)plt.legendplt.show()" }, { "code": null, "e": 17180, "s": 17072, "text": "It is same as Box whiskers plot only difference is instead of box histogram will represents spread of data." }, { "code": null, "e": 17416, "s": 17180, "text": "Observation: In above violin plot we observe that For long survive density for it is more near the 0 nodes and also it has whiskers in range o-7 and in violin 2 it shows the short survival density more from 0–20 ans threshold from 0–12" }, { "code": null, "e": 17429, "s": 17416, "text": "Contour Plot" }, { "code": null, "e": 17698, "s": 17429, "text": "Contour plots are like density plot means if the number of data is more on specific point that area will get darker and if you visualise it will make hill like structure where hill top has maximum density of point and density decreases as hill slope getting decreases." }, { "code": null, "e": 17761, "s": 17698, "text": "You can refer below plot how actually contour plot looks in 3D" }, { "code": null, "e": 17814, "s": 17761, "text": "In above image the yellow point has maximum density." }, { "code": null, "e": 17857, "s": 17814, "text": "Below is the contour plot for our data set" }, { "code": null, "e": 17957, "s": 17857, "text": "sns.jointplot(x=”Age”,y=”Axillary_Nodes”,data=haberman_Long_Survive,kind=”kde”)plt.grid()plt.show()" }, { "code": null, "e": 18310, "s": 17957, "text": "Observation: Above is the 2D density plot for long survival using feature age and axillary nodes, it is observed the density of point for long survival is more from age range 47–60 and axillary nodes from 0–3. The dark area have major density which is hill top in 3D and density is getting low as graph get lighter. Each shade represent 1 contour plot." } ]
Building a real-time web app in NodeJS Express with Socket.io library | by Charmaine Chui | Towards Data Science
To gain a deeper understanding of the travelling patterns among public transportation commuters, I had been tasked a few months ago to perform an analysis which involves trip chaining a series of bus journeys. While I had initially built a Bus Route Visualisation Site for the sole purpose of exporting custom bus route data based on specific Origin-Destination pairings selected: I later decided to further explore and leverage on the data provider’s public API which includes returning the real-time bus arrival timings at any specific bus stop. In short, I was curious about what other data fields the API includes in its real-time responses 🤔 While there are alternative libraries which are capable of integrating real-time data streaming within a web app, my primary reason for implementing Socket.io is because it not only serves its functionality of establishing a Web socket bidirectional connection between Server + Client but also, both Server & Client code implementations are written in JavaScript so there is no need to switch back and forth between 2 languages while coding the application’s backend and frontend. For starters, within an Express NodeJS web app, the server-side of the code conventionally refers to the app.js/server.js file i.e. the entry point of the web application where an instance of Express.js is being initialised. After installing the NodeJS Socket.io library via npm install socket.io, the server-side code implementation is as follows: 1. The library socket.io is imported via: const socketio=require("socket.io") 2. Any web socket instance has by default the namespace disconnect— which emits a message back to the server if the instance has disconnected from the frontend (usually due to disconnection from its web server) 3. The custom namespaces bus_arrivalsand get_bus_arrivals_info shall subsequently correspond to the exact same namespaces (KIV) from the client-side such that in the event multiple socket channels are present, the web socket instance would be able to identify based on namespaces which messages to emit to which channels. 4*. After the app instance is created from Express NodeJS library, a server instance which wraps around the app instance is initialised via: const server = http.createServer(app) ⚠ This is extremely important to note since both app and server instances have completely separate functions. While contents of the web app are being served by the app instance, the actual web socket connection is in fact running on the server instance which is denoted by: const io = socketio(server) Following up from point 3 of the above implementation, recall that the namespaces bus_arrivalsand get_bus_arrivals_info are specified for 2 web socket channels: To enable a client-side instance of the web socket to be initialised, the JavaScript browser library for socket.io must be included: <script type=”text/javascript” src=”js/socket.io.js”></script>` before the following code snippet to implement Socket.io is embedded within the browser’s JavaScript content: Server-Side NPM Package: socket.io v4.1.3 Client-Side JavaScript Library: Socket.IO v4.1.3 For more information to determine if the NPM package you have installed is compatible with the JavaScript library you have imported on the browser, please refer to Socket.io’s official site. Finally, after deciding which data fields of the Bus Arrival information should be included for display, the following is the layout I decided to implement: And there you go! The Bus ETAs would now be re-rendered every 10 seconds (can be customised) to reflect the latest updates! 🤩 FYI: For the full source code please head to my GitHub repo. The web app is currently deployed at: https://sg-transportation.herokuapp.com/ Hope the above illustrations of implementing Socket.io in NodeJS has been useful and many thanks for reading! ❤ Please follow me on medium if you would like to read my other upcoming recounts of tackling challenges at work (both people and technical issues)! Would really appreciate it 😀
[ { "code": null, "e": 553, "s": 172, "text": "To gain a deeper understanding of the travelling patterns among public transportation commuters, I had been tasked a few months ago to perform an analysis which involves trip chaining a series of bus journeys. While I had initially built a Bus Route Visualisation Site for the sole purpose of exporting custom bus route data based on specific Origin-Destination pairings selected:" }, { "code": null, "e": 819, "s": 553, "text": "I later decided to further explore and leverage on the data provider’s public API which includes returning the real-time bus arrival timings at any specific bus stop. In short, I was curious about what other data fields the API includes in its real-time responses 🤔" }, { "code": null, "e": 1300, "s": 819, "text": "While there are alternative libraries which are capable of integrating real-time data streaming within a web app, my primary reason for implementing Socket.io is because it not only serves its functionality of establishing a Web socket bidirectional connection between Server + Client but also, both Server & Client code implementations are written in JavaScript so there is no need to switch back and forth between 2 languages while coding the application’s backend and frontend." }, { "code": null, "e": 1649, "s": 1300, "text": "For starters, within an Express NodeJS web app, the server-side of the code conventionally refers to the app.js/server.js file i.e. the entry point of the web application where an instance of Express.js is being initialised. After installing the NodeJS Socket.io library via npm install socket.io, the server-side code implementation is as follows:" }, { "code": null, "e": 1691, "s": 1649, "text": "1. The library socket.io is imported via:" }, { "code": null, "e": 1727, "s": 1691, "text": "const socketio=require(\"socket.io\")" }, { "code": null, "e": 1938, "s": 1727, "text": "2. Any web socket instance has by default the namespace disconnect— which emits a message back to the server if the instance has disconnected from the frontend (usually due to disconnection from its web server)" }, { "code": null, "e": 2260, "s": 1938, "text": "3. The custom namespaces bus_arrivalsand get_bus_arrivals_info shall subsequently correspond to the exact same namespaces (KIV) from the client-side such that in the event multiple socket channels are present, the web socket instance would be able to identify based on namespaces which messages to emit to which channels." }, { "code": null, "e": 2401, "s": 2260, "text": "4*. After the app instance is created from Express NodeJS library, a server instance which wraps around the app instance is initialised via:" }, { "code": null, "e": 2439, "s": 2401, "text": "const server = http.createServer(app)" }, { "code": null, "e": 2713, "s": 2439, "text": "⚠ This is extremely important to note since both app and server instances have completely separate functions. While contents of the web app are being served by the app instance, the actual web socket connection is in fact running on the server instance which is denoted by:" }, { "code": null, "e": 2741, "s": 2713, "text": "const io = socketio(server)" }, { "code": null, "e": 2902, "s": 2741, "text": "Following up from point 3 of the above implementation, recall that the namespaces bus_arrivalsand get_bus_arrivals_info are specified for 2 web socket channels:" }, { "code": null, "e": 3035, "s": 2902, "text": "To enable a client-side instance of the web socket to be initialised, the JavaScript browser library for socket.io must be included:" }, { "code": null, "e": 3099, "s": 3035, "text": "<script type=”text/javascript” src=”js/socket.io.js”></script>`" }, { "code": null, "e": 3209, "s": 3099, "text": "before the following code snippet to implement Socket.io is embedded within the browser’s JavaScript content:" }, { "code": null, "e": 3251, "s": 3209, "text": "Server-Side NPM Package: socket.io v4.1.3" }, { "code": null, "e": 3300, "s": 3251, "text": "Client-Side JavaScript Library: Socket.IO v4.1.3" }, { "code": null, "e": 3491, "s": 3300, "text": "For more information to determine if the NPM package you have installed is compatible with the JavaScript library you have imported on the browser, please refer to Socket.io’s official site." }, { "code": null, "e": 3648, "s": 3491, "text": "Finally, after deciding which data fields of the Bus Arrival information should be included for display, the following is the layout I decided to implement:" }, { "code": null, "e": 3774, "s": 3648, "text": "And there you go! The Bus ETAs would now be re-rendered every 10 seconds (can be customised) to reflect the latest updates! 🤩" }, { "code": null, "e": 3914, "s": 3774, "text": "FYI: For the full source code please head to my GitHub repo. The web app is currently deployed at: https://sg-transportation.herokuapp.com/" } ]
How to set the opacity level for an element with JavaScript?
Use the opacity property in JavaScript to set the opacity level. You can try to run the following code to set the opacity level for an element with JavaScript − Live Demo <!DOCTYPE html> <html> <head> <style> #box { width: 450px; background-color: gray; } </style> </head> <body> <p>Click below to set Opacity.</p> <button type="button" onclick="display()">Set Opacity</button> <div id="box"> <p>This is a div. This is a div. This is a div. This is a div. This is a div.</p> <p>This is a div. This is a div. This is a div. This is a div. This is a div.</p> <p>This is a div. This is a div. This is a div. This is a div. This is a div.</p> </div> <br> <script> function display() { document.getElementById("box").style.opacity = "0.5"; } </script> </body> </html>
[ { "code": null, "e": 1223, "s": 1062, "text": "Use the opacity property in JavaScript to set the opacity level. You can try to run the following code to set the opacity level for an element with JavaScript −" }, { "code": null, "e": 1233, "s": 1223, "text": "Live Demo" }, { "code": null, "e": 1990, "s": 1233, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #box {\n width: 450px;\n background-color: gray;\n }\n </style>\n </head>\n <body>\n <p>Click below to set Opacity.</p>\n <button type=\"button\" onclick=\"display()\">Set Opacity</button>\n <div id=\"box\">\n <p>This is a div. This is a div. This is a div. This is a div. This is a div.</p>\n <p>This is a div. This is a div. This is a div. This is a div. This is a div.</p>\n <p>This is a div. This is a div. This is a div. This is a div. This is a div.</p>\n </div>\n <br>\n <script>\n function display() {\n document.getElementById(\"box\").style.opacity = \"0.5\";\n }\n </script>\n </body>\n</html>" } ]
How to get the square root of a number in JavaScript?
To get the square root, use the Math.sqrt() method. This method returns the square root of a number. If the value of a number is negative, sqrt returns NaN. You can try to run the following code to get the square root of a number − <html> <head> <title>JavaScript Math sqrt() Method</title> </head> <body> <script> var value = Math.sqrt( 0.5 ); document.write("First Value : " + value ); var value = Math.sqrt( 49 ); document.write("<br />Second Value : " + value ); </script> </body> </html>
[ { "code": null, "e": 1344, "s": 1187, "text": "To get the square root, use the Math.sqrt() method. This method returns the square root of a number. If the value of a number is negative, sqrt returns NaN." }, { "code": null, "e": 1419, "s": 1344, "text": "You can try to run the following code to get the square root of a number −" }, { "code": null, "e": 1747, "s": 1419, "text": "<html>\n <head>\n <title>JavaScript Math sqrt() Method</title>\n </head>\n <body>\n <script>\n var value = Math.sqrt( 0.5 );\n document.write(\"First Value : \" + value );\n\n var value = Math.sqrt( 49 );\n document.write(\"<br />Second Value : \" + value );\n </script>\n </body>\n</html>" } ]
ListIterator in Java
31 May, 2022 ListIterator is one of the four java cursors. It is a java iterator that is used to traverse all types of lists including ArrayList, Vector, LinkedList, Stack, etc. It is available since Java 1.2. It extends the iterator interface. The hierarchy of ListIterator is as follows: Some Important points about ListIterator It is useful for list implemented classes.Available since java 1.2.It supports bi-directional traversal. i.e both forward and backward directions.It supports all the four CRUD operations(Create, Read, Update, Delete) operations. It is useful for list implemented classes. Available since java 1.2. It supports bi-directional traversal. i.e both forward and backward directions. It supports all the four CRUD operations(Create, Read, Update, Delete) operations. There is no current element in ListIterator. Its cursor always lies between the previous and next elements. The previous() will return to the previous elements and the next() will return to the next element. Therefore, for a list of n length, there are n+1 possible cursors. Syntax: Declaration public interface ListIterator<E> extends Iterator<E> Where E represents the generic type i.e any parameter of any type/user-defined object. Syntax: To get a list Iterator on a list ListIterator<E> listIterator() This returns the list iterator of all the elements of the list. Example: Java // Java Program to Show the Usage of listIterator import java.util.*; public class ListIteratorDemo { // Main driver method public static void main(String[] args) { // Creating a list of names List<String> names = new LinkedList<>(); names.add("Welcome"); names.add("To"); names.add("Gfg"); // Getting ListIterator ListIterator<String> namesIterator = names.listIterator(); // Traversing elements using next() method while (namesIterator.hasNext()) { System.out.println(namesIterator.next()); } // for-each loop creates Internal Iterator here. for (String s : names) { System.out.println(s); } }} Welcome To Gfg Welcome To Gfg 1. Forward direction iteration hasNext(): This method returns true when the list has more elements to traverse while traversing in the forward direction next(): This method returns the next element of the list and advances the position of the cursor. nextIndex(): This method returns the index of the element that would be returned on calling the next() function. 2. Backward direction iteration hasPrevious(): This method returns true when the list has more elements to traverse while traversing in the reverse direction previous(): This method returns the previous element of the list and shifts the cursor one position backward. previousIndex(): This method returns the index of the element that would be returned on calling the previous() function. Example code showing both forward and backward direction iterations using list Iterator: Java // Java Program to traverse the list both in forward and// backward direction using listIterator import java.util.*; public class GFG { public static void main(String[] args) { // list of names List<String> names = new LinkedList<>(); names.add("learn"); names.add("from"); names.add("Geeksforgeeks"); // Getting ListIterator ListIterator<String> listIterator = names.listIterator(); // Traversing elements System.out.println("Forward Direction Iteration:"); while (listIterator.hasNext()) { System.out.println(listIterator.next()); } // Traversing elements, the iterator is at the end // at this point System.out.println("Backward Direction Iteration:"); while (listIterator.hasPrevious()) { System.out.println(listIterator.previous()); } }} Forward Direction Iteration: learn from Geeksforgeeks Backward Direction Iteration: Geeksforgeeks from learn A. listIterator(): The listIterator() method of java.util.ArrayList class is used to return a list iterator over the elements in this list (in proper sequence). The returned list iterator is fail-fast. Syntax: public ListIterator listIterator() Return Value: This method returns a list iterator over the elements in this list (in proper sequence). B. listIterator(int index) This listIterator(int index) method is used to return a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. The specified index indicates the first element that would be returned by an initial call to next. An initial call to the previous would return the element with the specified index minus one. The returned list iterator is fail-fast. Syntax: public ListIterator listIterator(int index) Parameters: This method takes the index of the first element as a parameter to be returned from the list iterator (by a call to next) Return Value: This method returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. Exception: This method throws IndexOutOfBoundsException if the index is out of range (index size()). Advantages: It supports all four CRUD (Create, Read, Update, Delete) operations. It supports Bi-directional traversing i.e both forward and backward direction iteration. Simple method names are easy to use. Limitations: This iterator is only for list implementation classes. Not a universal cursor. It is not applicable to all collection API. Parallel iteration of elements is not supported by the list Iterator. listiterator does not support the good performance of numerous elements iteration. Similarities: They both are introduced in java 1.2. They both are used for iteration lists. They both support forward direction traversal. They both supports READ and DELETE operations. Differences: Iterator ListIterator Method Description Method Description arcsinrad3 sankarsanpakhira Java-Iterator Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n31 May, 2022" }, { "code": null, "e": 332, "s": 54, "text": "ListIterator is one of the four java cursors. It is a java iterator that is used to traverse all types of lists including ArrayList, Vector, LinkedList, Stack, etc. It is available since Java 1.2. It extends the iterator interface. The hierarchy of ListIterator is as follows: " }, { "code": null, "e": 373, "s": 332, "text": "Some Important points about ListIterator" }, { "code": null, "e": 602, "s": 373, "text": "It is useful for list implemented classes.Available since java 1.2.It supports bi-directional traversal. i.e both forward and backward directions.It supports all the four CRUD operations(Create, Read, Update, Delete) operations." }, { "code": null, "e": 645, "s": 602, "text": "It is useful for list implemented classes." }, { "code": null, "e": 671, "s": 645, "text": "Available since java 1.2." }, { "code": null, "e": 751, "s": 671, "text": "It supports bi-directional traversal. i.e both forward and backward directions." }, { "code": null, "e": 834, "s": 751, "text": "It supports all the four CRUD operations(Create, Read, Update, Delete) operations." }, { "code": null, "e": 1109, "s": 834, "text": "There is no current element in ListIterator. Its cursor always lies between the previous and next elements. The previous() will return to the previous elements and the next() will return to the next element. Therefore, for a list of n length, there are n+1 possible cursors." }, { "code": null, "e": 1129, "s": 1109, "text": "Syntax: Declaration" }, { "code": null, "e": 1182, "s": 1129, "text": "public interface ListIterator<E> extends Iterator<E>" }, { "code": null, "e": 1269, "s": 1182, "text": "Where E represents the generic type i.e any parameter of any type/user-defined object." }, { "code": null, "e": 1310, "s": 1269, "text": "Syntax: To get a list Iterator on a list" }, { "code": null, "e": 1343, "s": 1310, "text": "ListIterator<E> listIterator() " }, { "code": null, "e": 1407, "s": 1343, "text": "This returns the list iterator of all the elements of the list." }, { "code": null, "e": 1416, "s": 1407, "text": "Example:" }, { "code": null, "e": 1421, "s": 1416, "text": "Java" }, { "code": "// Java Program to Show the Usage of listIterator import java.util.*; public class ListIteratorDemo { // Main driver method public static void main(String[] args) { // Creating a list of names List<String> names = new LinkedList<>(); names.add(\"Welcome\"); names.add(\"To\"); names.add(\"Gfg\"); // Getting ListIterator ListIterator<String> namesIterator = names.listIterator(); // Traversing elements using next() method while (namesIterator.hasNext()) { System.out.println(namesIterator.next()); } // for-each loop creates Internal Iterator here. for (String s : names) { System.out.println(s); } }}", "e": 2167, "s": 1421, "text": null }, { "code": null, "e": 2197, "s": 2167, "text": "Welcome\nTo\nGfg\nWelcome\nTo\nGfg" }, { "code": null, "e": 2228, "s": 2197, "text": "1. Forward direction iteration" }, { "code": null, "e": 2350, "s": 2228, "text": "hasNext(): This method returns true when the list has more elements to traverse while traversing in the forward direction" }, { "code": null, "e": 2448, "s": 2350, "text": "next(): This method returns the next element of the list and advances the position of the cursor." }, { "code": null, "e": 2561, "s": 2448, "text": "nextIndex(): This method returns the index of the element that would be returned on calling the next() function." }, { "code": null, "e": 2593, "s": 2561, "text": "2. Backward direction iteration" }, { "code": null, "e": 2719, "s": 2593, "text": "hasPrevious(): This method returns true when the list has more elements to traverse while traversing in the reverse direction" }, { "code": null, "e": 2829, "s": 2719, "text": "previous(): This method returns the previous element of the list and shifts the cursor one position backward." }, { "code": null, "e": 2950, "s": 2829, "text": "previousIndex(): This method returns the index of the element that would be returned on calling the previous() function." }, { "code": null, "e": 3039, "s": 2950, "text": "Example code showing both forward and backward direction iterations using list Iterator:" }, { "code": null, "e": 3044, "s": 3039, "text": "Java" }, { "code": "// Java Program to traverse the list both in forward and// backward direction using listIterator import java.util.*; public class GFG { public static void main(String[] args) { // list of names List<String> names = new LinkedList<>(); names.add(\"learn\"); names.add(\"from\"); names.add(\"Geeksforgeeks\"); // Getting ListIterator ListIterator<String> listIterator = names.listIterator(); // Traversing elements System.out.println(\"Forward Direction Iteration:\"); while (listIterator.hasNext()) { System.out.println(listIterator.next()); } // Traversing elements, the iterator is at the end // at this point System.out.println(\"Backward Direction Iteration:\"); while (listIterator.hasPrevious()) { System.out.println(listIterator.previous()); } }}", "e": 3949, "s": 3044, "text": null }, { "code": null, "e": 4058, "s": 3949, "text": "Forward Direction Iteration:\nlearn\nfrom\nGeeksforgeeks\nBackward Direction Iteration:\nGeeksforgeeks\nfrom\nlearn" }, { "code": null, "e": 4260, "s": 4058, "text": "A. listIterator(): The listIterator() method of java.util.ArrayList class is used to return a list iterator over the elements in this list (in proper sequence). The returned list iterator is fail-fast." }, { "code": null, "e": 4268, "s": 4260, "text": "Syntax:" }, { "code": null, "e": 4303, "s": 4268, "text": "public ListIterator listIterator()" }, { "code": null, "e": 4406, "s": 4303, "text": "Return Value: This method returns a list iterator over the elements in this list (in proper sequence)." }, { "code": null, "e": 4433, "s": 4406, "text": "B. listIterator(int index)" }, { "code": null, "e": 4837, "s": 4433, "text": "This listIterator(int index) method is used to return a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. The specified index indicates the first element that would be returned by an initial call to next. An initial call to the previous would return the element with the specified index minus one. The returned list iterator is fail-fast." }, { "code": null, "e": 4845, "s": 4837, "text": "Syntax:" }, { "code": null, "e": 4889, "s": 4845, "text": "public ListIterator listIterator(int index)" }, { "code": null, "e": 5023, "s": 4889, "text": "Parameters: This method takes the index of the first element as a parameter to be returned from the list iterator (by a call to next)" }, { "code": null, "e": 5174, "s": 5023, "text": "Return Value: This method returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list." }, { "code": null, "e": 5275, "s": 5174, "text": "Exception: This method throws IndexOutOfBoundsException if the index is out of range (index size())." }, { "code": null, "e": 5287, "s": 5275, "text": "Advantages:" }, { "code": null, "e": 5356, "s": 5287, "text": "It supports all four CRUD (Create, Read, Update, Delete) operations." }, { "code": null, "e": 5445, "s": 5356, "text": "It supports Bi-directional traversing i.e both forward and backward direction iteration." }, { "code": null, "e": 5482, "s": 5445, "text": "Simple method names are easy to use." }, { "code": null, "e": 5495, "s": 5482, "text": "Limitations:" }, { "code": null, "e": 5550, "s": 5495, "text": "This iterator is only for list implementation classes." }, { "code": null, "e": 5574, "s": 5550, "text": "Not a universal cursor." }, { "code": null, "e": 5618, "s": 5574, "text": "It is not applicable to all collection API." }, { "code": null, "e": 5688, "s": 5618, "text": "Parallel iteration of elements is not supported by the list Iterator." }, { "code": null, "e": 5771, "s": 5688, "text": "listiterator does not support the good performance of numerous elements iteration." }, { "code": null, "e": 5785, "s": 5771, "text": "Similarities:" }, { "code": null, "e": 5823, "s": 5785, "text": "They both are introduced in java 1.2." }, { "code": null, "e": 5863, "s": 5823, "text": "They both are used for iteration lists." }, { "code": null, "e": 5910, "s": 5863, "text": "They both support forward direction traversal." }, { "code": null, "e": 5957, "s": 5910, "text": "They both supports READ and DELETE operations." }, { "code": null, "e": 5970, "s": 5957, "text": "Differences:" }, { "code": null, "e": 5995, "s": 5970, "text": " Iterator" }, { "code": null, "e": 6051, "s": 5995, "text": " ListIterator" }, { "code": null, "e": 6058, "s": 6051, "text": "Method" }, { "code": null, "e": 6070, "s": 6058, "text": "Description" }, { "code": null, "e": 6077, "s": 6070, "text": "Method" }, { "code": null, "e": 6089, "s": 6077, "text": "Description" }, { "code": null, "e": 6100, "s": 6089, "text": "arcsinrad3" }, { "code": null, "e": 6117, "s": 6100, "text": "sankarsanpakhira" }, { "code": null, "e": 6131, "s": 6117, "text": "Java-Iterator" }, { "code": null, "e": 6136, "s": 6131, "text": "Java" }, { "code": null, "e": 6141, "s": 6136, "text": "Java" }, { "code": null, "e": 6239, "s": 6141, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6290, "s": 6239, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 6321, "s": 6290, "text": "How to iterate any Map in Java" }, { "code": null, "e": 6340, "s": 6321, "text": "Interfaces in Java" }, { "code": null, "e": 6370, "s": 6340, "text": "HashMap in Java with Examples" }, { "code": null, "e": 6385, "s": 6370, "text": "Stream In Java" }, { "code": null, "e": 6403, "s": 6385, "text": "ArrayList in Java" }, { "code": null, "e": 6423, "s": 6403, "text": "Collections in Java" }, { "code": null, "e": 6447, "s": 6423, "text": "Singleton Class in Java" }, { "code": null, "e": 6479, "s": 6447, "text": "Multidimensional Arrays in Java" } ]
Concatenating Objects in R Programming – combine() Function
31 Aug, 2020 In R programming, coercion function c() and combine() function are similar to each other but are different in a way. combine() functions acts like c() and unlist() functions but uses consistent dplyr coercion rules. Moreover, combine() function is used to combine factors in R programming. In this article, we’ll see the implementation of combine() and c() function with same outputs and different outputs on the same operation. Syntax: combine(x, y, ...) Parameters:x, y, .... are vectors to combine Example 1: In this example, we’ll see the same output of both these functions on same operation. # Package requiredinstall.packages("dplyr") # Load the librarylibrary(dplyr) x <- c(1, 2, 3)y <- c(4, 5, 6) # Using c() functioncat("Using c() function:\n")c(x, y) cat("\n")# Using combine() functioncat("Using combine() function:\n")combine(x, y) Output: Using c() function: [1] 1 2 3 4 5 6 Using combine() function: [1] 1 2 3 4 5 6 Example 2:In this example, we’ll see the different outputs of both these functions on the same operation. library(dplyr) x <- factor(c("a", "a", "b", "c"))y <- factor(c("b", "a", "c", "b")) # Using c() functioncat("Using c() function:\n")c(x, y) # Using combine() functioncat("\n")cat("Using combine() function:\n")combine(x, y) Output: Using c() function: [1] 1 1 2 3 2 1 3 2 Using combine() function: [1] a a b c b a c b Levels: a b c Akanksha_Rai R DataFrame-Function R List-Function R Matrix-Function R Object-Function R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R Loops in R (for, while, repeat) How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? Logistic Regression in R Programming R - if statement
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Aug, 2020" }, { "code": null, "e": 457, "s": 28, "text": "In R programming, coercion function c() and combine() function are similar to each other but are different in a way. combine() functions acts like c() and unlist() functions but uses consistent dplyr coercion rules. Moreover, combine() function is used to combine factors in R programming. In this article, we’ll see the implementation of combine() and c() function with same outputs and different outputs on the same operation." }, { "code": null, "e": 484, "s": 457, "text": "Syntax: combine(x, y, ...)" }, { "code": null, "e": 529, "s": 484, "text": "Parameters:x, y, .... are vectors to combine" }, { "code": null, "e": 540, "s": 529, "text": "Example 1:" }, { "code": null, "e": 626, "s": 540, "text": "In this example, we’ll see the same output of both these functions on same operation." }, { "code": "# Package requiredinstall.packages(\"dplyr\") # Load the librarylibrary(dplyr) x <- c(1, 2, 3)y <- c(4, 5, 6) # Using c() functioncat(\"Using c() function:\\n\")c(x, y) cat(\"\\n\")# Using combine() functioncat(\"Using combine() function:\\n\")combine(x, y)", "e": 877, "s": 626, "text": null }, { "code": null, "e": 885, "s": 877, "text": "Output:" }, { "code": null, "e": 964, "s": 885, "text": "Using c() function:\n[1] 1 2 3 4 5 6\n\nUsing combine() function:\n[1] 1 2 3 4 5 6" }, { "code": null, "e": 1070, "s": 964, "text": "Example 2:In this example, we’ll see the different outputs of both these functions on the same operation." }, { "code": "library(dplyr) x <- factor(c(\"a\", \"a\", \"b\", \"c\"))y <- factor(c(\"b\", \"a\", \"c\", \"b\")) # Using c() functioncat(\"Using c() function:\\n\")c(x, y) # Using combine() functioncat(\"\\n\")cat(\"Using combine() function:\\n\")combine(x, y)", "e": 1296, "s": 1070, "text": null }, { "code": null, "e": 1304, "s": 1296, "text": "Output:" }, { "code": null, "e": 1405, "s": 1304, "text": "Using c() function:\n[1] 1 1 2 3 2 1 3 2\n\nUsing combine() function:\n[1] a a b c b a c b\nLevels: a b c" }, { "code": null, "e": 1418, "s": 1405, "text": "Akanksha_Rai" }, { "code": null, "e": 1439, "s": 1418, "text": "R DataFrame-Function" }, { "code": null, "e": 1455, "s": 1439, "text": "R List-Function" }, { "code": null, "e": 1473, "s": 1455, "text": "R Matrix-Function" }, { "code": null, "e": 1491, "s": 1473, "text": "R Object-Function" }, { "code": null, "e": 1509, "s": 1491, "text": "R Vector-Function" }, { "code": null, "e": 1520, "s": 1509, "text": "R Language" }, { "code": null, "e": 1618, "s": 1520, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1670, "s": 1618, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 1722, "s": 1670, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1754, "s": 1722, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 1812, "s": 1754, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1847, "s": 1812, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1891, "s": 1847, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 1929, "s": 1891, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1978, "s": 1929, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2015, "s": 1978, "text": "Logistic Regression in R Programming" } ]
Program to print the sum of the given nth term
09 Aug, 2021 Given the value of the n. You have to find the sum of the series where the nth term of the sequence is given by:Tn = n2 – ( n – 1 )2Examples : Input : 3 Output : 9 Explanation: So here the term of the sequence upto n = 3 are: 1, 3, 5 And hence the required sum is = 1 + 3 + 5 = 9 Input : 6 Output : 36 Simple Approach Just use a loop and calculate the sum of each term and print the sum. C++ Java Python3 C# PHP Javascript // CPP program to find summation of series#include <bits/stdc++.h>using namespace std; int summingSeries(long n){ // use of loop to calculate // sum of each term int S = 0; for (int i = 1; i <= n; i++) S += i * i - (i - 1) * (i - 1); return S;} // Driver Codeint main(){ int n = 100; cout << "The sum of n term is: " << summingSeries(n) << endl; return 0;} // JAVA program to find summation of seriesimport java.io.*;import java.math.*;import java.text.*;import java.util.*;import java.util.regex.*; class GFG{ // function to calculate sum of series static int summingSeries(long n) { // use of loop to calculate // sum of each term int S = 0; for (i = 1; i <= n; i++) S += i * i - (i - 1) * (i - 1); return S; } // Driver code public static void main(String[] args) { int n = 100; System.out.println("The sum of n term is: " + summingSeries(n)); }} # Python3 program to find summation# of series def summingSeries(n): # use of loop to calculate # sum of each term S = 0 for i in range(1, n+1): S += i * i - (i - 1) * (i - 1) return S # Driver Coden = 100print("The sum of n term is: ", summingSeries(n), sep = "")# This code is contributed by Smitha. // C# program to illustrate...// Summation of seriesusing System; class GFG{ // function to calculate sum of series static int summingSeries(long n) { // Using the pow function calculate // the sum of the series return (int)Math.Pow(n, 2); } // Driver code public static void Main(String[] args) { int n = 100; Console.Write("The sum of n term is: " + summingSeries(n)); }} // This code contribute by Parashar... <?php// PHP program to find// summation of series function summingSeries( $n){ // use of loop to calculate // sum of each term $S = 0; for ($i = 1; $i <= $n; $i++) $S += $i * $i - ($i - 1) * ($i - 1); return $S;} // Driver Code$n = 100;echo "The sum of n term is: ",summingSeries($n) ; // This code contribute by vt_m.?> <script>// Javascript program to find summation of series function summingSeries(n){ // use of loop to calculate // sum of each term let S = 0; for (let i = 1; i <= n; i++) S += i * i - (i - 1) * (i - 1); return S;} // Driver Codelet n = 100;document.write("The sum of n term is: " + summingSeries(n)); // This code is contributed by rishavmahato348.</script> Output: The sum of n term is: 10000 Time complexity – O(N) Space complexity – O(1)Efficient Approach Use of mathematical approach can solve this problem in more efficient way. Tn = n2 – (n-1)2Sum of the series is given by (S) = SUM( Tn )LET US TAKE A EXAMPLE IF N = 4 It means there should be 4 terms in the series so1st term = 12 – ( 1 – 1 )2 2nd term = 22 – ( 2 – 1 )2 3th term = 32 – ( 3 – 1 )2 4th term = 42 – ( 3 – 1 )2SO SUM IS GIVEN BY = (1 – 0) + (4 – 1) + (9 – 4) + (16 – 9) = 16FROM THIS WE HAVE NOTICE THAT 1, 4, 9 GET CANCELLED FROM THE SERIES ONLY 16 IS LEFT WHICH IS EQUAL TO THE SQUARE OF NSo from the above series we notice that each term gets canceled from the next term, only the last term is left which is equal to N2. C++ Java Python3 C# PHP Javascript // CPP program to illustrate...// Summation of series #include <bits/stdc++.h>using namespace std; int summingSeries(long n){ // Sum of n terms is n^2 return pow(n, 2);} // Driver Codeint main(){ int n = 100; cout << "The sum of n term is: " << summingSeries(n) << endl; return 0;} // JAVA program to illustrate...// Summation of series import java.io.*;import java.math.*;import java.text.*;import java.util.*;import java.util.regex.*; class GFG{ // function to calculate sum of series static int summingSeries(long n) { // Using the pow function calculate // the sum of the series return (int)Math.pow(n, 2); } // Driver code public static void main(String[] args) { int n = 100; System.out.println("The sum of n term is: " + summingSeries(n)); }} # Python3 program to illustrate...# Summation of seriesimport math def summingSeries(n): # Sum of n terms is n^2 return math.pow(n, 2) # Driver Coden = 100print ("The sum of n term is: ", summingSeries(n))# This code is contributed by mits. // C# program to illustrate...// Summation of seriesusing System; class GFG{ // function to calculate sum of series static int summingSeries(long n) { // Using the pow function calculate // the sum of the series return (int)Math.Pow(n, 2); } // Driver code public static void Main() { int n = 100; Console.Write("The sum of n term is: " + summingSeries(n)); }} // This code is contributed by nitin mittal. <?php// PHP program to illustrate...// Summation of series function summingSeries($n){ // Sum of n terms is n^2 return pow($n, 2);} // Driver Code$n = 100;echo "The sum of n term is: ",summingSeries($n); // This code contribute by vt_m.?> <script>// Javascript program to illustrate...// Summation of series function summingSeries(n){ // Sum of n terms is n^2 return Math.pow(n, 2);} // Driver Codelet n = 100;document.write("The sum of n term is: " + summingSeries(n) + "<br>"); // This code is contributed by subham348.</script> Output: The sum of n term is: 10000 Time complexity – O(1) Space complexity – O(1) parashar nitin mittal Smitha Dinesh Semwal vt_m Mithun Kumar Akanksha_Rai shubham prakash 1 rishavmahato348 subham348 simmytarika5 surindertarika1234 series-sum Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operators in C / C++ Prime Numbers Find minimum number of coins that make a given value Minimum number of jumps to reach end The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Modulo 10^9+7 (1000000007) Modulo Operator (%) in C/C++ with Examples Program for factorial of a number Program to find sum of elements in a given array
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Aug, 2021" }, { "code": null, "e": 172, "s": 28, "text": "Given the value of the n. You have to find the sum of the series where the nth term of the sequence is given by:Tn = n2 – ( n – 1 )2Examples : " }, { "code": null, "e": 347, "s": 172, "text": "Input : 3\nOutput : 9\n\nExplanation: So here the term of the sequence upto n = 3 are: \n 1, 3, 5 And hence the required sum is = 1 + 3 + 5 = 9\n\nInput : 6\nOutput : 36" }, { "code": null, "e": 434, "s": 347, "text": "Simple Approach Just use a loop and calculate the sum of each term and print the sum. " }, { "code": null, "e": 438, "s": 434, "text": "C++" }, { "code": null, "e": 443, "s": 438, "text": "Java" }, { "code": null, "e": 451, "s": 443, "text": "Python3" }, { "code": null, "e": 454, "s": 451, "text": "C#" }, { "code": null, "e": 458, "s": 454, "text": "PHP" }, { "code": null, "e": 469, "s": 458, "text": "Javascript" }, { "code": "// CPP program to find summation of series#include <bits/stdc++.h>using namespace std; int summingSeries(long n){ // use of loop to calculate // sum of each term int S = 0; for (int i = 1; i <= n; i++) S += i * i - (i - 1) * (i - 1); return S;} // Driver Codeint main(){ int n = 100; cout << \"The sum of n term is: \" << summingSeries(n) << endl; return 0;}", "e": 869, "s": 469, "text": null }, { "code": "// JAVA program to find summation of seriesimport java.io.*;import java.math.*;import java.text.*;import java.util.*;import java.util.regex.*; class GFG{ // function to calculate sum of series static int summingSeries(long n) { // use of loop to calculate // sum of each term int S = 0; for (i = 1; i <= n; i++) S += i * i - (i - 1) * (i - 1); return S; } // Driver code public static void main(String[] args) { int n = 100; System.out.println(\"The sum of n term is: \" + summingSeries(n)); }}", "e": 1488, "s": 869, "text": null }, { "code": "# Python3 program to find summation# of series def summingSeries(n): # use of loop to calculate # sum of each term S = 0 for i in range(1, n+1): S += i * i - (i - 1) * (i - 1) return S # Driver Coden = 100print(\"The sum of n term is: \", summingSeries(n), sep = \"\")# This code is contributed by Smitha.", "e": 1828, "s": 1488, "text": null }, { "code": "// C# program to illustrate...// Summation of seriesusing System; class GFG{ // function to calculate sum of series static int summingSeries(long n) { // Using the pow function calculate // the sum of the series return (int)Math.Pow(n, 2); } // Driver code public static void Main(String[] args) { int n = 100; Console.Write(\"The sum of n term is: \" + summingSeries(n)); }} // This code contribute by Parashar...", "e": 2326, "s": 1828, "text": null }, { "code": "<?php// PHP program to find// summation of series function summingSeries( $n){ // use of loop to calculate // sum of each term $S = 0; for ($i = 1; $i <= $n; $i++) $S += $i * $i - ($i - 1) * ($i - 1); return $S;} // Driver Code$n = 100;echo \"The sum of n term is: \",summingSeries($n) ; // This code contribute by vt_m.?>", "e": 2702, "s": 2326, "text": null }, { "code": "<script>// Javascript program to find summation of series function summingSeries(n){ // use of loop to calculate // sum of each term let S = 0; for (let i = 1; i <= n; i++) S += i * i - (i - 1) * (i - 1); return S;} // Driver Codelet n = 100;document.write(\"The sum of n term is: \" + summingSeries(n)); // This code is contributed by rishavmahato348.</script>", "e": 3089, "s": 2702, "text": null }, { "code": null, "e": 3098, "s": 3089, "text": "Output: " }, { "code": null, "e": 3126, "s": 3098, "text": "The sum of n term is: 10000" }, { "code": null, "e": 3267, "s": 3126, "text": "Time complexity – O(N) Space complexity – O(1)Efficient Approach Use of mathematical approach can solve this problem in more efficient way. " }, { "code": null, "e": 3830, "s": 3267, "text": "Tn = n2 – (n-1)2Sum of the series is given by (S) = SUM( Tn )LET US TAKE A EXAMPLE IF N = 4 It means there should be 4 terms in the series so1st term = 12 – ( 1 – 1 )2 2nd term = 22 – ( 2 – 1 )2 3th term = 32 – ( 3 – 1 )2 4th term = 42 – ( 3 – 1 )2SO SUM IS GIVEN BY = (1 – 0) + (4 – 1) + (9 – 4) + (16 – 9) = 16FROM THIS WE HAVE NOTICE THAT 1, 4, 9 GET CANCELLED FROM THE SERIES ONLY 16 IS LEFT WHICH IS EQUAL TO THE SQUARE OF NSo from the above series we notice that each term gets canceled from the next term, only the last term is left which is equal to N2. " }, { "code": null, "e": 3834, "s": 3830, "text": "C++" }, { "code": null, "e": 3839, "s": 3834, "text": "Java" }, { "code": null, "e": 3847, "s": 3839, "text": "Python3" }, { "code": null, "e": 3850, "s": 3847, "text": "C#" }, { "code": null, "e": 3854, "s": 3850, "text": "PHP" }, { "code": null, "e": 3865, "s": 3854, "text": "Javascript" }, { "code": "// CPP program to illustrate...// Summation of series #include <bits/stdc++.h>using namespace std; int summingSeries(long n){ // Sum of n terms is n^2 return pow(n, 2);} // Driver Codeint main(){ int n = 100; cout << \"The sum of n term is: \" << summingSeries(n) << endl; return 0;}", "e": 4170, "s": 3865, "text": null }, { "code": "// JAVA program to illustrate...// Summation of series import java.io.*;import java.math.*;import java.text.*;import java.util.*;import java.util.regex.*; class GFG{ // function to calculate sum of series static int summingSeries(long n) { // Using the pow function calculate // the sum of the series return (int)Math.pow(n, 2); } // Driver code public static void main(String[] args) { int n = 100; System.out.println(\"The sum of n term is: \" + summingSeries(n)); }}", "e": 4727, "s": 4170, "text": null }, { "code": "# Python3 program to illustrate...# Summation of seriesimport math def summingSeries(n): # Sum of n terms is n^2 return math.pow(n, 2) # Driver Coden = 100print (\"The sum of n term is: \", summingSeries(n))# This code is contributed by mits.", "e": 4983, "s": 4727, "text": null }, { "code": "// C# program to illustrate...// Summation of seriesusing System; class GFG{ // function to calculate sum of series static int summingSeries(long n) { // Using the pow function calculate // the sum of the series return (int)Math.Pow(n, 2); } // Driver code public static void Main() { int n = 100; Console.Write(\"The sum of n term is: \" + summingSeries(n)); }} // This code is contributed by nitin mittal.", "e": 5481, "s": 4983, "text": null }, { "code": "<?php// PHP program to illustrate...// Summation of series function summingSeries($n){ // Sum of n terms is n^2 return pow($n, 2);} // Driver Code$n = 100;echo \"The sum of n term is: \",summingSeries($n); // This code contribute by vt_m.?>", "e": 5727, "s": 5481, "text": null }, { "code": "<script>// Javascript program to illustrate...// Summation of series function summingSeries(n){ // Sum of n terms is n^2 return Math.pow(n, 2);} // Driver Codelet n = 100;document.write(\"The sum of n term is: \" + summingSeries(n) + \"<br>\"); // This code is contributed by subham348.</script>", "e": 6036, "s": 5727, "text": null }, { "code": null, "e": 6045, "s": 6036, "text": "Output: " }, { "code": null, "e": 6073, "s": 6045, "text": "The sum of n term is: 10000" }, { "code": null, "e": 6122, "s": 6073, "text": "Time complexity – O(1) Space complexity – O(1) " }, { "code": null, "e": 6131, "s": 6122, "text": "parashar" }, { "code": null, "e": 6144, "s": 6131, "text": "nitin mittal" }, { "code": null, "e": 6165, "s": 6144, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 6170, "s": 6165, "text": "vt_m" }, { "code": null, "e": 6183, "s": 6170, "text": "Mithun Kumar" }, { "code": null, "e": 6196, "s": 6183, "text": "Akanksha_Rai" }, { "code": null, "e": 6214, "s": 6196, "text": "shubham prakash 1" }, { "code": null, "e": 6230, "s": 6214, "text": "rishavmahato348" }, { "code": null, "e": 6240, "s": 6230, "text": "subham348" }, { "code": null, "e": 6253, "s": 6240, "text": "simmytarika5" }, { "code": null, "e": 6272, "s": 6253, "text": "surindertarika1234" }, { "code": null, "e": 6283, "s": 6272, "text": "series-sum" }, { "code": null, "e": 6296, "s": 6283, "text": "Mathematical" }, { "code": null, "e": 6309, "s": 6296, "text": "Mathematical" }, { "code": null, "e": 6407, "s": 6309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6428, "s": 6407, "text": "Operators in C / C++" }, { "code": null, "e": 6442, "s": 6428, "text": "Prime Numbers" }, { "code": null, "e": 6495, "s": 6442, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 6532, "s": 6495, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 6575, "s": 6532, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 6607, "s": 6575, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 6634, "s": 6607, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 6677, "s": 6634, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 6711, "s": 6677, "text": "Program for factorial of a number" } ]
Collect.js | count() Function
05 Jun, 2020 The count() function is used to count the number of collections in the element. In JavaScript, the array is first converted to a collection and then the function is applied to the collection. Syntax: data.count() Parameters: This function does not accept any parameterReturn Value: Returns the count of the element in that collection. Below examples illustrate the count() function in collect.jsExample 1: Javascript // It is used to import collect.js libraryconst collect = require('collect.js'); const num = [0 , 1 , 2 , 3 , 4, 5 , 6, 7, 8, 9]; const data = collect(num);const total = data.count(); console.log('Total number of elements are:', {total}); Output: Total number of elements are: { total: 10 } Example 2: Javascript // It is used to import collect.js libraryconst collect = require('collect.js'); const collection = collect([1, 2, 3, 4]);const x = collection.count(); console.log(`Total number of elements are : ${x}`); Output: Total number of elements are : 4 Reference: https://collect.js.org/api/count.html Collect.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2020" }, { "code": null, "e": 220, "s": 28, "text": "The count() function is used to count the number of collections in the element. In JavaScript, the array is first converted to a collection and then the function is applied to the collection." }, { "code": null, "e": 229, "s": 220, "text": "Syntax: " }, { "code": null, "e": 243, "s": 229, "text": "data.count()\n" }, { "code": null, "e": 367, "s": 243, "text": "Parameters: This function does not accept any parameterReturn Value: Returns the count of the element in that collection. " }, { "code": null, "e": 439, "s": 367, "text": "Below examples illustrate the count() function in collect.jsExample 1: " }, { "code": null, "e": 450, "s": 439, "text": "Javascript" }, { "code": "// It is used to import collect.js libraryconst collect = require('collect.js'); const num = [0 , 1 , 2 , 3 , 4, 5 , 6, 7, 8, 9]; const data = collect(num);const total = data.count(); console.log('Total number of elements are:', {total});", "e": 691, "s": 450, "text": null }, { "code": null, "e": 699, "s": 691, "text": "Output:" }, { "code": null, "e": 744, "s": 699, "text": "Total number of elements are: { total: 10 }\n" }, { "code": null, "e": 755, "s": 744, "text": "Example 2:" }, { "code": null, "e": 766, "s": 755, "text": "Javascript" }, { "code": "// It is used to import collect.js libraryconst collect = require('collect.js'); const collection = collect([1, 2, 3, 4]);const x = collection.count(); console.log(`Total number of elements are : ${x}`);", "e": 972, "s": 766, "text": null }, { "code": null, "e": 980, "s": 972, "text": "Output:" }, { "code": null, "e": 1013, "s": 980, "text": "Total number of elements are : 4" }, { "code": null, "e": 1062, "s": 1013, "text": "Reference: https://collect.js.org/api/count.html" }, { "code": null, "e": 1073, "s": 1062, "text": "Collect.js" }, { "code": null, "e": 1084, "s": 1073, "text": "JavaScript" }, { "code": null, "e": 1101, "s": 1084, "text": "Web Technologies" } ]
Difference between var and val in Kotlin
03 Jun, 2020 var and val are both used to declare variables in Kotlin language. However, there are some key differences between them: It is a general variable. The value of a variable that is declared using var can be changed anytime throughout the program. var is also called mutable and non-final variable, as there value can be changed anytime.Example: fun main() { var marks = 10 println("Previous marks is " + marks) marks = 30 println("New marks " + marks) } Output : Previous marks is 10 New marks 30 The object stored using val cannot be changed, it cannot be reassigned, it is just like the final keyword in java. val is immutable. Once assigned the val becomes read-only, however, the properties of a val object could be changed, but the object itself is read-only. Example 1: fun main(){ val marks = 10 println("Previous marks is " + marks) marks = 30 println("new marks " + marks)} Output: Val cannot be reassigned Example 2: // Changing values of val objectfun main(){ val book = Book("Java", 1000) println(book) book.name = "Kotlin" println(book)}data class Book(var name : String = "", var price : Int = 0) output: Book(name=Java, price=1000) Book(name=Kotlin, price=1000) Articles Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction Time complexities of different data structures Difference Between Object And Class SQL | DROP, TRUNCATE Implementation of LinkedList in Javascript Services in Android with Example Bottom Navigation Bar in Android How to Add Views Dynamically and Store Data in Arraylist in Android? Android UI Layouts Android RecyclerView in Kotlin
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jun, 2020" }, { "code": null, "e": 149, "s": 28, "text": "var and val are both used to declare variables in Kotlin language. However, there are some key differences between them:" }, { "code": null, "e": 371, "s": 149, "text": "It is a general variable. The value of a variable that is declared using var can be changed anytime throughout the program. var is also called mutable and non-final variable, as there value can be changed anytime.Example:" }, { "code": "fun main() { var marks = 10 println(\"Previous marks is \" + marks) marks = 30 println(\"New marks \" + marks) }", "e": 488, "s": 371, "text": null }, { "code": null, "e": 497, "s": 488, "text": "Output :" }, { "code": null, "e": 531, "s": 497, "text": "Previous marks is 10\nNew marks 30" }, { "code": null, "e": 799, "s": 531, "text": "The object stored using val cannot be changed, it cannot be reassigned, it is just like the final keyword in java. val is immutable. Once assigned the val becomes read-only, however, the properties of a val object could be changed, but the object itself is read-only." }, { "code": null, "e": 810, "s": 799, "text": "Example 1:" }, { "code": "fun main(){ val marks = 10 println(\"Previous marks is \" + marks) marks = 30 println(\"new marks \" + marks)}", "e": 931, "s": 810, "text": null }, { "code": null, "e": 939, "s": 931, "text": "Output:" }, { "code": null, "e": 965, "s": 939, "text": "Val cannot be reassigned\n" }, { "code": null, "e": 976, "s": 965, "text": "Example 2:" }, { "code": "// Changing values of val objectfun main(){ val book = Book(\"Java\", 1000) println(book) book.name = \"Kotlin\" println(book)}data class Book(var name : String = \"\", var price : Int = 0)", "e": 1188, "s": 976, "text": null }, { "code": null, "e": 1196, "s": 1188, "text": "output:" }, { "code": null, "e": 1255, "s": 1196, "text": "Book(name=Java, price=1000)\nBook(name=Kotlin, price=1000)\n" }, { "code": null, "e": 1264, "s": 1255, "text": "Articles" }, { "code": null, "e": 1271, "s": 1264, "text": "Kotlin" }, { "code": null, "e": 1369, "s": 1271, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1395, "s": 1369, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1442, "s": 1395, "text": "Time complexities of different data structures" }, { "code": null, "e": 1478, "s": 1442, "text": "Difference Between Object And Class" }, { "code": null, "e": 1499, "s": 1478, "text": "SQL | DROP, TRUNCATE" }, { "code": null, "e": 1542, "s": 1499, "text": "Implementation of LinkedList in Javascript" }, { "code": null, "e": 1575, "s": 1542, "text": "Services in Android with Example" }, { "code": null, "e": 1608, "s": 1575, "text": "Bottom Navigation Bar in Android" }, { "code": null, "e": 1677, "s": 1608, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 1696, "s": 1677, "text": "Android UI Layouts" } ]
Implementing upper_bound() and lower_bound() in C
06 Aug, 2021 Given a sorted array arr[] of N integers and a number K, the task is to write the C program to find the upper_bound() and lower_bound() of K in the given array.Examples: Input: arr[] = {4, 6, 10, 12, 18, 20}, K = 6 Output: Lower bound of 6 is 6 at index 1 Upper bound of 6 is 10 at index 2Input: arr[] = {4, 6, 10, 12, 18, 20}, K = 20 Output: Lower bound of 20 is 20 at index 5 Upper bound doesn’t exist Approach: The idea is to use Binary Search. Below are the steps: For lower_bound(): Initialise the startIndex as 0 and endIndex as N – 1.Compare K with the middle element(say arr[mid]) of the array.If the middle element is greater equals to K then update the endIndex as a middle index(mid).Else Update startIndex as mid + 1.Repeat the above steps until startIndex is less than endIndex.After all the above steps the startIndex is the lower_bound of K in the given array. Initialise the startIndex as 0 and endIndex as N – 1.Compare K with the middle element(say arr[mid]) of the array.If the middle element is greater equals to K then update the endIndex as a middle index(mid).Else Update startIndex as mid + 1.Repeat the above steps until startIndex is less than endIndex.After all the above steps the startIndex is the lower_bound of K in the given array. Initialise the startIndex as 0 and endIndex as N – 1. Compare K with the middle element(say arr[mid]) of the array. If the middle element is greater equals to K then update the endIndex as a middle index(mid). Else Update startIndex as mid + 1. Repeat the above steps until startIndex is less than endIndex. After all the above steps the startIndex is the lower_bound of K in the given array. For upper_bound(): Initialise the startIndex as 0 and endIndex as N – 1.Compare K with the middle element(say arr[mid]) of the array.If the middle element is less than equals to K then update the startIndex as middle index + 1(mid + 1).Else Update endIndex as mid.Repeat the above steps until startIndex is less than endIndex.After all the above steps the startIndex is the upper_bound of K in the given array. Initialise the startIndex as 0 and endIndex as N – 1.Compare K with the middle element(say arr[mid]) of the array.If the middle element is less than equals to K then update the startIndex as middle index + 1(mid + 1).Else Update endIndex as mid.Repeat the above steps until startIndex is less than endIndex.After all the above steps the startIndex is the upper_bound of K in the given array. Initialise the startIndex as 0 and endIndex as N – 1. Compare K with the middle element(say arr[mid]) of the array. If the middle element is less than equals to K then update the startIndex as middle index + 1(mid + 1). Else Update endIndex as mid. Repeat the above steps until startIndex is less than endIndex. After all the above steps the startIndex is the upper_bound of K in the given array. Below is the iterative and recursive implementation of the above approach: Iterative Solution Recursive Solution // C program for iterative implementation// of the above approach #include <stdio.h> // Function to implement lower_boundint lower_bound(int arr[], int N, int X){ int mid; // Initialise starting index and // ending index int low = 0; int high = N; // Till low is less than high while (low < high) { mid = low + (high - low) / 2; // If X is less than or equal // to arr[mid], then find in // left subarray if (X <= arr[mid]) { high = mid; } // If X is greater arr[mid] // then find in right subarray else { low = mid + 1; } } // if X is greater than arr[n-1] if(low < N && arr[low] < X) { low++; } // Return the lower_bound index return low;} // Function to implement upper_boundint upper_bound(int arr[], int N, int X){ int mid; // Initialise starting index and // ending index int low = 0; int high = N; // Till low is less than high while (low < high) { // Find the middle index mid = low + (high - low) / 2; // If X is greater than or equal // to arr[mid] then find // in right subarray if (X >= arr[mid]) { low = mid + 1; } // If X is less than arr[mid] // then find in left subarray else { high = mid; } } // if X is greater than arr[n-1] if(low < N && arr[low] <= X) { low++; } // Return the upper_bound index return low;} // Function to implement lower_bound// and upper_bound of Xvoid printBound(int arr[], int N, int X){ int idx; // If lower_bound doesn't exists if (lower_bound(arr, N, X) == N) { printf("Lower bound doesn't exist"); } else { // Find lower_bound idx = lower_bound(arr, N, X); printf("Lower bound of %d is" "% d at index % d\n ", X, arr[idx], idx); } // If upper_bound doesn't exists if (upper_bound(arr, N, X) == N) { printf("Upper bound doesn't exist"); } else { // Find upper_bound idx = upper_bound(arr, N, X); printf("Upper bound of %d is" "% d at index % d\n ", X, arr[idx], idx); }} // Driver Codeint main(){ // Given array int arr[] = { 4, 6, 10, 12, 18, 20 }; int N = sizeof(arr) / sizeof(arr[0]); // Element whose lower bound and // upper bound to be found int X = 6; // Function Call printBound(arr, N, X); return 0;} // C program for recursive implementation// of the above approach #include <stdio.h> // Recursive implementation of// lower_boundint lower_bound(int arr[], int low, int high, int X){ // Base Case if (low > high) { return low; } // Find the middle index int mid = low + (high - low) / 2; // If arr[mid] is greater than // or equal to X then search // in left subarray if (arr[mid] >= X) { return lower_bound(arr, low, mid - 1, X); } // If arr[mid] is less than X // then search in right subarray return lower_bound(arr, mid + 1, high, X);} // Recursive implementation of// upper_boundint upper_bound(int arr[], int low, int high, int X){ // Base Case if (low > high) return low; // Find the middle index int mid = low + (high - low) / 2; // If arr[mid] is less than // or equal to X search in // right subarray if (arr[mid] <= X) { return upper_bound(arr, mid + 1, high, X); } // If arr[mid] is greater than X // then search in left subarray return upper_bound(arr, low, mid - 1, X);} // Function to implement lower_bound// and upper_bound of Xvoid printBound(int arr[], int N, int X){ int idx; // If lower_bound doesn't exists if (lower_bound(arr, 0, N, X) == N) { printf("Lower bound doesn't exist"); } else { // Find lower_bound idx = lower_bound(arr, 0, N, X); printf("Lower bound of %d " "is %d at index %d\n", X, arr[idx], idx); } // If upper_bound doesn't exists if (upper_bound(arr, 0, N, X) == N) { printf("Upper bound doesn't exist"); } else { // Find upper_bound idx = upper_bound(arr, 0, N, X); printf("Upper bound of %d is" "% d at index % d\n ", X, arr[idx], idx); }} // Driver Codeint main(){ // Given array int arr[] = { 4, 6, 10, 12, 18, 20 }; int N = sizeof(arr) / sizeof(arr[0]); // Element whose lower bound and // upper bound to be found int X = 6; // Function Call printBound(arr, N, X); return 0;} Lower bound of 6 is 6 at index 1 Upper bound of 6 is 10 at index 2 Time Complexity: O(log2 N), where N is the number of elements in the array. Auxiliary Space: O(1). ssaksham shivoy4ndixit gabaa406 pankajsharmagfg Algorithms Arrays C Programs Competitive Programming Recursion Searching Arrays Searching Recursion Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Aug, 2021" }, { "code": null, "e": 226, "s": 54, "text": "Given a sorted array arr[] of N integers and a number K, the task is to write the C program to find the upper_bound() and lower_bound() of K in the given array.Examples: " }, { "code": null, "e": 462, "s": 226, "text": "Input: arr[] = {4, 6, 10, 12, 18, 20}, K = 6 Output: Lower bound of 6 is 6 at index 1 Upper bound of 6 is 10 at index 2Input: arr[] = {4, 6, 10, 12, 18, 20}, K = 20 Output: Lower bound of 20 is 20 at index 5 Upper bound doesn’t exist " }, { "code": null, "e": 531, "s": 464, "text": "Approach: The idea is to use Binary Search. Below are the steps: " }, { "code": null, "e": 938, "s": 531, "text": "For lower_bound(): Initialise the startIndex as 0 and endIndex as N – 1.Compare K with the middle element(say arr[mid]) of the array.If the middle element is greater equals to K then update the endIndex as a middle index(mid).Else Update startIndex as mid + 1.Repeat the above steps until startIndex is less than endIndex.After all the above steps the startIndex is the lower_bound of K in the given array." }, { "code": null, "e": 1326, "s": 938, "text": "Initialise the startIndex as 0 and endIndex as N – 1.Compare K with the middle element(say arr[mid]) of the array.If the middle element is greater equals to K then update the endIndex as a middle index(mid).Else Update startIndex as mid + 1.Repeat the above steps until startIndex is less than endIndex.After all the above steps the startIndex is the lower_bound of K in the given array." }, { "code": null, "e": 1380, "s": 1326, "text": "Initialise the startIndex as 0 and endIndex as N – 1." }, { "code": null, "e": 1442, "s": 1380, "text": "Compare K with the middle element(say arr[mid]) of the array." }, { "code": null, "e": 1536, "s": 1442, "text": "If the middle element is greater equals to K then update the endIndex as a middle index(mid)." }, { "code": null, "e": 1571, "s": 1536, "text": "Else Update startIndex as mid + 1." }, { "code": null, "e": 1634, "s": 1571, "text": "Repeat the above steps until startIndex is less than endIndex." }, { "code": null, "e": 1719, "s": 1634, "text": "After all the above steps the startIndex is the lower_bound of K in the given array." }, { "code": null, "e": 2130, "s": 1719, "text": "For upper_bound(): Initialise the startIndex as 0 and endIndex as N – 1.Compare K with the middle element(say arr[mid]) of the array.If the middle element is less than equals to K then update the startIndex as middle index + 1(mid + 1).Else Update endIndex as mid.Repeat the above steps until startIndex is less than endIndex.After all the above steps the startIndex is the upper_bound of K in the given array." }, { "code": null, "e": 2522, "s": 2130, "text": "Initialise the startIndex as 0 and endIndex as N – 1.Compare K with the middle element(say arr[mid]) of the array.If the middle element is less than equals to K then update the startIndex as middle index + 1(mid + 1).Else Update endIndex as mid.Repeat the above steps until startIndex is less than endIndex.After all the above steps the startIndex is the upper_bound of K in the given array." }, { "code": null, "e": 2576, "s": 2522, "text": "Initialise the startIndex as 0 and endIndex as N – 1." }, { "code": null, "e": 2638, "s": 2576, "text": "Compare K with the middle element(say arr[mid]) of the array." }, { "code": null, "e": 2742, "s": 2638, "text": "If the middle element is less than equals to K then update the startIndex as middle index + 1(mid + 1)." }, { "code": null, "e": 2771, "s": 2742, "text": "Else Update endIndex as mid." }, { "code": null, "e": 2834, "s": 2771, "text": "Repeat the above steps until startIndex is less than endIndex." }, { "code": null, "e": 2919, "s": 2834, "text": "After all the above steps the startIndex is the upper_bound of K in the given array." }, { "code": null, "e": 2995, "s": 2919, "text": "Below is the iterative and recursive implementation of the above approach: " }, { "code": null, "e": 3014, "s": 2995, "text": "Iterative Solution" }, { "code": null, "e": 3033, "s": 3014, "text": "Recursive Solution" }, { "code": "// C program for iterative implementation// of the above approach #include <stdio.h> // Function to implement lower_boundint lower_bound(int arr[], int N, int X){ int mid; // Initialise starting index and // ending index int low = 0; int high = N; // Till low is less than high while (low < high) { mid = low + (high - low) / 2; // If X is less than or equal // to arr[mid], then find in // left subarray if (X <= arr[mid]) { high = mid; } // If X is greater arr[mid] // then find in right subarray else { low = mid + 1; } } // if X is greater than arr[n-1] if(low < N && arr[low] < X) { low++; } // Return the lower_bound index return low;} // Function to implement upper_boundint upper_bound(int arr[], int N, int X){ int mid; // Initialise starting index and // ending index int low = 0; int high = N; // Till low is less than high while (low < high) { // Find the middle index mid = low + (high - low) / 2; // If X is greater than or equal // to arr[mid] then find // in right subarray if (X >= arr[mid]) { low = mid + 1; } // If X is less than arr[mid] // then find in left subarray else { high = mid; } } // if X is greater than arr[n-1] if(low < N && arr[low] <= X) { low++; } // Return the upper_bound index return low;} // Function to implement lower_bound// and upper_bound of Xvoid printBound(int arr[], int N, int X){ int idx; // If lower_bound doesn't exists if (lower_bound(arr, N, X) == N) { printf(\"Lower bound doesn't exist\"); } else { // Find lower_bound idx = lower_bound(arr, N, X); printf(\"Lower bound of %d is\" \"% d at index % d\\n \", X, arr[idx], idx); } // If upper_bound doesn't exists if (upper_bound(arr, N, X) == N) { printf(\"Upper bound doesn't exist\"); } else { // Find upper_bound idx = upper_bound(arr, N, X); printf(\"Upper bound of %d is\" \"% d at index % d\\n \", X, arr[idx], idx); }} // Driver Codeint main(){ // Given array int arr[] = { 4, 6, 10, 12, 18, 20 }; int N = sizeof(arr) / sizeof(arr[0]); // Element whose lower bound and // upper bound to be found int X = 6; // Function Call printBound(arr, N, X); return 0;}", "e": 5597, "s": 3033, "text": null }, { "code": "// C program for recursive implementation// of the above approach #include <stdio.h> // Recursive implementation of// lower_boundint lower_bound(int arr[], int low, int high, int X){ // Base Case if (low > high) { return low; } // Find the middle index int mid = low + (high - low) / 2; // If arr[mid] is greater than // or equal to X then search // in left subarray if (arr[mid] >= X) { return lower_bound(arr, low, mid - 1, X); } // If arr[mid] is less than X // then search in right subarray return lower_bound(arr, mid + 1, high, X);} // Recursive implementation of// upper_boundint upper_bound(int arr[], int low, int high, int X){ // Base Case if (low > high) return low; // Find the middle index int mid = low + (high - low) / 2; // If arr[mid] is less than // or equal to X search in // right subarray if (arr[mid] <= X) { return upper_bound(arr, mid + 1, high, X); } // If arr[mid] is greater than X // then search in left subarray return upper_bound(arr, low, mid - 1, X);} // Function to implement lower_bound// and upper_bound of Xvoid printBound(int arr[], int N, int X){ int idx; // If lower_bound doesn't exists if (lower_bound(arr, 0, N, X) == N) { printf(\"Lower bound doesn't exist\"); } else { // Find lower_bound idx = lower_bound(arr, 0, N, X); printf(\"Lower bound of %d \" \"is %d at index %d\\n\", X, arr[idx], idx); } // If upper_bound doesn't exists if (upper_bound(arr, 0, N, X) == N) { printf(\"Upper bound doesn't exist\"); } else { // Find upper_bound idx = upper_bound(arr, 0, N, X); printf(\"Upper bound of %d is\" \"% d at index % d\\n \", X, arr[idx], idx); }} // Driver Codeint main(){ // Given array int arr[] = { 4, 6, 10, 12, 18, 20 }; int N = sizeof(arr) / sizeof(arr[0]); // Element whose lower bound and // upper bound to be found int X = 6; // Function Call printBound(arr, N, X); return 0;}", "e": 7846, "s": 5597, "text": null }, { "code": null, "e": 7916, "s": 7846, "text": "Lower bound of 6 is 6 at index 1\n Upper bound of 6 is 10 at index 2" }, { "code": null, "e": 8017, "s": 7918, "text": "Time Complexity: O(log2 N), where N is the number of elements in the array. Auxiliary Space: O(1)." }, { "code": null, "e": 8026, "s": 8017, "text": "ssaksham" }, { "code": null, "e": 8040, "s": 8026, "text": "shivoy4ndixit" }, { "code": null, "e": 8049, "s": 8040, "text": "gabaa406" }, { "code": null, "e": 8065, "s": 8049, "text": "pankajsharmagfg" }, { "code": null, "e": 8076, "s": 8065, "text": "Algorithms" }, { "code": null, "e": 8083, "s": 8076, "text": "Arrays" }, { "code": null, "e": 8094, "s": 8083, "text": "C Programs" }, { "code": null, "e": 8118, "s": 8094, "text": "Competitive Programming" }, { "code": null, "e": 8128, "s": 8118, "text": "Recursion" }, { "code": null, "e": 8138, "s": 8128, "text": "Searching" }, { "code": null, "e": 8145, "s": 8138, "text": "Arrays" }, { "code": null, "e": 8155, "s": 8145, "text": "Searching" }, { "code": null, "e": 8165, "s": 8155, "text": "Recursion" }, { "code": null, "e": 8176, "s": 8165, "text": "Algorithms" } ]
Connect new point to the previous point on a image with a straight line in Opencv-Python
31 Aug, 2021 OpenCV-Python is a library of Python bindings designed to solve computer vision problems. Let’s see how to Connect a new point to the previous point on an image with a straight line. Step 1: Draw points on image: On a image we can mark points using cv2.circle( ) method. This method is used to draw a circle on any image. Syntax: cv2.circle(image, center_coordinates, radius, color, thickness) Parameters: This method will take the following parameters: image: It is the image on which circle is to be drawn. center_coordinates: It is the center coordinates of the circle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value). radius: It is the radius of the circle. color: It is the color of the borderline of the circle to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color. thickness: It is the thickness of the circle borderline in px. The thickness of -1 px will fill the rectangle shape by the specified color. Return: It returns an image with a circle drawn on it. Step 2: Joining two points through a straight line: We can join two points on an image using the cv2.line() method. This method is used to draw a line on any image. Syntax: cv2.circle(image, center_coordinates, radius, color, thickness) Parameters: This method will take the following parameters: image: It is the image on which circle is to be drawn. center_coordinates: It is the center coordinates of the circle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value). radius: It is the radius of the circle. color: It is the color of the borderline of the circle to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color. thickness: It is the thickness of the circle borderline in px. The thickness of -1 px will fill the rectangle shape by the specified color. Return Value: It returns an image with a line drawn on it. Below is the implementation: Python3 # importing required packagesimport cv2import numpy as np # mouse call back functiondef click_event(event, x, y, flags, params): # if the left button of mouse # is clicked then this # condition executes if event == cv2.EVENT_LBUTTONDOWN: # appending the points we # clicked to list points.append((x,y)) # marking the point with a circle # of center at that point and # small radius cv2.circle(img,(x,y), 4, (0, 255, 0), -1) # if length of points list # greater than2 then this # condition executes if len(points) >= 2: # joins the current point and # the previous point in the # list with a line cv2.line(img, points[-1], points[-2], (0, 255, 255), 5) # displays the image cv2.imshow('image', img) # making an black image# of size (512,512,3)# create 3-d numpy# zeros arrayimg = np.zeros((512, 512, 3), np.uint8) # declare a list to append all the# points on the image we clickedpoints = [] # show the imagecv2.imshow('image',img) # setting mouse call backcv2.setMouseCallback('image', click_event) # no waitingcv2.waitKey(0) # To close the image# window that we openedcv2.destroyAllWindows() singghakshay Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Aug, 2021" }, { "code": null, "e": 211, "s": 28, "text": "OpenCV-Python is a library of Python bindings designed to solve computer vision problems. Let’s see how to Connect a new point to the previous point on an image with a straight line." }, { "code": null, "e": 241, "s": 211, "text": "Step 1: Draw points on image:" }, { "code": null, "e": 350, "s": 241, "text": "On a image we can mark points using cv2.circle( ) method. This method is used to draw a circle on any image." }, { "code": null, "e": 422, "s": 350, "text": "Syntax: cv2.circle(image, center_coordinates, radius, color, thickness)" }, { "code": null, "e": 482, "s": 422, "text": "Parameters: This method will take the following parameters:" }, { "code": null, "e": 537, "s": 482, "text": "image: It is the image on which circle is to be drawn." }, { "code": null, "e": 704, "s": 537, "text": "center_coordinates: It is the center coordinates of the circle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value)." }, { "code": null, "e": 744, "s": 704, "text": "radius: It is the radius of the circle." }, { "code": null, "e": 870, "s": 744, "text": "color: It is the color of the borderline of the circle to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color." }, { "code": null, "e": 1010, "s": 870, "text": "thickness: It is the thickness of the circle borderline in px. The thickness of -1 px will fill the rectangle shape by the specified color." }, { "code": null, "e": 1065, "s": 1010, "text": "Return: It returns an image with a circle drawn on it." }, { "code": null, "e": 1117, "s": 1065, "text": "Step 2: Joining two points through a straight line:" }, { "code": null, "e": 1230, "s": 1117, "text": "We can join two points on an image using the cv2.line() method. This method is used to draw a line on any image." }, { "code": null, "e": 1302, "s": 1230, "text": "Syntax: cv2.circle(image, center_coordinates, radius, color, thickness)" }, { "code": null, "e": 1362, "s": 1302, "text": "Parameters: This method will take the following parameters:" }, { "code": null, "e": 1417, "s": 1362, "text": "image: It is the image on which circle is to be drawn." }, { "code": null, "e": 1584, "s": 1417, "text": "center_coordinates: It is the center coordinates of the circle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value)." }, { "code": null, "e": 1624, "s": 1584, "text": "radius: It is the radius of the circle." }, { "code": null, "e": 1750, "s": 1624, "text": "color: It is the color of the borderline of the circle to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color." }, { "code": null, "e": 1890, "s": 1750, "text": "thickness: It is the thickness of the circle borderline in px. The thickness of -1 px will fill the rectangle shape by the specified color." }, { "code": null, "e": 1949, "s": 1890, "text": "Return Value: It returns an image with a line drawn on it." }, { "code": null, "e": 1978, "s": 1949, "text": "Below is the implementation:" }, { "code": null, "e": 1986, "s": 1978, "text": "Python3" }, { "code": "# importing required packagesimport cv2import numpy as np # mouse call back functiondef click_event(event, x, y, flags, params): # if the left button of mouse # is clicked then this # condition executes if event == cv2.EVENT_LBUTTONDOWN: # appending the points we # clicked to list points.append((x,y)) # marking the point with a circle # of center at that point and # small radius cv2.circle(img,(x,y), 4, (0, 255, 0), -1) # if length of points list # greater than2 then this # condition executes if len(points) >= 2: # joins the current point and # the previous point in the # list with a line cv2.line(img, points[-1], points[-2], (0, 255, 255), 5) # displays the image cv2.imshow('image', img) # making an black image# of size (512,512,3)# create 3-d numpy# zeros arrayimg = np.zeros((512, 512, 3), np.uint8) # declare a list to append all the# points on the image we clickedpoints = [] # show the imagecv2.imshow('image',img) # setting mouse call backcv2.setMouseCallback('image', click_event) # no waitingcv2.waitKey(0) # To close the image# window that we openedcv2.destroyAllWindows()", "e": 3371, "s": 1986, "text": null }, { "code": null, "e": 3384, "s": 3371, "text": "singghakshay" }, { "code": null, "e": 3398, "s": 3384, "text": "Python-OpenCV" }, { "code": null, "e": 3405, "s": 3398, "text": "Python" } ]
Sampling Distributions with Python | by Luís Roque | Medium | Towards Data Science
In a series of weekly articles, I will be covering some important topics of statistics with a twist. The goal is to use Python to help us get intuition on complex concepts, empirically test theoretical proofs, or build algorithms from scratch. In this series, you will find articles covering topics such as random variables, sampling distributions, confidence intervals, significance tests, and more. At the end of each article, you can find exercises to test your knowledge. The solutions will be shared in the article of the following week. Articles published so far: Bernoulli and Binomial Random Variables with Python From Binomial to Geometric and Poisson Random Variables with Python Sampling Distribution of a Sample Proportion with Python Confidence Intervals with Python Significance Tests with Python Two-sample Inference for the Difference Between Groups with Python Inference for Categorical Data Advanced Regression Analysis of Variance — ANOVA As usual, the code is available on my GitHub. We often find ourselves wanting to estimate a parameter for a population, for instance, its mean or standard deviation. Usually, we cannot collect data from the overall population. In this case, the only way for us to estimate the parameters of our population is by random sampling from it. We define the size of the sample n and calculate a statistic for each sample. This statistic is what we use to calculate the parameter of the overall population. Notice that the statistic that we calculate for each random sample could be far from the population value because it is a random sample. That is why we perform this process a series of times, which we can call trials. Let’s define a straightforward example. We have a population of 100 athletes with numbered shirts with distinct values from 0 to 99. First, we calculate the parameters for our population, μ, and σ. import numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import bernoulli, norm, poissonfrom scipy import statsfrom scipy.stats import kurtosis, skewimport seaborn as snsX = np.random.choice(np.arange(0, 100), 100, replace=False)print(f'μ={X.mean()}')print(f'σ={X.std()}')μ=49.5σ=28.86607004772212 We take 100 random samples of size 5. rs = []for i in range(100): rs.append(np.random.choice(X, 5))rs = np.array(rs)# 5 examples of our random samplesrs[:5]array([[87, 73, 61, 91, 99], [10, 5, 46, 72, 92], [ 1, 3, 7, 59, 88], [ 1, 42, 87, 21, 42], [65, 9, 54, 88, 67]]) For each one, we calculate some statistic; in this case, the sample mean x̄. Thus, x̄ s an array of 100 values (the mean value of each sample). Let’s print the first 5 values and then plot a histogram to understand the sampling distribution's shape better. In fact, this is the sampling distribution of the sample mean for a sample size equal to 5. x_bar = rs.mean(axis=1)print(x_bar[:5])plt.hist(x_bar, bins=100);[82.2 45. 31.6 38.6 56.6] We will start this section by creating two Random Variables (RV), a Bernoulli RV and a Binomial RV (if you are unfamiliar with the details, please see my previous articles from this series). The problem at hand is the following, there are 20,000 distinct universes where Rick and Morty live and we want to calculate the proportion of Mortys that we can find if we visit one random universe. Let X be the following Bernoulli RV: We already saw in a past article that and Now, let’s define a new RV, which is equal to the sum of 10 independent trials of X. This is a Binomial RV with Now it is time to visit some universes and look for Morty there randomly. Imagine that we visit 10 universes each time, which are indeed samples that we are taking from the overall population of universes. Notice that we can consider these samples independent even if we choose distinct universes for the sample of 10. This is due to a very small number of samples compared to the population. There is, in fact, a 10% rule to assume independence in a random sampling without replacement from a population of a certain size. Time to look for Morty. p = 0.6n = 10X = bernoulli(p)Y = [X.rvs(n) for i in range(10000)]plt.hist(np.sum(Y, axis=1)); And there you go, this is the sampling distribution of the sampling proportion. How can we calculate its mean and standard deviation? The expected value for your sample proportion is the proportion of Mortys that we find in our visits, showing an unbiased estimation for the population parameter. In the same way, the standard deviation of the sample proportion is the standard deviation of our binomial random variable Y divided by n. print('Empirically calculated expected value: {}'.format(np.mean(np.mean(Y, axis=1))))print('Theoretical expected value: {}'.format(p))Empirically calculated expected value: 0.5977399999999999Theoretical expected value: 0.6print('Empirically calculated standard deviation: {}'.format(np.std(np.mean(Y, axis=1))))print('Theoretical standard deviation: {}'.format(np.sqrt(p*(1-p)/n)))Empirically calculated standard deviation: 0.15472844728749785Theoretical standard deviation: 0.15491933384829668 There you go; we arrive at very similar values. First, by performing a large number of trials of 10 visit tours to random universes. Secondly, by computing the theoretical values for this sampling distribution. In this article, we will understand exactly why these two approaches yield similar results. There are two conditions to consider a sampling distribution approximately normal in its shape. Let’s try an example. You ran a music store and received 100 new CDs every week (consider these to be a random sample). Your supplier states that they are delivering approximately 10% of Rock CDs. You calculate the weekly proportion of Rock CDs in the weekly sample. n = 100p = 0.1print(n*p)print(n*(1-p))10.090.0 The conditions are met. Let’s plot it and look at the resulting distribution. X = bernoulli(p)Y = [X.rvs(100) for i in range(10000)]normal = np.random.normal(p*n, np.sqrt(n*p*(1-p)), (1000, ))density = stats.gaussian_kde(normal)n_, x, _ = plt.hist(normal, bins=np.linspace(0, 20, 50), histtype=u'step', density=True) plt.close()plt.hist(np.sum(Y, axis=1), density=True)plt.plot(x, density(x)); Looks good and approximately normal. What if instead of a 10% probability of receiving Rock CDs, we were informed that it changed to 3%? n = 100p_ = 0.03print(n*p_)print(n*(1-p_))3.097.0 The first condition is not met. X = bernoulli(p_)Y_ = [X.rvs(100) for i in range(10000)]normal = np.random.normal(p_*n, np.sqrt(n*p_*(1-p_)), (1000, ))density = stats.gaussian_kde(normal)n_, x, _ = plt.hist(normal, bins=np.linspace(0, 20, 50), histtype=u'step', density=True) plt.close()plt.hist(np.sum(Y_, axis=1), density=True)plt.plot(x, density(x)); In fact, our distribution is skewed to the right. Why are these conditions important? These are relevant when we need to answer questions about the probability of sampling proportions. For example, returning to our example and considering the initial information of 10% probability of receiving Rock CDs. Consider that you find on your first trial that 12% of the CDs were Rock CDs. Assuming that the true proportion is informed by your supplier, what would be the probability that more than 12% of the sample you searched consists of Rock CDs? We already know that the sampling distribution is approximately normal. So we need to build our normal distribution and compute P(p>0.12). print('Empirically calculated expected value: {}'.format(np.mean(np.mean(Y, axis=1))))print('Theoretical expected value: {}'.format(p))Empirically calculated expected value: 0.09973800000000001Theoretical expected value: 0.1print('Empirically calculated standard deviation: {}'.format(np.std(np.mean(Y, axis=1))))print('Theoretical standard deviation: {}'.format(np.sqrt(p*(1-p)/n)))Empirically calculated standard deviation: 0.029996189024607777Theoretical standard deviation: 0.030000000000000002n = 100p = 0.10p_ = 0.12print(f'P(p>0.12)={1-norm.cdf(p_, p, np.sqrt(p*(1-p)/n))}')P(p>0.12)=0.252492537546923 In the first section, we have calculated the number o Mortys that we found in samples of our population of universes using two different approaches. The first by deriving the theoretical properties of a sampling distribution of sampling proportions. The second one by estimating the parameters using the statistics of the sampling distribution. In this section, we will understand better the second approach. Let’s start by defining the population mean μ: where N represents the population size or the 20,000 universes. The sample mean ȳ can be defined as, where n represents the sample size or one of the simple random samples of size 10 that we have drawn from the overall population. p = 0.6n = 10X = bernoulli(p)Y = [X.rvs(n) for i in range(10000)]# One random sampley_bar = np.mean(Y[0])y_bar0.9 Notice that ȳ is a statistic that we use to infer the population parameter. Nevertheless, these could be different as we are randomly taking samples from the population. We want to get the intuition on the Central Limit Theorem (CLT), and then we will get to its interest and applications. But, first, let’s define a clearly non-normal distribution. elements = np.arange(6)probabilities = [0.3, 0., 0.05, 0.05, 0.2, 0.4]X = np.random.choice(elements, 100, p=probabilities)sns.histplot(X, stat='probability'); Now, we can draw samples from it. We are going to draw samples of size 4 and calculate its mean. s_1 = np.random.choice(elements, 4, p=probabilities)print(s_1)x_bar_1 = np.mean(s_1)print(x_bar_1)[0 5 4 0]2.25 Let’s do the same procedure 10,000 times. s = []n=4for i in range(10000): s.append(np.random.choice(elements, n, p=probabilities))s = np.mean(np.asarray(s), axis=1)print('Kurtosis: ' + str(np.round(kurtosis(s),2)))print('Skew: ' + str(np.round(skew(s),2)))print('---')print('μ=' + str(np.round(np.mean(s), 2)))print('σ=' + str(np.round(np.std(s), 2)))sns.histplot(s, stat='probability');Kurtosis: -0.36Skew: -0.27---μ=3.06σ=1.06 The distribution above does not look like our original distribution anymore. The CTL tells us that as you take more samples and calculate their mean, the resulting distribution will approximate a normal distribution. We can measure it by the value of the skewness and kurtosis, which for a normal distribution should be zero. A positively skewed distribution has a tail to the right, while a negative one has a tail to the left. If the distribution has positive kurtosis, it has fatter tails than the normal distribution; conversely, the tails would be thinner in a negative scenario. What the CLT also tells us is that the approximation becomes better as the sample size increases. So let’s test it by increasing the sample size from 4 to 20 and then to 100. s = []n=20for i in range(10000): s.append(np.random.choice(elements, n, p=probabilities))s = np.mean(np.asarray(s), axis=1)print('Kurtosis: ' + str(np.round(kurtosis(s),2)))print('Skew: ' + str(np.round(skew(s),2)))print('---')print('μ=' + str(np.round(np.mean(s), 2)))print('σ=' + str(np.round(np.std(s), 2)))sns.histplot(s, stat='probability');Kurtosis: -0.1Skew: -0.09---μ=3.06σ=0.47 s = []n=100for i in range(10000): s.append(np.random.choice(elements, n, p=probabilities))s = np.mean(np.asarray(s), axis=1)print('Kurtosis: ' + str(np.round(kurtosis(s),2)))print('Skew: ' + str(np.round(skew(s),2)))print('---')print('μ=' + str(np.round(np.mean(s), 2)))print('σ=' + str(np.round(np.std(s), 2)))sns.histplot(s, stat='probability');Kurtosis: -0.08Skew: -0.03---μ=3.05σ=0.22 Notice how the last plot resembles a normal distribution. There is a convention that a sample size bigger than 30 is enough to approximate a normal distribution. Also, notice that the value of the mean and standard deviation of the sampling distribution that we have been plotting for the different sample sizes. Not surprisingly, the mean is the same as the original distribution. But the value for the standard deviation is indeed strange, as it has been shrinking. In fact, this is an important property to take note of: the standard deviation of our sampling distribution of sample means is the square root of the standard deviation of the original population divided by the sample size. Thus, we can write it as: print("Theoretical value: " + str(np.sqrt(X.var()/n)))print("Empirically computed: " + str(s.std()))Theoretical value: 0.20789179878003847Empirically computed: 0.2151977077573086 This process is not specific to the sample mean; we could be, for instance, calculate the sample sum. s = []for i in range(10000): s.append(np.random.choice(elements, 100, p=probabilities))s = np.sum(np.asarray(s), axis=1)print('Kurtosis: ' + str(np.round(kurtosis(s),2)))print('Skew: ' + str(np.round(skew(s),2)))sns.histplot(s, stat='probability');Kurtosis: -0.04Skew: -0.02 I hope that now you see why the normal distribution is so often used to model different processes. Even if you do not know the distribution of a process that you want to describe statistically, if you add or take the mean of your measurements (assuming that they all have the same distribution), suddenly you get a normal distribution. The problem that we faced in this article is the estimation of parameters of a population. Very often we can not collect enough data to represent the entire population and so, we need to find another way to estimate its parameters. The method that we explored draws random samples from the population. From the random samples, we calculate statistics which we afterward use to infer the parameters of the population. We looked at sampling distributions of sampling proportions and sampling distributions of sample means. We also explored the CLT. It tells us that independently of the shape of the original distribution of a process that we want to describe statistically, the mean or sum of samples taken from this original distribution will approximate a normal distribution for a sample size larger than 30. You will get the solutions in next week’s article. Rick takes an SRS of 75 citizens on a distant planet to see what proportion of citizens sampled are satisfied with their standard of living. Suppose that 60% of the 1,000,000,000 citizens who live on the planet are satisfied with their living standards. What are the mean and standard deviation of the sampling distribution of the proportion of citizens who are satisfied with their standard of living?A certain planet with over 1,000,000 households has a mean household income of $1,000,000 with a standard deviation of $150,000. Rick plans to take random samples of 700 households and calculate the sample mean income. Then, calculate the mean and standard deviation of the sampling distribution of the sample mean.Rick is performing quality control tests on different portal guns since there is some variability in the manufacturing process. For example, a certain gun has a target thickness of 5mm. The distribution of thicknesses is skewed to the right with a mean of 5mm and a standard deviation of 1mm. A quality control check on this part involves taking a random sample of 35 points and calculating the mean thickness of those points. What is the shape of the sampling distribution of the sample mean thickness? What is the probability that the mean thickness in the sample is within 0.2mm of the target value? Rick takes an SRS of 75 citizens on a distant planet to see what proportion of citizens sampled are satisfied with their standard of living. Suppose that 60% of the 1,000,000,000 citizens who live on the planet are satisfied with their living standards. What are the mean and standard deviation of the sampling distribution of the proportion of citizens who are satisfied with their standard of living? A certain planet with over 1,000,000 households has a mean household income of $1,000,000 with a standard deviation of $150,000. Rick plans to take random samples of 700 households and calculate the sample mean income. Then, calculate the mean and standard deviation of the sampling distribution of the sample mean. Rick is performing quality control tests on different portal guns since there is some variability in the manufacturing process. For example, a certain gun has a target thickness of 5mm. The distribution of thicknesses is skewed to the right with a mean of 5mm and a standard deviation of 1mm. A quality control check on this part involves taking a random sample of 35 points and calculating the mean thickness of those points. What is the shape of the sampling distribution of the sample mean thickness? What is the probability that the mean thickness in the sample is within 0.2mm of the target value? def geomcdf_1(p, x): # implementing first approach prob = 0 for i in range(x-1): prob+=p*(1-p)**i return probdef geomcdf_2(p, x): # implementing second approach prob = 1-(1-p)**(x-1) return prob You have a standard deck of cards, and you are picking cards until you get a Queen (you replace the cards if they are not Queens). What is the probability that you need to pick 5 cards? And less than 10? And more than 12? You have a standard deck of cards, and you are picking cards until you get a Queen (you replace the cards if they are not Queens). What is the probability that you need to pick 5 cards? And less than 10? And more than 12? # Exactly 5p = 4/52p**1*(1-p)**40.055848076855744666# Less than 10geomcdf_2(p, 10)0.5134348005963145# More than 121 - geomcdf_2(p, 13)0.3826967066770909 2. Jorge conducts inspections on freezers. He finds that 94% of the freezers successfully pass the inspection. Let C be the number of freezers Jorge inspects until a freezer fails an inspection. Assume that the results of each inspection are independent. # Our probability of success is actually the probability of failing the inspectionp=1-0.94p**1*(1-p)**40.04684493760000003 3. Pedro makes 25% of the free kicks shots he attempts. For a warm-up, Pedro likes to shoot free kick shots until he makes one. Let M be the number of shots it takes Pedro to make his first free-kick. Assume that the results of each shot are independent. Find the probability that it takes Pedro fewer than 4 attempts to make his first shot. p=0.25# We can use our two functionsgeomcdf_2(p, 4)0.578125geomcdf_1(p, 4)0.578125# which are computing1-0.75**30.578125# and0.25+0.25*0.75+0.25*0.75**20.578125 4. Build a function that computes the Poisson PMF without using any functions from external packages besides np.exp from numpy. Choose some parameters and compare your result with the pmf function from scipy. def fact(k): k_ = 1 for i in range(1, k+1): k_ *= i return k_def poisson_pmf(k, λ): return np.exp(-λ)*λ**k/fact(k)poisson_pmf(1, 2)0.2706705664732254poisson.pmf(1, 2)0.2706705664732254 5. Build a function that computes the Poisson CDF without using any external package. Choose some parameters and compare your result with the cdf function from scipy. def poisson_cdf(x, λ): p = [] for i in range(x+1): p.append(poisson_pmf(i, λ)) return sum(p)poisson_cdf(2, 2)0.6766764161830635poisson.cdf(2, 2)0.6766764161830634
[ { "code": null, "e": 273, "s": 172, "text": "In a series of weekly articles, I will be covering some important topics of statistics with a twist." }, { "code": null, "e": 573, "s": 273, "text": "The goal is to use Python to help us get intuition on complex concepts, empirically test theoretical proofs, or build algorithms from scratch. In this series, you will find articles covering topics such as random variables, sampling distributions, confidence intervals, significance tests, and more." }, { "code": null, "e": 715, "s": 573, "text": "At the end of each article, you can find exercises to test your knowledge. The solutions will be shared in the article of the following week." }, { "code": null, "e": 742, "s": 715, "text": "Articles published so far:" }, { "code": null, "e": 794, "s": 742, "text": "Bernoulli and Binomial Random Variables with Python" }, { "code": null, "e": 862, "s": 794, "text": "From Binomial to Geometric and Poisson Random Variables with Python" }, { "code": null, "e": 919, "s": 862, "text": "Sampling Distribution of a Sample Proportion with Python" }, { "code": null, "e": 952, "s": 919, "text": "Confidence Intervals with Python" }, { "code": null, "e": 983, "s": 952, "text": "Significance Tests with Python" }, { "code": null, "e": 1050, "s": 983, "text": "Two-sample Inference for the Difference Between Groups with Python" }, { "code": null, "e": 1081, "s": 1050, "text": "Inference for Categorical Data" }, { "code": null, "e": 1101, "s": 1081, "text": "Advanced Regression" }, { "code": null, "e": 1130, "s": 1101, "text": "Analysis of Variance — ANOVA" }, { "code": null, "e": 1176, "s": 1130, "text": "As usual, the code is available on my GitHub." }, { "code": null, "e": 1847, "s": 1176, "text": "We often find ourselves wanting to estimate a parameter for a population, for instance, its mean or standard deviation. Usually, we cannot collect data from the overall population. In this case, the only way for us to estimate the parameters of our population is by random sampling from it. We define the size of the sample n and calculate a statistic for each sample. This statistic is what we use to calculate the parameter of the overall population. Notice that the statistic that we calculate for each random sample could be far from the population value because it is a random sample. That is why we perform this process a series of times, which we can call trials." }, { "code": null, "e": 2045, "s": 1847, "text": "Let’s define a straightforward example. We have a population of 100 athletes with numbered shirts with distinct values from 0 to 99. First, we calculate the parameters for our population, μ, and σ." }, { "code": null, "e": 2352, "s": 2045, "text": "import numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import bernoulli, norm, poissonfrom scipy import statsfrom scipy.stats import kurtosis, skewimport seaborn as snsX = np.random.choice(np.arange(0, 100), 100, replace=False)print(f'μ={X.mean()}')print(f'σ={X.std()}')μ=49.5σ=28.86607004772212" }, { "code": null, "e": 2390, "s": 2352, "text": "We take 100 random samples of size 5." }, { "code": null, "e": 2653, "s": 2390, "text": "rs = []for i in range(100): rs.append(np.random.choice(X, 5))rs = np.array(rs)# 5 examples of our random samplesrs[:5]array([[87, 73, 61, 91, 99], [10, 5, 46, 72, 92], [ 1, 3, 7, 59, 88], [ 1, 42, 87, 21, 42], [65, 9, 54, 88, 67]])" }, { "code": null, "e": 3002, "s": 2653, "text": "For each one, we calculate some statistic; in this case, the sample mean x̄. Thus, x̄ s an array of 100 values (the mean value of each sample). Let’s print the first 5 values and then plot a histogram to understand the sampling distribution's shape better. In fact, this is the sampling distribution of the sample mean for a sample size equal to 5." }, { "code": null, "e": 3094, "s": 3002, "text": "x_bar = rs.mean(axis=1)print(x_bar[:5])plt.hist(x_bar, bins=100);[82.2 45. 31.6 38.6 56.6]" }, { "code": null, "e": 3285, "s": 3094, "text": "We will start this section by creating two Random Variables (RV), a Bernoulli RV and a Binomial RV (if you are unfamiliar with the details, please see my previous articles from this series)." }, { "code": null, "e": 3522, "s": 3285, "text": "The problem at hand is the following, there are 20,000 distinct universes where Rick and Morty live and we want to calculate the proportion of Mortys that we can find if we visit one random universe. Let X be the following Bernoulli RV:" }, { "code": null, "e": 3560, "s": 3522, "text": "We already saw in a past article that" }, { "code": null, "e": 3564, "s": 3560, "text": "and" }, { "code": null, "e": 3676, "s": 3564, "text": "Now, let’s define a new RV, which is equal to the sum of 10 independent trials of X. This is a Binomial RV with" }, { "code": null, "e": 4200, "s": 3676, "text": "Now it is time to visit some universes and look for Morty there randomly. Imagine that we visit 10 universes each time, which are indeed samples that we are taking from the overall population of universes. Notice that we can consider these samples independent even if we choose distinct universes for the sample of 10. This is due to a very small number of samples compared to the population. There is, in fact, a 10% rule to assume independence in a random sampling without replacement from a population of a certain size." }, { "code": null, "e": 4224, "s": 4200, "text": "Time to look for Morty." }, { "code": null, "e": 4318, "s": 4224, "text": "p = 0.6n = 10X = bernoulli(p)Y = [X.rvs(n) for i in range(10000)]plt.hist(np.sum(Y, axis=1));" }, { "code": null, "e": 4754, "s": 4318, "text": "And there you go, this is the sampling distribution of the sampling proportion. How can we calculate its mean and standard deviation? The expected value for your sample proportion is the proportion of Mortys that we find in our visits, showing an unbiased estimation for the population parameter. In the same way, the standard deviation of the sample proportion is the standard deviation of our binomial random variable Y divided by n." }, { "code": null, "e": 5250, "s": 4754, "text": "print('Empirically calculated expected value: {}'.format(np.mean(np.mean(Y, axis=1))))print('Theoretical expected value: {}'.format(p))Empirically calculated expected value: 0.5977399999999999Theoretical expected value: 0.6print('Empirically calculated standard deviation: {}'.format(np.std(np.mean(Y, axis=1))))print('Theoretical standard deviation: {}'.format(np.sqrt(p*(1-p)/n)))Empirically calculated standard deviation: 0.15472844728749785Theoretical standard deviation: 0.15491933384829668" }, { "code": null, "e": 5553, "s": 5250, "text": "There you go; we arrive at very similar values. First, by performing a large number of trials of 10 visit tours to random universes. Secondly, by computing the theoretical values for this sampling distribution. In this article, we will understand exactly why these two approaches yield similar results." }, { "code": null, "e": 5649, "s": 5553, "text": "There are two conditions to consider a sampling distribution approximately normal in its shape." }, { "code": null, "e": 5916, "s": 5649, "text": "Let’s try an example. You ran a music store and received 100 new CDs every week (consider these to be a random sample). Your supplier states that they are delivering approximately 10% of Rock CDs. You calculate the weekly proportion of Rock CDs in the weekly sample." }, { "code": null, "e": 5963, "s": 5916, "text": "n = 100p = 0.1print(n*p)print(n*(1-p))10.090.0" }, { "code": null, "e": 6041, "s": 5963, "text": "The conditions are met. Let’s plot it and look at the resulting distribution." }, { "code": null, "e": 6376, "s": 6041, "text": "X = bernoulli(p)Y = [X.rvs(100) for i in range(10000)]normal = np.random.normal(p*n, np.sqrt(n*p*(1-p)), (1000, ))density = stats.gaussian_kde(normal)n_, x, _ = plt.hist(normal, bins=np.linspace(0, 20, 50), histtype=u'step', density=True) plt.close()plt.hist(np.sum(Y, axis=1), density=True)plt.plot(x, density(x));" }, { "code": null, "e": 6513, "s": 6376, "text": "Looks good and approximately normal. What if instead of a 10% probability of receiving Rock CDs, we were informed that it changed to 3%?" }, { "code": null, "e": 6563, "s": 6513, "text": "n = 100p_ = 0.03print(n*p_)print(n*(1-p_))3.097.0" }, { "code": null, "e": 6595, "s": 6563, "text": "The first condition is not met." }, { "code": null, "e": 6936, "s": 6595, "text": "X = bernoulli(p_)Y_ = [X.rvs(100) for i in range(10000)]normal = np.random.normal(p_*n, np.sqrt(n*p_*(1-p_)), (1000, ))density = stats.gaussian_kde(normal)n_, x, _ = plt.hist(normal, bins=np.linspace(0, 20, 50), histtype=u'step', density=True) plt.close()plt.hist(np.sum(Y_, axis=1), density=True)plt.plot(x, density(x));" }, { "code": null, "e": 6986, "s": 6936, "text": "In fact, our distribution is skewed to the right." }, { "code": null, "e": 7481, "s": 6986, "text": "Why are these conditions important? These are relevant when we need to answer questions about the probability of sampling proportions. For example, returning to our example and considering the initial information of 10% probability of receiving Rock CDs. Consider that you find on your first trial that 12% of the CDs were Rock CDs. Assuming that the true proportion is informed by your supplier, what would be the probability that more than 12% of the sample you searched consists of Rock CDs?" }, { "code": null, "e": 7620, "s": 7481, "text": "We already know that the sampling distribution is approximately normal. So we need to build our normal distribution and compute P(p>0.12)." }, { "code": null, "e": 8229, "s": 7620, "text": "print('Empirically calculated expected value: {}'.format(np.mean(np.mean(Y, axis=1))))print('Theoretical expected value: {}'.format(p))Empirically calculated expected value: 0.09973800000000001Theoretical expected value: 0.1print('Empirically calculated standard deviation: {}'.format(np.std(np.mean(Y, axis=1))))print('Theoretical standard deviation: {}'.format(np.sqrt(p*(1-p)/n)))Empirically calculated standard deviation: 0.029996189024607777Theoretical standard deviation: 0.030000000000000002n = 100p = 0.10p_ = 0.12print(f'P(p>0.12)={1-norm.cdf(p_, p, np.sqrt(p*(1-p)/n))}')P(p>0.12)=0.252492537546923" }, { "code": null, "e": 8638, "s": 8229, "text": "In the first section, we have calculated the number o Mortys that we found in samples of our population of universes using two different approaches. The first by deriving the theoretical properties of a sampling distribution of sampling proportions. The second one by estimating the parameters using the statistics of the sampling distribution. In this section, we will understand better the second approach." }, { "code": null, "e": 8685, "s": 8638, "text": "Let’s start by defining the population mean μ:" }, { "code": null, "e": 8787, "s": 8685, "text": "where N represents the population size or the 20,000 universes. The sample mean ȳ can be defined as," }, { "code": null, "e": 8917, "s": 8787, "text": "where n represents the sample size or one of the simple random samples of size 10 that we have drawn from the overall population." }, { "code": null, "e": 9031, "s": 8917, "text": "p = 0.6n = 10X = bernoulli(p)Y = [X.rvs(n) for i in range(10000)]# One random sampley_bar = np.mean(Y[0])y_bar0.9" }, { "code": null, "e": 9202, "s": 9031, "text": "Notice that ȳ is a statistic that we use to infer the population parameter. Nevertheless, these could be different as we are randomly taking samples from the population." }, { "code": null, "e": 9382, "s": 9202, "text": "We want to get the intuition on the Central Limit Theorem (CLT), and then we will get to its interest and applications. But, first, let’s define a clearly non-normal distribution." }, { "code": null, "e": 9541, "s": 9382, "text": "elements = np.arange(6)probabilities = [0.3, 0., 0.05, 0.05, 0.2, 0.4]X = np.random.choice(elements, 100, p=probabilities)sns.histplot(X, stat='probability');" }, { "code": null, "e": 9638, "s": 9541, "text": "Now, we can draw samples from it. We are going to draw samples of size 4 and calculate its mean." }, { "code": null, "e": 9750, "s": 9638, "text": "s_1 = np.random.choice(elements, 4, p=probabilities)print(s_1)x_bar_1 = np.mean(s_1)print(x_bar_1)[0 5 4 0]2.25" }, { "code": null, "e": 9792, "s": 9750, "text": "Let’s do the same procedure 10,000 times." }, { "code": null, "e": 10182, "s": 9792, "text": "s = []n=4for i in range(10000): s.append(np.random.choice(elements, n, p=probabilities))s = np.mean(np.asarray(s), axis=1)print('Kurtosis: ' + str(np.round(kurtosis(s),2)))print('Skew: ' + str(np.round(skew(s),2)))print('---')print('μ=' + str(np.round(np.mean(s), 2)))print('σ=' + str(np.round(np.std(s), 2)))sns.histplot(s, stat='probability');Kurtosis: -0.36Skew: -0.27---μ=3.06σ=1.06" }, { "code": null, "e": 10767, "s": 10182, "text": "The distribution above does not look like our original distribution anymore. The CTL tells us that as you take more samples and calculate their mean, the resulting distribution will approximate a normal distribution. We can measure it by the value of the skewness and kurtosis, which for a normal distribution should be zero. A positively skewed distribution has a tail to the right, while a negative one has a tail to the left. If the distribution has positive kurtosis, it has fatter tails than the normal distribution; conversely, the tails would be thinner in a negative scenario." }, { "code": null, "e": 10942, "s": 10767, "text": "What the CLT also tells us is that the approximation becomes better as the sample size increases. So let’s test it by increasing the sample size from 4 to 20 and then to 100." }, { "code": null, "e": 11332, "s": 10942, "text": "s = []n=20for i in range(10000): s.append(np.random.choice(elements, n, p=probabilities))s = np.mean(np.asarray(s), axis=1)print('Kurtosis: ' + str(np.round(kurtosis(s),2)))print('Skew: ' + str(np.round(skew(s),2)))print('---')print('μ=' + str(np.round(np.mean(s), 2)))print('σ=' + str(np.round(np.std(s), 2)))sns.histplot(s, stat='probability');Kurtosis: -0.1Skew: -0.09---μ=3.06σ=0.47" }, { "code": null, "e": 11724, "s": 11332, "text": "s = []n=100for i in range(10000): s.append(np.random.choice(elements, n, p=probabilities))s = np.mean(np.asarray(s), axis=1)print('Kurtosis: ' + str(np.round(kurtosis(s),2)))print('Skew: ' + str(np.round(skew(s),2)))print('---')print('μ=' + str(np.round(np.mean(s), 2)))print('σ=' + str(np.round(np.std(s), 2)))sns.histplot(s, stat='probability');Kurtosis: -0.08Skew: -0.03---μ=3.05σ=0.22" }, { "code": null, "e": 12442, "s": 11724, "text": "Notice how the last plot resembles a normal distribution. There is a convention that a sample size bigger than 30 is enough to approximate a normal distribution. Also, notice that the value of the mean and standard deviation of the sampling distribution that we have been plotting for the different sample sizes. Not surprisingly, the mean is the same as the original distribution. But the value for the standard deviation is indeed strange, as it has been shrinking. In fact, this is an important property to take note of: the standard deviation of our sampling distribution of sample means is the square root of the standard deviation of the original population divided by the sample size. Thus, we can write it as:" }, { "code": null, "e": 12621, "s": 12442, "text": "print(\"Theoretical value: \" + str(np.sqrt(X.var()/n)))print(\"Empirically computed: \" + str(s.std()))Theoretical value: 0.20789179878003847Empirically computed: 0.2151977077573086" }, { "code": null, "e": 12723, "s": 12621, "text": "This process is not specific to the sample mean; we could be, for instance, calculate the sample sum." }, { "code": null, "e": 13001, "s": 12723, "text": "s = []for i in range(10000): s.append(np.random.choice(elements, 100, p=probabilities))s = np.sum(np.asarray(s), axis=1)print('Kurtosis: ' + str(np.round(kurtosis(s),2)))print('Skew: ' + str(np.round(skew(s),2)))sns.histplot(s, stat='probability');Kurtosis: -0.04Skew: -0.02" }, { "code": null, "e": 13337, "s": 13001, "text": "I hope that now you see why the normal distribution is so often used to model different processes. Even if you do not know the distribution of a process that you want to describe statistically, if you add or take the mean of your measurements (assuming that they all have the same distribution), suddenly you get a normal distribution." }, { "code": null, "e": 13858, "s": 13337, "text": "The problem that we faced in this article is the estimation of parameters of a population. Very often we can not collect enough data to represent the entire population and so, we need to find another way to estimate its parameters. The method that we explored draws random samples from the population. From the random samples, we calculate statistics which we afterward use to infer the parameters of the population. We looked at sampling distributions of sampling proportions and sampling distributions of sample means." }, { "code": null, "e": 14148, "s": 13858, "text": "We also explored the CLT. It tells us that independently of the shape of the original distribution of a process that we want to describe statistically, the mean or sum of samples taken from this original distribution will approximate a normal distribution for a sample size larger than 30." }, { "code": null, "e": 14199, "s": 14148, "text": "You will get the solutions in next week’s article." }, { "code": null, "e": 15519, "s": 14199, "text": "Rick takes an SRS of 75 citizens on a distant planet to see what proportion of citizens sampled are satisfied with their standard of living. Suppose that 60% of the 1,000,000,000 citizens who live on the planet are satisfied with their living standards. What are the mean and standard deviation of the sampling distribution of the proportion of citizens who are satisfied with their standard of living?A certain planet with over 1,000,000 households has a mean household income of $1,000,000 with a standard deviation of $150,000. Rick plans to take random samples of 700 households and calculate the sample mean income. Then, calculate the mean and standard deviation of the sampling distribution of the sample mean.Rick is performing quality control tests on different portal guns since there is some variability in the manufacturing process. For example, a certain gun has a target thickness of 5mm. The distribution of thicknesses is skewed to the right with a mean of 5mm and a standard deviation of 1mm. A quality control check on this part involves taking a random sample of 35 points and calculating the mean thickness of those points. What is the shape of the sampling distribution of the sample mean thickness? What is the probability that the mean thickness in the sample is within 0.2mm of the target value?" }, { "code": null, "e": 15922, "s": 15519, "text": "Rick takes an SRS of 75 citizens on a distant planet to see what proportion of citizens sampled are satisfied with their standard of living. Suppose that 60% of the 1,000,000,000 citizens who live on the planet are satisfied with their living standards. What are the mean and standard deviation of the sampling distribution of the proportion of citizens who are satisfied with their standard of living?" }, { "code": null, "e": 16238, "s": 15922, "text": "A certain planet with over 1,000,000 households has a mean household income of $1,000,000 with a standard deviation of $150,000. Rick plans to take random samples of 700 households and calculate the sample mean income. Then, calculate the mean and standard deviation of the sampling distribution of the sample mean." }, { "code": null, "e": 16841, "s": 16238, "text": "Rick is performing quality control tests on different portal guns since there is some variability in the manufacturing process. For example, a certain gun has a target thickness of 5mm. The distribution of thicknesses is skewed to the right with a mean of 5mm and a standard deviation of 1mm. A quality control check on this part involves taking a random sample of 35 points and calculating the mean thickness of those points. What is the shape of the sampling distribution of the sample mean thickness? What is the probability that the mean thickness in the sample is within 0.2mm of the target value?" }, { "code": null, "e": 17064, "s": 16841, "text": "def geomcdf_1(p, x): # implementing first approach prob = 0 for i in range(x-1): prob+=p*(1-p)**i return probdef geomcdf_2(p, x): # implementing second approach prob = 1-(1-p)**(x-1) return prob" }, { "code": null, "e": 17286, "s": 17064, "text": "You have a standard deck of cards, and you are picking cards until you get a Queen (you replace the cards if they are not Queens). What is the probability that you need to pick 5 cards? And less than 10? And more than 12?" }, { "code": null, "e": 17508, "s": 17286, "text": "You have a standard deck of cards, and you are picking cards until you get a Queen (you replace the cards if they are not Queens). What is the probability that you need to pick 5 cards? And less than 10? And more than 12?" }, { "code": null, "e": 17661, "s": 17508, "text": "# Exactly 5p = 4/52p**1*(1-p)**40.055848076855744666# Less than 10geomcdf_2(p, 10)0.5134348005963145# More than 121 - geomcdf_2(p, 13)0.3826967066770909" }, { "code": null, "e": 17916, "s": 17661, "text": "2. Jorge conducts inspections on freezers. He finds that 94% of the freezers successfully pass the inspection. Let C be the number of freezers Jorge inspects until a freezer fails an inspection. Assume that the results of each inspection are independent." }, { "code": null, "e": 18039, "s": 17916, "text": "# Our probability of success is actually the probability of failing the inspectionp=1-0.94p**1*(1-p)**40.04684493760000003" }, { "code": null, "e": 18381, "s": 18039, "text": "3. Pedro makes 25% of the free kicks shots he attempts. For a warm-up, Pedro likes to shoot free kick shots until he makes one. Let M be the number of shots it takes Pedro to make his first free-kick. Assume that the results of each shot are independent. Find the probability that it takes Pedro fewer than 4 attempts to make his first shot." }, { "code": null, "e": 18542, "s": 18381, "text": "p=0.25# We can use our two functionsgeomcdf_2(p, 4)0.578125geomcdf_1(p, 4)0.578125# which are computing1-0.75**30.578125# and0.25+0.25*0.75+0.25*0.75**20.578125" }, { "code": null, "e": 18751, "s": 18542, "text": "4. Build a function that computes the Poisson PMF without using any functions from external packages besides np.exp from numpy. Choose some parameters and compare your result with the pmf function from scipy." }, { "code": null, "e": 18955, "s": 18751, "text": "def fact(k): k_ = 1 for i in range(1, k+1): k_ *= i return k_def poisson_pmf(k, λ): return np.exp(-λ)*λ**k/fact(k)poisson_pmf(1, 2)0.2706705664732254poisson.pmf(1, 2)0.2706705664732254" }, { "code": null, "e": 19122, "s": 18955, "text": "5. Build a function that computes the Poisson CDF without using any external package. Choose some parameters and compare your result with the cdf function from scipy." } ]
How to skip a particular test method in TestNG?
We can skip a particular test method in TestNG. To overlook a particular test method from execution in TestNG enabled helper attribute is used. This attribute has to be set to false to overlook a test method from execution. Code Implementation of Java class file. @Test(enabled=false) public void verifyRepay(){ System.out.println("Repayment successful"); } @Test public void Login(){ System.out.println("Login is successful "); } @Test public verifyHistory(){ System.out.println ("History verification is successful"); } Here the verifyRepay() method shall be overlooked during execution.
[ { "code": null, "e": 1326, "s": 1062, "text": "We can skip a particular test method in TestNG. To overlook a particular test method from execution in TestNG enabled helper attribute is used. This attribute has to be set to false to overlook a test method from execution. Code Implementation of Java class file." }, { "code": null, "e": 1593, "s": 1326, "text": "@Test(enabled=false)\npublic void verifyRepay(){\n System.out.println(\"Repayment successful\");\n}\n@Test\npublic void Login(){\n System.out.println(\"Login is successful \");\n}\n@Test\npublic verifyHistory(){\n System.out.println (\"History verification is successful\");\n}" }, { "code": null, "e": 1661, "s": 1593, "text": "Here the verifyRepay() method shall be overlooked during execution." } ]
Executing SQL Statements from a Text File on MySQL Client
Let us understand how SQL statements can be executed from a text file on the MySQL client. The mysql client is generally used in interactive way. Let us see an example of the same − shell> mysql db_name It is also possible to put the SQL statements in a file and then tell mysql to read the input from that specific file. To do this, a text file text_file is first created. This text file would contain the statements that need to be executed. Let us take an example to understand the same − shell> mysql db_name < text_file If a USE db_name statement is placed as the first statement in the text file, it is unnecessary to specify the database name on the command line. Let us take an example to understand the same − shell> mysql < text_file If mysql is already running, an SQL script file can be executed using the source command or \. command. Let us take an example to understand the same − mysql> source file_name mysql> \. file_name Sometimes the user may want the script to display progress information to them. For this insert statements like that given below can be used − SELECT '<info_to_display>' AS ' '; <info_to_display> The mysql can also be invoked with the help of --verbose option. This causes every statement to be displayed before the result it produces. The mysql ignores Unicode byte order mark (BOM) characters at the beginning of input files. The mysql ignores Unicode byte order mark (BOM) characters at the beginning of input files. Before this functionality, they were read and sent over to the server, thereby resulting in a syntax error. Before this functionality, they were read and sent over to the server, thereby resulting in a syntax error. The present of a BOM doesn’t cause mysql to change its default character set. The present of a BOM doesn’t cause mysql to change its default character set. To do this, mysql can be invoked with an option like --default-character-set=utf8. To do this, mysql can be invoked with an option like --default-character-set=utf8.
[ { "code": null, "e": 1244, "s": 1062, "text": "Let us understand how SQL statements can be executed from a text file on the MySQL client. The mysql client is generally used in interactive way. Let us see an example of the same −" }, { "code": null, "e": 1265, "s": 1244, "text": "shell> mysql db_name" }, { "code": null, "e": 1436, "s": 1265, "text": "It is also possible to put the SQL statements in a file and then tell mysql to read the input from that specific file. To do this, a text file text_file is first created." }, { "code": null, "e": 1554, "s": 1436, "text": "This text file would contain the statements that need to be executed. Let us take an example to understand the same −" }, { "code": null, "e": 1587, "s": 1554, "text": "shell> mysql db_name < text_file" }, { "code": null, "e": 1781, "s": 1587, "text": "If a USE db_name statement is placed as the first statement in the text file, it is unnecessary to specify the database name on the command line. Let us take an example to understand the same −" }, { "code": null, "e": 1806, "s": 1781, "text": "shell> mysql < text_file" }, { "code": null, "e": 1958, "s": 1806, "text": "If mysql is already running, an SQL script file can be executed using the source command or \\. command. Let us take an example to understand the same −" }, { "code": null, "e": 2002, "s": 1958, "text": "mysql> source file_name\nmysql> \\. file_name" }, { "code": null, "e": 2145, "s": 2002, "text": "Sometimes the user may want the script to display progress information to them. For this insert statements like that given below can be used −" }, { "code": null, "e": 2180, "s": 2145, "text": "SELECT '<info_to_display>' AS ' ';" }, { "code": null, "e": 2198, "s": 2180, "text": "<info_to_display>" }, { "code": null, "e": 2338, "s": 2198, "text": "The mysql can also be invoked with the help of --verbose option. This causes every statement to be displayed before the result it produces." }, { "code": null, "e": 2430, "s": 2338, "text": "The mysql ignores Unicode byte order mark (BOM) characters at the beginning of input files." }, { "code": null, "e": 2522, "s": 2430, "text": "The mysql ignores Unicode byte order mark (BOM) characters at the beginning of input files." }, { "code": null, "e": 2630, "s": 2522, "text": "Before this functionality, they were read and sent over to the server, thereby resulting in a syntax error." }, { "code": null, "e": 2738, "s": 2630, "text": "Before this functionality, they were read and sent over to the server, thereby resulting in a syntax error." }, { "code": null, "e": 2816, "s": 2738, "text": "The present of a BOM doesn’t cause mysql to change its default character set." }, { "code": null, "e": 2894, "s": 2816, "text": "The present of a BOM doesn’t cause mysql to change its default character set." }, { "code": null, "e": 2977, "s": 2894, "text": "To do this, mysql can be invoked with an option like --default-character-set=utf8." }, { "code": null, "e": 3060, "s": 2977, "text": "To do this, mysql can be invoked with an option like --default-character-set=utf8." } ]
Accessing Values of Lists in Python
To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. Live Demo #!/usr/bin/python list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5, 6, 7 ]; print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5] When the above code is executed, it produces the following result − list1[0]: physics list2[1:5]: [2, 3, 4, 5]
[ { "code": null, "e": 1198, "s": 1062, "text": "To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index." }, { "code": null, "e": 1209, "s": 1198, "text": " Live Demo" }, { "code": null, "e": 1367, "s": 1209, "text": "#!/usr/bin/python\nlist1 = ['physics', 'chemistry', 1997, 2000];\nlist2 = [1, 2, 3, 4, 5, 6, 7 ];\nprint \"list1[0]: \", list1[0]\nprint \"list2[1:5]: \", list2[1:5]" }, { "code": null, "e": 1435, "s": 1367, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 1478, "s": 1435, "text": "list1[0]: physics\nlist2[1:5]: [2, 3, 4, 5]" } ]
Convert Unicode to UTF-8 in Java
Before moving onto their conversions, let us learn about Unicode and UTF-8. Unicode is an international standard of character encoding which has the capability of representing a majority of written languages all over the globe. Unicode uses hexadecimal to represent a character. Unicode is a 16-bit character encoding system. The lowest value is \u0000 and the highest value is \uFFFF. UTF-8 is a variable width character encoding. UTF-8 has the ability to be as condensed as ASCII but can also contain any Unicode characters with some increase in the size of the file. UTF stands for Unicode Transformation Format. The '8' signifies that it allocates 8-bit blocks to denote a character. The number of blocks needed to represent a character varies from 1 to 4. In order to convert Unicode to UTF-8 in Java, we use the getBytes() method. The getBytes() method encodes a String into a sequence of bytes and returns a byte array. Declaration - The getBytes() method is declared as follows. public byte[] getBytes(String charsetName) where charsetName is the specific charset by which the String is encoded into an array of bytes. Let us see a program to convert Unicode to UTF-8 in Java using the getBytes() method. Live Demo public class Example { public static void main(String[] args) throws Exception { String str1 = "\u0000"; String str2 = "\uFFFF"; byte[] arr = str1.getBytes("UTF-8"); byte[] brr = str2.getBytes("UTF-8"); System.out.println("UTF-8 for \\u0000"); for(byte a: arr) { System.out.print(a); } System.out.println("\nUTF-8 for \\uffff" ); for(byte b: brr) { System.out.print(b); } } } UTF-8 for \u0000 0 UTF-8 for \uffff -17-65-65 Let us understand the above program. We have created two Strings. String str1 = "\u0000"; String str2 = "\uFFFF"; String str1 is assigned \u0000 which is the lowest value in Unicode. String str2 is assigned \uFFFF which is the highest value in Unicode. To convert them into UTF-8, we use the getBytes(“UTF-8”) method. This gives us an array of bytes as follows − byte[] arr = str1.getBytes("UTF-8"); byte[] brr = str2.getBytes("UTF-8"); Then to print the byte array, we use an enhanced for loop as follows − for(byte a: arr) { System.out.print(a); } for(byte b: brr) { System.out.print(b); }
[ { "code": null, "e": 1138, "s": 1062, "text": "Before moving onto their conversions, let us learn about Unicode and UTF-8." }, { "code": null, "e": 1448, "s": 1138, "text": "Unicode is an international standard of character encoding which has the capability of representing a majority of written languages all over the globe. Unicode uses hexadecimal to represent a character. Unicode is a 16-bit character encoding system. The lowest value is \\u0000 and the highest value is \\uFFFF." }, { "code": null, "e": 1823, "s": 1448, "text": "UTF-8 is a variable width character encoding. UTF-8 has the ability to be as condensed as ASCII but can also contain any Unicode characters with some increase in the size of the file. UTF stands for Unicode Transformation Format. The '8' signifies that it allocates 8-bit blocks to denote a character. The number of blocks needed to represent a character varies from 1 to 4." }, { "code": null, "e": 1989, "s": 1823, "text": "In order to convert Unicode to UTF-8 in Java, we use the getBytes() method. The getBytes() method encodes a String into a sequence of bytes and returns a byte array." }, { "code": null, "e": 2049, "s": 1989, "text": "Declaration - The getBytes() method is declared as follows." }, { "code": null, "e": 2092, "s": 2049, "text": "public byte[] getBytes(String charsetName)" }, { "code": null, "e": 2189, "s": 2092, "text": "where charsetName is the specific charset by which the String is encoded into an array of bytes." }, { "code": null, "e": 2275, "s": 2189, "text": "Let us see a program to convert Unicode to UTF-8 in Java using the getBytes() method." }, { "code": null, "e": 2286, "s": 2275, "text": " Live Demo" }, { "code": null, "e": 2746, "s": 2286, "text": "public class Example {\n public static void main(String[] args) throws Exception {\n String str1 = \"\\u0000\";\n String str2 = \"\\uFFFF\";\n byte[] arr = str1.getBytes(\"UTF-8\");\n byte[] brr = str2.getBytes(\"UTF-8\");\n System.out.println(\"UTF-8 for \\\\u0000\");\n for(byte a: arr) {\n System.out.print(a);\n }\n System.out.println(\"\\nUTF-8 for \\\\uffff\" );\n for(byte b: brr) {\n System.out.print(b);\n }\n }\n}" }, { "code": null, "e": 2792, "s": 2746, "text": "UTF-8 for \\u0000\n0\nUTF-8 for \\uffff\n-17-65-65" }, { "code": null, "e": 2858, "s": 2792, "text": "Let us understand the above program. We have created two Strings." }, { "code": null, "e": 2906, "s": 2858, "text": "String str1 = \"\\u0000\";\nString str2 = \"\\uFFFF\";" }, { "code": null, "e": 3045, "s": 2906, "text": "String str1 is assigned \\u0000 which is the lowest value in Unicode. String str2 is assigned \\uFFFF which is the highest value in Unicode." }, { "code": null, "e": 3155, "s": 3045, "text": "To convert them into UTF-8, we use the getBytes(“UTF-8”) method. This gives us an array of bytes as follows −" }, { "code": null, "e": 3229, "s": 3155, "text": "byte[] arr = str1.getBytes(\"UTF-8\");\nbyte[] brr = str2.getBytes(\"UTF-8\");" }, { "code": null, "e": 3300, "s": 3229, "text": "Then to print the byte array, we use an enhanced for loop as follows −" }, { "code": null, "e": 3390, "s": 3300, "text": "for(byte a: arr) {\n System.out.print(a);\n}\nfor(byte b: brr) {\n System.out.print(b);\n}" } ]
How to Install Tensorflow 2.1 on Ubuntu 18.04 LTS with GPU support: Nvidia Drivers, CUDA 10 and cuDNN | by Dr. Joanne Kitson | Towards Data Science
In Part 1 of this series, I discussed how you can upgrade your PC hardware to incorporate a CUDA Toolkit compatible graphics processing card and I installed an Nvidia GTX 1060 6GB. Part 2 of the series covered the installation of CUDA, cuDNN and Tensorflow on Windows 10. In Part 3, I wiped Windows 10 from my PC and installed Ubuntu 18.04 LTS from a bootable DVD. In this Part 4 of the series, I am installing drivers for the Nvidia GPU which are compatible with the version of CUDA Toolkit, cuDNN and Tensorflow I wish to install on Ubuntu 18.04, namely Tensorflow 2.1 — this requires CUDA 10.1 or above. In doing so, in my case this involves also handling my current installations of Nvidia drivers, CUDA, cuDNN, and Tensorflow (details of which are set out at Step 1). The version of Tensorflow you select will determine the compatible versions of CUDA, cuDNN, compiler, toolchain and the Nvidia driver versions to install. Therefore before moving through the steps of installing an Nvidia driver, CUDA, cuDNN and then Tensorflow 2.1, I’m “beginning with the end in mind” and first checking the correct software versions compatible with my target version of Tensorflow. According to the Tensorflow website and CUDA installation guide: NVIDIA GPU drivers — CUDA 10.1 requires 418.x or higher. CUDA® Toolkit — TensorFlow supports CUDA 10.1 (TensorFlow >= 2.1.0). Tensorflow 1.13 and above requires CUDA 10. I would like to be able to install various versions of Tensorflow (with GPU support) between 1.13–2.1, so CUDA 10.1 is definitely required CUPTI (ships with the CUDA Toolkit) g++ compiler and toolchain cuDNN SDK (>= 7.6) (Optional) TensorRT 6.0 to improve latency and throughput for inference on some models. When I previously installed Tensorflow on this Ubuntu 18.04 machine, only Tensorflow 1.12/CUDA 9 was available and CUDA 10 was not yet compatible with Tensorflow. I therefore already have the following installed on this machine prior to completing the new steps below: Tensorflow version 1.12 CUDA Toolkit version 9.0 cuDNN version of 7.2, required for Tensorflow version 1.12 gcc and g++ compilers and toolchain NVIDIA GPU driver 390.132 (CUDA 9.0 requires 384.x or greater) Prior to starting CUDA download and installation, make the checks suggested here on the Nvidia CUDA website: Verify the system has a CUDA-capable GPU Verify the system is running a supported version of Linux. Verify the system has gcc installed. Verify the system has the correct kernel headers and development packages installed. Step 2.1: Check the system has a CUDA capable GPU Run the following command in your Ubuntu terminal to check your graphics card (GPU): lspci | grep -i nvidia If your graphics card is from NVIDIA and it is listed here , your GPU is CUDA-capable. Step 2.2: Check for your upcoming CUDA installation that your version of linux is supported Check your system version using the following command: uname -m && cat /etc/*release When you get that result relating to your system version, you can check the CUDA online documentation to ensure that that version is supported. Step 2.3: Check gcc installation gcc --version Step 2.4: Check that Ubuntu system has the correct kernel headers and development packages are installed The version of the kernel your system is running can be found by running the following command: uname -r For Ubuntu, the kernel headers and development packages for the currently running kernel can be installed with: # my current kernel header is 4.15.0-99-generic, yours may differuname_r =”4.15.0-99-generic” sudo apt-get install linux-headers-${uname_r} Step 2.5: Check any current Nvidia drivers You also can check what Nvidia GPU driver you currently have (if any) by running the ‘nvidia-smi’ command, and you can see that initially, I have Nvidia driver 390.132: Next, download the Nvidia package repositories. These commands are based on the instructions from the Tensorflow website to add Nvidia package repositories. Start by downloading the CUDA 10.1 .deb file by typing the following into the bash terminal on your Ubuntu 18.04 machine: wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-repo-ubuntu1804_10.1.243-1_amd64.deb Next, get the keys: sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub Then install the CUDA 10.1 .deb file for 64 bit Ubuntu 18.04: sudo dpkg -i cuda-repo-ubuntu1804_10.1.243-1_amd64.deb Run the update packages command to download the updated versions of various packages: sudo apt-get update Get further Nvidia package repositories for CUDA 10.1 (as per commands on Tensorflow website): wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/nvidia-machine-learning-repo-ubuntu1804_1.0.0-1_amd64.deb Once the Nvidia package repositories have been downloaded, install the Nvidia .deb package with privileges (sudo): sudo apt install ./nvidia-machine-learning-repo-ubuntu1804_1.0.0-1_amd64.deb And update packages again: sudo apt-get update I have NVIDIA Driver version 390 installed already; install nvidia driver version 430. sudo apt-get install --no-install-recommends nvidia-driver-430 I get the message that my system has unmet dependencies, so I remedied this by removing the PPA by using the following command (note: -r is for remove): sudo apt-add-repository -r ppa:graphics-drivers/ppa Make sure package listing is up to date: sudo apt update Remove all the existing nvidia drivers: sudo apt-get remove --purge '^nvidia-.*' Then try reinstalling the Nvidia driver version 430: sudo apt-get install --no-install-recommends nvidia-driver-430 The fresh Nvidia version 430 driver install gives the output below and completes successfully. Once you have installed nvidia driver 430, shutdown and restart your PC. Check that the new GPU driver is visible with the following command in your bash terminal: nvidia-smi The output of that command will look something like this and will confirm that the new Nvidia driver version is 430.50. Note that the CUDA Version is now 10.1 (as installed above): In order to install the CUDA and cuDNN development and runtime libraries, the Tensorflow installation page recommends the following commands: First, the installation of CUDA 10.1; when this is is run, it will take about 20-30 min to download, unpack and install: # Install development and runtime libraries (~4GB)sudo apt-get install --no-install-recommends cuda-10-1 Note that amongst the terminal print out, there is an instruction to ‘reboot your computer and verify that the NVIDIA graphics driver can be loaded’ (Fig 6.2). The installation messages complete as follows (Fig 6.3) Reboot the computer (as per the instruction in Fig 6.2). Following reboot, run the following command to check the installation of drivers again: nvidia-smi Note that following the reboot, the NVIDIA driver has (unexpectedly) been upgraded to version 440.64.00, and the CUDA version upgraded from version 10.1 to 10.2, as shown in Fig 7.1. Accordingly, I am choosing the appropriate cuDNN for CUDA 10.2 for the instructions below. You can download cuDNN from here. Below are the steps which I took to download the cuDNN files. You have to register in order to download cuDNN (free) and the login screenshot is shown at Fig 8.2: Once you have logged in, then you are taken to a cuDNN Download page: In order to get the v.7.6.4 or any other slightly older cuDNN version, click on “Archived cuDNN Releases” shown in Fig 8.3. As it appears that CUDA 10.2 has been installed above on my machine (rather than CUDA 10.1), I have selected the appropriate cuDNN library for CUDA 10.2. This is cuDNN version 7.6.5: From Fig. 8.4, choose the following three items from the list: cuDNN Runtime Library for Ubuntu 18.04 (Deb) cuDNN Developer Library for Ubuntu 18.04 (Deb) cuDNN Code Samples and User Guide for Ubuntu 18.04 (Deb) — optional This gives the following .deb packages to be downloaded: In order to install cuDNN, instructions some instructions are available from the tensorflow website with more detailed commands for the cuDNN libraries from the guidance in the cuDNN installation guide. There is a screenshot shown from this below: # change directory to where the cuDNN runtime library is downloaded cd ~/Downloads# Install cuDNN runtime librarysudo dpkg -i libcudnn7_7.6.5.32-1+cuda10.2_amd64.deb# Install cuDNN developer librarysudo dpkg -i libcudnn7-dev_7.6.5.32-1+cuda10.2_amd64.deb# (optional) install code samples and the cuDNN library documentationsudo dpkg -i libcudnn7-doc_7.6.5.32-1+cuda10.2_amd64.deb Following the downloads relating to cuDNN in Step 9, this step 10 covers testing the new cuDNN installation. Commands for testing of the cuDNN installation is covered in the cuDNN Installation guide: Applying the in the cuDNN installation guide, verify that cuDNN is installed and running properly by compiling the mnistCUDNN sample located in the /usr/scr/cudnn_samples_v7 , installed by the Debian (.deb) files. When you have installed the .deb files, you can find the example below by going to the /usr/src folder and there you can see ‘cudnn_samples_v7’ (Fig 10.1): Then copy the cudnn_samples_v7 folder to home, as shown in Fig 10.1: After copying the samples folder to the home folder (where you can run them) change directory into the mnistCUDNN folder, and run the following to compile the mnistCUDNN example: make clean && make The output of this command is shown in Fig 9.8: Then run the mnistCUDNN example within the mnishCUDNN folder by using the following command: ./mnistCUDNN When you run the mnistCUDNN example, a successful run should finish with “Test passed!” together with the classification result, as shown in Fig 10.4. The final package listed as part of the software requirements is the optional Tensorflow RT, which can be downloaded and installed “to improve latency and throughput for inference on some models”. The installation instructions for Tensorflow RT are outlined on Tensorflow’s own website here, but more detailed instructions and clearer information on tensorflow RT installation for different operating systems, including Linux Debian which I am using can be found here. Clicking ‘Download’ in Fig 11.1 takes you to the page with the screenshot shown in Fig 11.2 (note that you have to have a free registration for this as with cuDNN, and log in again using your Nvidia developer credentials you used for cuDNN above, in order to download TensorRT): This takes you to a further page (Fig 11.3) which shows the available TensorRT versions. I have chosen to download TensorRT 6 as per the Tensorflow suggestions at Step 1. Having chosen TensorRT 6.0, this provides further download choices shown in Fig 11.4: I’m choosing TensorRT 6.0.1.8 GA for Ubuntu 1804 and CUDA 10.2 .deb local repo packages (as my system changed to having CUDA 10.2 rather than 10.1 during the steps above). You can check the version(s) of CUDA you have installed, as follows: Fig. 11.6 shows that I have CUDA 9.0, CUDA 10.1 and CUDA 10.2 (CUDA 10.2 was installed last). Based on this excellent article called MultiCUDA: Multiple Versions of CUDA on One Machine, multiple versions of CUDA can live side by side. It states “Installing multiple versions won’t cause any of the previous versions to get overwritten, so no need to worry. Each version you install will overwrite the configurations that cause the operating system to use a certain version, but by default, they all get installed under /usr/local in separate directories by their version numbers.” I have therefore left all three versions of CUDA in place — CUDA 10.2 will be used in the first instance. Notes on installing Tensorflow RT are on the Nvidia website here. I am installing the .deb version of Tensorflow RT, which as Fig 12.1 above states automatically installs dependencies. The version independent instructions for installing Tensorflow RT are as follows: os=”ubuntu1x04”tag=”cudax.x-trt7.x.x.x-ea-yyyymmdd”sudo dpkg -i nv-tensorrt-repo-${os}-${tag}_1-1_amd64.debsudo apt-key add /var/nv-tensorrt-repo-${tag}/7fa2af80.pubsudo apt-get updatesudo apt-get install tensorrt The .deb file for TensorRT which I have downloaded is “nv-tensorrt-repo-ubuntu1804-cuda10.2-trt6.0.1.8-ga-20191108_1–1_amd64.deb” and I have downloaded it to ‘Downloads. For my operating system and CUDA ‘tag’, these installation instructions become: # change directory to where you have downloaded the .deb file # (in my case, downloads)cd ~/Downloads# specific instructions for nv-tensorrt-repo-ubuntu1804-cuda10.2-trt6.0.1.8-ga-20191108_1–1_amd64.deb os=”ubuntu1804”tag=”cuda10.2-trt6.0.1.8-ga-20191108”sudo dpkg -i nv-tensorrt-repo-${os}-${tag}_1-1_amd64.debsudo apt-key add /var/nv-tensorrt-repo-${tag}/7fa2af80.pub Changing to the Downloads folder and installing the TensorflowRT .deb file is shown in the terminal in Fig 12.2. Having added the key for the TensorRT installation, finally, update packages, and install Tensor RT. This will take a few minutes. You will be prompted for a ‘y/n’ answer during tensor RT installation, which you can pre-empt by adding a ‘-y’ flag to the installation command. sudo apt-get update#install tensor rt - optionally add a '-y' flag at the end of the command below to pre-empt the prompt sudo apt-get install tensorrt -y As per the instructionshere, use the following command: sudo apt-get install python3-libnvinfer-dev If you plan to use TensorRT with TensorFlow, run the following command: sudo apt-get install uff-converter-tf Verify the TensorRT installation using the following command:- dpkg -l | grep TensorRT Every installation step I have carried out up until this point (as described in the steps above) has been a system wide installation. You could install Tensorflow on a similar system wide basis, but it is more advisable to install it within a virtual environment so that it stops your Tensorflow installation unintentionally installing/uninstalling (or generally interfering with) other packages. This step sets out installation within a new virtual environment using the command line and Pycharm IDE, but you can create a virtual environment using your preferred method. The commands for installing Tensorflow 2 within a virtual environment are here. As of Tensorflow version [X], there is no separate installation command for the CPU and GPU supported versions respectively. I have created an illustrative project in Pycharm to show the initial creation of the virtual environment. The version of Pycharm is Community Edition 2020.1.1. This starts by creating a new (demo) project in Pycharm, using File -> New Project as shown in Fig 13.1 This produces the window for creating a project within a virtual environment as shown in Fig 13.2 The window in Fig 13.2 gives the option to name the new project. If you click the arrow to the left of the words “Project Interpreter” it provides the options shown in Fig 13.3. Naming the project “example_tf_2” in the Location box makes changes to the window as shown in Fig 13.4 When you click ‘Create’ to create a new project, the window shown in Fig 13.5 appears: I choose ‘attach’ which adds this new project to the drop down list of other projects in Pycharm which I already have open. This now creates a new project folder called ‘example_tf_2’; note that it has a ‘venv’ folder. In the bottom window of the Pycharm viewer (the Terminal), change directory to the relevant directory (in this case, the new project directory is “example_tf_2”.) Activate your new virtual environment (called ‘venv’) by using the following command in the command line: source venv/bin/activate If you have called your virtual environment something else e.g. ‘myvenv’, then the corresponding command would instead be: source myvenv/bin/activate When you run the activation command, then the command line changes to show you “(venv)” at the beginning which means that the virtual environment has now been activated. To install Tensorflow within this virtual environment, run the following pip command in the command line window (either in Pycharm or in your own terminal): # choosing 'tensorflow' without specifying the version installs the # latest stable version of tensorflow (here, version 2.1.0)# the command prompt should read something like:# (venv) /your/particular/path$# installs latest stable version of tensorflow, with GPU or CPU supportpip install tensorflow When the installation of Tensorflow 2.1.0 has finalised within the virtual environment, the terminal will return to the command prompt “$”: To test CUDA support for your Tensorflow installation and that Tensorflow has found your GPU devices, first invoke Python from within the terminal by typing ‘python’ at the command line: python The command prompt should change from “$” to “>>”. Then import Tensorflow, following which you can run the build test in the shell: # import tensorflow package import tensorflow as tf# test that tensorflow has been built with cudatf.test.is_built_with_cuda() This should return the output ‘True’. In order to check the GPU(s) found by Tensorflow, you can list these out using the following command: tf.config.list_physical_devices(‘GPU’) Tensorflow should output something like the example above — the name and device type. Finally, you could verify the install by using the command shown on the Tensorflow website (from a standard command prompt “$”). N.B. If you have the python command prompt (“>>>”) and wish to return to the standard shell command prompt (“$”), press CTRL+ Z. The command below imports Tensorflow and carries out a computation e.g.: python -c "import tensorflow as tf;print(tf.reduce_sum(tf.random.normal([1000, 1000])))" This will output information on your GPU and installed packages, together with the output to the test function. This article has set out the process I used to install new Nvidia drivers, CUDA, cuDNN and TensorRT (optional), all precursors to using Tensorflow 2 with GPU support on my Ubuntu 18.04 machine. Previously I have always used stand-alone Keras with a Tensorflow backend. Now with Tensorflow 2.0 and above, Keras is included in the form “tf.keras”, so it is no longer necessary to install Keras separately (although I suppose you still can). Tensorflow Keras (tf.keras) appears to have many of the same features of stand-alone Keras, and a guide for tf.keras can be found here. The guide states that tf.keras can run any Keras-compatible code, but note: The tf.keras version in the latest TensorFlow release might not be the same as the latest keras version from PyPI. Check tf.keras.version. When saving a model’s weights, tf.keras defaults to the checkpoint format. Pass save_format='h5' to use HDF5 (or pass a filename that ends in .h5).
[ { "code": null, "e": 536, "s": 171, "text": "In Part 1 of this series, I discussed how you can upgrade your PC hardware to incorporate a CUDA Toolkit compatible graphics processing card and I installed an Nvidia GTX 1060 6GB. Part 2 of the series covered the installation of CUDA, cuDNN and Tensorflow on Windows 10. In Part 3, I wiped Windows 10 from my PC and installed Ubuntu 18.04 LTS from a bootable DVD." }, { "code": null, "e": 944, "s": 536, "text": "In this Part 4 of the series, I am installing drivers for the Nvidia GPU which are compatible with the version of CUDA Toolkit, cuDNN and Tensorflow I wish to install on Ubuntu 18.04, namely Tensorflow 2.1 — this requires CUDA 10.1 or above. In doing so, in my case this involves also handling my current installations of Nvidia drivers, CUDA, cuDNN, and Tensorflow (details of which are set out at Step 1)." }, { "code": null, "e": 1345, "s": 944, "text": "The version of Tensorflow you select will determine the compatible versions of CUDA, cuDNN, compiler, toolchain and the Nvidia driver versions to install. Therefore before moving through the steps of installing an Nvidia driver, CUDA, cuDNN and then Tensorflow 2.1, I’m “beginning with the end in mind” and first checking the correct software versions compatible with my target version of Tensorflow." }, { "code": null, "e": 1410, "s": 1345, "text": "According to the Tensorflow website and CUDA installation guide:" }, { "code": null, "e": 1467, "s": 1410, "text": "NVIDIA GPU drivers — CUDA 10.1 requires 418.x or higher." }, { "code": null, "e": 1719, "s": 1467, "text": "CUDA® Toolkit — TensorFlow supports CUDA 10.1 (TensorFlow >= 2.1.0). Tensorflow 1.13 and above requires CUDA 10. I would like to be able to install various versions of Tensorflow (with GPU support) between 1.13–2.1, so CUDA 10.1 is definitely required" }, { "code": null, "e": 1755, "s": 1719, "text": "CUPTI (ships with the CUDA Toolkit)" }, { "code": null, "e": 1782, "s": 1755, "text": "g++ compiler and toolchain" }, { "code": null, "e": 1801, "s": 1782, "text": "cuDNN SDK (>= 7.6)" }, { "code": null, "e": 1889, "s": 1801, "text": "(Optional) TensorRT 6.0 to improve latency and throughput for inference on some models." }, { "code": null, "e": 2158, "s": 1889, "text": "When I previously installed Tensorflow on this Ubuntu 18.04 machine, only Tensorflow 1.12/CUDA 9 was available and CUDA 10 was not yet compatible with Tensorflow. I therefore already have the following installed on this machine prior to completing the new steps below:" }, { "code": null, "e": 2182, "s": 2158, "text": "Tensorflow version 1.12" }, { "code": null, "e": 2207, "s": 2182, "text": "CUDA Toolkit version 9.0" }, { "code": null, "e": 2266, "s": 2207, "text": "cuDNN version of 7.2, required for Tensorflow version 1.12" }, { "code": null, "e": 2302, "s": 2266, "text": "gcc and g++ compilers and toolchain" }, { "code": null, "e": 2365, "s": 2302, "text": "NVIDIA GPU driver 390.132 (CUDA 9.0 requires 384.x or greater)" }, { "code": null, "e": 2474, "s": 2365, "text": "Prior to starting CUDA download and installation, make the checks suggested here on the Nvidia CUDA website:" }, { "code": null, "e": 2515, "s": 2474, "text": "Verify the system has a CUDA-capable GPU" }, { "code": null, "e": 2574, "s": 2515, "text": "Verify the system is running a supported version of Linux." }, { "code": null, "e": 2611, "s": 2574, "text": "Verify the system has gcc installed." }, { "code": null, "e": 2696, "s": 2611, "text": "Verify the system has the correct kernel headers and development packages installed." }, { "code": null, "e": 2746, "s": 2696, "text": "Step 2.1: Check the system has a CUDA capable GPU" }, { "code": null, "e": 2831, "s": 2746, "text": "Run the following command in your Ubuntu terminal to check your graphics card (GPU):" }, { "code": null, "e": 2854, "s": 2831, "text": "lspci | grep -i nvidia" }, { "code": null, "e": 2941, "s": 2854, "text": "If your graphics card is from NVIDIA and it is listed here , your GPU is CUDA-capable." }, { "code": null, "e": 3033, "s": 2941, "text": "Step 2.2: Check for your upcoming CUDA installation that your version of linux is supported" }, { "code": null, "e": 3088, "s": 3033, "text": "Check your system version using the following command:" }, { "code": null, "e": 3118, "s": 3088, "text": "uname -m && cat /etc/*release" }, { "code": null, "e": 3262, "s": 3118, "text": "When you get that result relating to your system version, you can check the CUDA online documentation to ensure that that version is supported." }, { "code": null, "e": 3295, "s": 3262, "text": "Step 2.3: Check gcc installation" }, { "code": null, "e": 3309, "s": 3295, "text": "gcc --version" }, { "code": null, "e": 3414, "s": 3309, "text": "Step 2.4: Check that Ubuntu system has the correct kernel headers and development packages are installed" }, { "code": null, "e": 3510, "s": 3414, "text": "The version of the kernel your system is running can be found by running the following command:" }, { "code": null, "e": 3519, "s": 3510, "text": "uname -r" }, { "code": null, "e": 3631, "s": 3519, "text": "For Ubuntu, the kernel headers and development packages for the currently running kernel can be installed with:" }, { "code": null, "e": 3771, "s": 3631, "text": "# my current kernel header is 4.15.0-99-generic, yours may differuname_r =”4.15.0-99-generic” sudo apt-get install linux-headers-${uname_r}" }, { "code": null, "e": 3814, "s": 3771, "text": "Step 2.5: Check any current Nvidia drivers" }, { "code": null, "e": 3983, "s": 3814, "text": "You also can check what Nvidia GPU driver you currently have (if any) by running the ‘nvidia-smi’ command, and you can see that initially, I have Nvidia driver 390.132:" }, { "code": null, "e": 4262, "s": 3983, "text": "Next, download the Nvidia package repositories. These commands are based on the instructions from the Tensorflow website to add Nvidia package repositories. Start by downloading the CUDA 10.1 .deb file by typing the following into the bash terminal on your Ubuntu 18.04 machine:" }, { "code": null, "e": 4384, "s": 4262, "text": "wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-repo-ubuntu1804_10.1.243-1_amd64.deb" }, { "code": null, "e": 4404, "s": 4384, "text": "Next, get the keys:" }, { "code": null, "e": 4522, "s": 4404, "text": "sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub" }, { "code": null, "e": 4584, "s": 4522, "text": "Then install the CUDA 10.1 .deb file for 64 bit Ubuntu 18.04:" }, { "code": null, "e": 4639, "s": 4584, "text": "sudo dpkg -i cuda-repo-ubuntu1804_10.1.243-1_amd64.deb" }, { "code": null, "e": 4725, "s": 4639, "text": "Run the update packages command to download the updated versions of various packages:" }, { "code": null, "e": 4745, "s": 4725, "text": "sudo apt-get update" }, { "code": null, "e": 4840, "s": 4745, "text": "Get further Nvidia package repositories for CUDA 10.1 (as per commands on Tensorflow website):" }, { "code": null, "e": 4989, "s": 4840, "text": "wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/nvidia-machine-learning-repo-ubuntu1804_1.0.0-1_amd64.deb" }, { "code": null, "e": 5104, "s": 4989, "text": "Once the Nvidia package repositories have been downloaded, install the Nvidia .deb package with privileges (sudo):" }, { "code": null, "e": 5181, "s": 5104, "text": "sudo apt install ./nvidia-machine-learning-repo-ubuntu1804_1.0.0-1_amd64.deb" }, { "code": null, "e": 5208, "s": 5181, "text": "And update packages again:" }, { "code": null, "e": 5228, "s": 5208, "text": "sudo apt-get update" }, { "code": null, "e": 5315, "s": 5228, "text": "I have NVIDIA Driver version 390 installed already; install nvidia driver version 430." }, { "code": null, "e": 5378, "s": 5315, "text": "sudo apt-get install --no-install-recommends nvidia-driver-430" }, { "code": null, "e": 5531, "s": 5378, "text": "I get the message that my system has unmet dependencies, so I remedied this by removing the PPA by using the following command (note: -r is for remove):" }, { "code": null, "e": 5583, "s": 5531, "text": "sudo apt-add-repository -r ppa:graphics-drivers/ppa" }, { "code": null, "e": 5624, "s": 5583, "text": "Make sure package listing is up to date:" }, { "code": null, "e": 5640, "s": 5624, "text": "sudo apt update" }, { "code": null, "e": 5680, "s": 5640, "text": "Remove all the existing nvidia drivers:" }, { "code": null, "e": 5721, "s": 5680, "text": "sudo apt-get remove --purge '^nvidia-.*'" }, { "code": null, "e": 5774, "s": 5721, "text": "Then try reinstalling the Nvidia driver version 430:" }, { "code": null, "e": 5837, "s": 5774, "text": "sudo apt-get install --no-install-recommends nvidia-driver-430" }, { "code": null, "e": 5932, "s": 5837, "text": "The fresh Nvidia version 430 driver install gives the output below and completes successfully." }, { "code": null, "e": 6005, "s": 5932, "text": "Once you have installed nvidia driver 430, shutdown and restart your PC." }, { "code": null, "e": 6096, "s": 6005, "text": "Check that the new GPU driver is visible with the following command in your bash terminal:" }, { "code": null, "e": 6107, "s": 6096, "text": "nvidia-smi" }, { "code": null, "e": 6288, "s": 6107, "text": "The output of that command will look something like this and will confirm that the new Nvidia driver version is 430.50. Note that the CUDA Version is now 10.1 (as installed above):" }, { "code": null, "e": 6430, "s": 6288, "text": "In order to install the CUDA and cuDNN development and runtime libraries, the Tensorflow installation page recommends the following commands:" }, { "code": null, "e": 6551, "s": 6430, "text": "First, the installation of CUDA 10.1; when this is is run, it will take about 20-30 min to download, unpack and install:" }, { "code": null, "e": 6657, "s": 6551, "text": "# Install development and runtime libraries (~4GB)sudo apt-get install --no-install-recommends cuda-10-1 " }, { "code": null, "e": 6817, "s": 6657, "text": "Note that amongst the terminal print out, there is an instruction to ‘reboot your computer and verify that the NVIDIA graphics driver can be loaded’ (Fig 6.2)." }, { "code": null, "e": 6873, "s": 6817, "text": "The installation messages complete as follows (Fig 6.3)" }, { "code": null, "e": 7018, "s": 6873, "text": "Reboot the computer (as per the instruction in Fig 6.2). Following reboot, run the following command to check the installation of drivers again:" }, { "code": null, "e": 7029, "s": 7018, "text": "nvidia-smi" }, { "code": null, "e": 7303, "s": 7029, "text": "Note that following the reboot, the NVIDIA driver has (unexpectedly) been upgraded to version 440.64.00, and the CUDA version upgraded from version 10.1 to 10.2, as shown in Fig 7.1. Accordingly, I am choosing the appropriate cuDNN for CUDA 10.2 for the instructions below." }, { "code": null, "e": 7399, "s": 7303, "text": "You can download cuDNN from here. Below are the steps which I took to download the cuDNN files." }, { "code": null, "e": 7500, "s": 7399, "text": "You have to register in order to download cuDNN (free) and the login screenshot is shown at Fig 8.2:" }, { "code": null, "e": 7570, "s": 7500, "text": "Once you have logged in, then you are taken to a cuDNN Download page:" }, { "code": null, "e": 7877, "s": 7570, "text": "In order to get the v.7.6.4 or any other slightly older cuDNN version, click on “Archived cuDNN Releases” shown in Fig 8.3. As it appears that CUDA 10.2 has been installed above on my machine (rather than CUDA 10.1), I have selected the appropriate cuDNN library for CUDA 10.2. This is cuDNN version 7.6.5:" }, { "code": null, "e": 7940, "s": 7877, "text": "From Fig. 8.4, choose the following three items from the list:" }, { "code": null, "e": 7985, "s": 7940, "text": "cuDNN Runtime Library for Ubuntu 18.04 (Deb)" }, { "code": null, "e": 8032, "s": 7985, "text": "cuDNN Developer Library for Ubuntu 18.04 (Deb)" }, { "code": null, "e": 8100, "s": 8032, "text": "cuDNN Code Samples and User Guide for Ubuntu 18.04 (Deb) — optional" }, { "code": null, "e": 8157, "s": 8100, "text": "This gives the following .deb packages to be downloaded:" }, { "code": null, "e": 8405, "s": 8157, "text": "In order to install cuDNN, instructions some instructions are available from the tensorflow website with more detailed commands for the cuDNN libraries from the guidance in the cuDNN installation guide. There is a screenshot shown from this below:" }, { "code": null, "e": 8785, "s": 8405, "text": "# change directory to where the cuDNN runtime library is downloaded cd ~/Downloads# Install cuDNN runtime librarysudo dpkg -i libcudnn7_7.6.5.32-1+cuda10.2_amd64.deb# Install cuDNN developer librarysudo dpkg -i libcudnn7-dev_7.6.5.32-1+cuda10.2_amd64.deb# (optional) install code samples and the cuDNN library documentationsudo dpkg -i libcudnn7-doc_7.6.5.32-1+cuda10.2_amd64.deb" }, { "code": null, "e": 8985, "s": 8785, "text": "Following the downloads relating to cuDNN in Step 9, this step 10 covers testing the new cuDNN installation. Commands for testing of the cuDNN installation is covered in the cuDNN Installation guide:" }, { "code": null, "e": 9199, "s": 8985, "text": "Applying the in the cuDNN installation guide, verify that cuDNN is installed and running properly by compiling the mnistCUDNN sample located in the /usr/scr/cudnn_samples_v7 , installed by the Debian (.deb) files." }, { "code": null, "e": 9355, "s": 9199, "text": "When you have installed the .deb files, you can find the example below by going to the /usr/src folder and there you can see ‘cudnn_samples_v7’ (Fig 10.1):" }, { "code": null, "e": 9424, "s": 9355, "text": "Then copy the cudnn_samples_v7 folder to home, as shown in Fig 10.1:" }, { "code": null, "e": 9603, "s": 9424, "text": "After copying the samples folder to the home folder (where you can run them) change directory into the mnistCUDNN folder, and run the following to compile the mnistCUDNN example:" }, { "code": null, "e": 9622, "s": 9603, "text": "make clean && make" }, { "code": null, "e": 9670, "s": 9622, "text": "The output of this command is shown in Fig 9.8:" }, { "code": null, "e": 9763, "s": 9670, "text": "Then run the mnistCUDNN example within the mnishCUDNN folder by using the following command:" }, { "code": null, "e": 9776, "s": 9763, "text": "./mnistCUDNN" }, { "code": null, "e": 9927, "s": 9776, "text": "When you run the mnistCUDNN example, a successful run should finish with “Test passed!” together with the classification result, as shown in Fig 10.4." }, { "code": null, "e": 10124, "s": 9927, "text": "The final package listed as part of the software requirements is the optional Tensorflow RT, which can be downloaded and installed “to improve latency and throughput for inference on some models”." }, { "code": null, "e": 10396, "s": 10124, "text": "The installation instructions for Tensorflow RT are outlined on Tensorflow’s own website here, but more detailed instructions and clearer information on tensorflow RT installation for different operating systems, including Linux Debian which I am using can be found here." }, { "code": null, "e": 10675, "s": 10396, "text": "Clicking ‘Download’ in Fig 11.1 takes you to the page with the screenshot shown in Fig 11.2 (note that you have to have a free registration for this as with cuDNN, and log in again using your Nvidia developer credentials you used for cuDNN above, in order to download TensorRT):" }, { "code": null, "e": 10846, "s": 10675, "text": "This takes you to a further page (Fig 11.3) which shows the available TensorRT versions. I have chosen to download TensorRT 6 as per the Tensorflow suggestions at Step 1." }, { "code": null, "e": 10932, "s": 10846, "text": "Having chosen TensorRT 6.0, this provides further download choices shown in Fig 11.4:" }, { "code": null, "e": 11104, "s": 10932, "text": "I’m choosing TensorRT 6.0.1.8 GA for Ubuntu 1804 and CUDA 10.2 .deb local repo packages (as my system changed to having CUDA 10.2 rather than 10.1 during the steps above)." }, { "code": null, "e": 11173, "s": 11104, "text": "You can check the version(s) of CUDA you have installed, as follows:" }, { "code": null, "e": 11754, "s": 11173, "text": "Fig. 11.6 shows that I have CUDA 9.0, CUDA 10.1 and CUDA 10.2 (CUDA 10.2 was installed last). Based on this excellent article called MultiCUDA: Multiple Versions of CUDA on One Machine, multiple versions of CUDA can live side by side. It states “Installing multiple versions won’t cause any of the previous versions to get overwritten, so no need to worry. Each version you install will overwrite the configurations that cause the operating system to use a certain version, but by default, they all get installed under /usr/local in separate directories by their version numbers.”" }, { "code": null, "e": 11860, "s": 11754, "text": "I have therefore left all three versions of CUDA in place — CUDA 10.2 will be used in the first instance." }, { "code": null, "e": 11926, "s": 11860, "text": "Notes on installing Tensorflow RT are on the Nvidia website here." }, { "code": null, "e": 12127, "s": 11926, "text": "I am installing the .deb version of Tensorflow RT, which as Fig 12.1 above states automatically installs dependencies. The version independent instructions for installing Tensorflow RT are as follows:" }, { "code": null, "e": 12341, "s": 12127, "text": "os=”ubuntu1x04”tag=”cudax.x-trt7.x.x.x-ea-yyyymmdd”sudo dpkg -i nv-tensorrt-repo-${os}-${tag}_1-1_amd64.debsudo apt-key add /var/nv-tensorrt-repo-${tag}/7fa2af80.pubsudo apt-get updatesudo apt-get install tensorrt" }, { "code": null, "e": 12511, "s": 12341, "text": "The .deb file for TensorRT which I have downloaded is “nv-tensorrt-repo-ubuntu1804-cuda10.2-trt6.0.1.8-ga-20191108_1–1_amd64.deb” and I have downloaded it to ‘Downloads." }, { "code": null, "e": 12591, "s": 12511, "text": "For my operating system and CUDA ‘tag’, these installation instructions become:" }, { "code": null, "e": 12961, "s": 12591, "text": "# change directory to where you have downloaded the .deb file # (in my case, downloads)cd ~/Downloads# specific instructions for nv-tensorrt-repo-ubuntu1804-cuda10.2-trt6.0.1.8-ga-20191108_1–1_amd64.deb os=”ubuntu1804”tag=”cuda10.2-trt6.0.1.8-ga-20191108”sudo dpkg -i nv-tensorrt-repo-${os}-${tag}_1-1_amd64.debsudo apt-key add /var/nv-tensorrt-repo-${tag}/7fa2af80.pub" }, { "code": null, "e": 13074, "s": 12961, "text": "Changing to the Downloads folder and installing the TensorflowRT .deb file is shown in the terminal in Fig 12.2." }, { "code": null, "e": 13350, "s": 13074, "text": "Having added the key for the TensorRT installation, finally, update packages, and install Tensor RT. This will take a few minutes. You will be prompted for a ‘y/n’ answer during tensor RT installation, which you can pre-empt by adding a ‘-y’ flag to the installation command." }, { "code": null, "e": 13505, "s": 13350, "text": "sudo apt-get update#install tensor rt - optionally add a '-y' flag at the end of the command below to pre-empt the prompt sudo apt-get install tensorrt -y" }, { "code": null, "e": 13561, "s": 13505, "text": "As per the instructionshere, use the following command:" }, { "code": null, "e": 13605, "s": 13561, "text": "sudo apt-get install python3-libnvinfer-dev" }, { "code": null, "e": 13677, "s": 13605, "text": "If you plan to use TensorRT with TensorFlow, run the following command:" }, { "code": null, "e": 13715, "s": 13677, "text": "sudo apt-get install uff-converter-tf" }, { "code": null, "e": 13778, "s": 13715, "text": "Verify the TensorRT installation using the following command:-" }, { "code": null, "e": 13802, "s": 13778, "text": "dpkg -l | grep TensorRT" }, { "code": null, "e": 14199, "s": 13802, "text": "Every installation step I have carried out up until this point (as described in the steps above) has been a system wide installation. You could install Tensorflow on a similar system wide basis, but it is more advisable to install it within a virtual environment so that it stops your Tensorflow installation unintentionally installing/uninstalling (or generally interfering with) other packages." }, { "code": null, "e": 14579, "s": 14199, "text": "This step sets out installation within a new virtual environment using the command line and Pycharm IDE, but you can create a virtual environment using your preferred method. The commands for installing Tensorflow 2 within a virtual environment are here. As of Tensorflow version [X], there is no separate installation command for the CPU and GPU supported versions respectively." }, { "code": null, "e": 14740, "s": 14579, "text": "I have created an illustrative project in Pycharm to show the initial creation of the virtual environment. The version of Pycharm is Community Edition 2020.1.1." }, { "code": null, "e": 14844, "s": 14740, "text": "This starts by creating a new (demo) project in Pycharm, using File -> New Project as shown in Fig 13.1" }, { "code": null, "e": 14942, "s": 14844, "text": "This produces the window for creating a project within a virtual environment as shown in Fig 13.2" }, { "code": null, "e": 15120, "s": 14942, "text": "The window in Fig 13.2 gives the option to name the new project. If you click the arrow to the left of the words “Project Interpreter” it provides the options shown in Fig 13.3." }, { "code": null, "e": 15223, "s": 15120, "text": "Naming the project “example_tf_2” in the Location box makes changes to the window as shown in Fig 13.4" }, { "code": null, "e": 15310, "s": 15223, "text": "When you click ‘Create’ to create a new project, the window shown in Fig 13.5 appears:" }, { "code": null, "e": 15529, "s": 15310, "text": "I choose ‘attach’ which adds this new project to the drop down list of other projects in Pycharm which I already have open. This now creates a new project folder called ‘example_tf_2’; note that it has a ‘venv’ folder." }, { "code": null, "e": 15692, "s": 15529, "text": "In the bottom window of the Pycharm viewer (the Terminal), change directory to the relevant directory (in this case, the new project directory is “example_tf_2”.)" }, { "code": null, "e": 15798, "s": 15692, "text": "Activate your new virtual environment (called ‘venv’) by using the following command in the command line:" }, { "code": null, "e": 15824, "s": 15798, "text": "source venv/bin/activate " }, { "code": null, "e": 15947, "s": 15824, "text": "If you have called your virtual environment something else e.g. ‘myvenv’, then the corresponding command would instead be:" }, { "code": null, "e": 15974, "s": 15947, "text": "source myvenv/bin/activate" }, { "code": null, "e": 16144, "s": 15974, "text": "When you run the activation command, then the command line changes to show you “(venv)” at the beginning which means that the virtual environment has now been activated." }, { "code": null, "e": 16301, "s": 16144, "text": "To install Tensorflow within this virtual environment, run the following pip command in the command line window (either in Pycharm or in your own terminal):" }, { "code": null, "e": 16601, "s": 16301, "text": "# choosing 'tensorflow' without specifying the version installs the # latest stable version of tensorflow (here, version 2.1.0)# the command prompt should read something like:# (venv) /your/particular/path$# installs latest stable version of tensorflow, with GPU or CPU supportpip install tensorflow" }, { "code": null, "e": 16741, "s": 16601, "text": "When the installation of Tensorflow 2.1.0 has finalised within the virtual environment, the terminal will return to the command prompt “$”:" }, { "code": null, "e": 16928, "s": 16741, "text": "To test CUDA support for your Tensorflow installation and that Tensorflow has found your GPU devices, first invoke Python from within the terminal by typing ‘python’ at the command line:" }, { "code": null, "e": 16935, "s": 16928, "text": "python" }, { "code": null, "e": 17067, "s": 16935, "text": "The command prompt should change from “$” to “>>”. Then import Tensorflow, following which you can run the build test in the shell:" }, { "code": null, "e": 17194, "s": 17067, "text": "# import tensorflow package import tensorflow as tf# test that tensorflow has been built with cudatf.test.is_built_with_cuda()" }, { "code": null, "e": 17232, "s": 17194, "text": "This should return the output ‘True’." }, { "code": null, "e": 17334, "s": 17232, "text": "In order to check the GPU(s) found by Tensorflow, you can list these out using the following command:" }, { "code": null, "e": 17373, "s": 17334, "text": "tf.config.list_physical_devices(‘GPU’)" }, { "code": null, "e": 17459, "s": 17373, "text": "Tensorflow should output something like the example above — the name and device type." }, { "code": null, "e": 17717, "s": 17459, "text": "Finally, you could verify the install by using the command shown on the Tensorflow website (from a standard command prompt “$”). N.B. If you have the python command prompt (“>>>”) and wish to return to the standard shell command prompt (“$”), press CTRL+ Z." }, { "code": null, "e": 17790, "s": 17717, "text": "The command below imports Tensorflow and carries out a computation e.g.:" }, { "code": null, "e": 17879, "s": 17790, "text": "python -c \"import tensorflow as tf;print(tf.reduce_sum(tf.random.normal([1000, 1000])))\"" }, { "code": null, "e": 17991, "s": 17879, "text": "This will output information on your GPU and installed packages, together with the output to the test function." }, { "code": null, "e": 18185, "s": 17991, "text": "This article has set out the process I used to install new Nvidia drivers, CUDA, cuDNN and TensorRT (optional), all precursors to using Tensorflow 2 with GPU support on my Ubuntu 18.04 machine." }, { "code": null, "e": 18430, "s": 18185, "text": "Previously I have always used stand-alone Keras with a Tensorflow backend. Now with Tensorflow 2.0 and above, Keras is included in the form “tf.keras”, so it is no longer necessary to install Keras separately (although I suppose you still can)." }, { "code": null, "e": 18566, "s": 18430, "text": "Tensorflow Keras (tf.keras) appears to have many of the same features of stand-alone Keras, and a guide for tf.keras can be found here." }, { "code": null, "e": 18642, "s": 18566, "text": "The guide states that tf.keras can run any Keras-compatible code, but note:" }, { "code": null, "e": 18781, "s": 18642, "text": "The tf.keras version in the latest TensorFlow release might not be the same as the latest keras version from PyPI. Check tf.keras.version." } ]
How to set background color in HTML?
To set the background color in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <body> tag, with the CSS property background-color. HTML5 do not support the <body> tag bgcolor attribute, so the CSS style is used to add background color. The bgcolor attribute deprecated in HTML5. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet. You can try to run the following code to set the background color in HTML − <!DOCTYPE html> <html> <head> <title>HTML Backgorund Color</title> </head> <body style="background-color:grey;"> <h1>Products</h1> <p>We have developed more than 10 products till now.</p> </body> </html>
[ { "code": null, "e": 1422, "s": 1062, "text": "To set the background color in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <body> tag, with the CSS property background-color. HTML5 do not support the <body> tag bgcolor attribute, so the CSS style is used to add background color. The bgcolor attribute deprecated in HTML5." }, { "code": null, "e": 1584, "s": 1422, "text": "Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet." }, { "code": null, "e": 1660, "s": 1584, "text": "You can try to run the following code to set the background color in HTML −" }, { "code": null, "e": 1894, "s": 1660, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Backgorund Color</title>\n </head>\n <body style=\"background-color:grey;\">\n <h1>Products</h1>\n <p>We have developed more than 10 products till now.</p>\n </body>\n</html>" } ]
FAANG Ask These 4 Python Simulations in 2021 | by Leihua Ye, PhD | Towards Data Science
Updated on Jan-10–2021 1 2 3 4 5 6 7 8 9 10 Powered by Play.ht Create audio with Play.ht Powered by Play.ht Statistical Simulation is the most heavily tested topic in Data Science/Engineering Interviews! If we go over DS Interview questions posted at Glassdoor, statistical simulation is the key skill that all big tech companies expect their applicants to excel in. Interview scenarios may either be asked to perform a power analysis of A/B experiments or construct a binomial distribution to simulate user behaviors in a programming language, R or Python. These are not difficult questions but require a deep understanding of fundamental statistics and fluent programming skills. Without deliberate practice, these questions may likely trip you over. This post presents 4 types of the most often tested statistical distributions in Data Science interviews and live-code solutions in Python. In a previous post, I have covered the fundamentals of statistical thinking and R codes. In case you missed it, here is the portal: towardsdatascience.com Disclaimer: I assume my fellow readers understand the statistical basics (e.g., what a binomial distribution is) and some familiarity with the Python programming environment (e.g., how to write a simple for loop). Here is a light refresher on common statistical distributions by Zijing Zhu. In R or Python, please answer the following question. For a sequence of numbers, (a1,a2,a3,a4,...,an), please write a function that randomly returns each element, ai, with probability ai/∑ai. (Condition 1) For example, for a sequence (1,2,3,4), the function returns element 1 with a probability of 1/10 and 4 with a probability of 4/10. (Condition 2) You can use any library, but no random.choice(). (Condition 3) This is a real interview question that I asked by a travel company. Let’s break it down. The question asks for a function that returns an element proportional to its weights, ai/∑ai. It can be completed in two steps: # Step 1: Calculate the probability for each element ai with respect to the total sum ∑ai.# Step 2: Simulate the process and return the element (it is more complicated than it sounds). For step 1, we do something like the follow: import numpy as npdef weight_func(sequence):# step 1 prob = [] total_sum = sum(sequence) for i in range(len(sequence)): prob.append(sequence[i]/total_sum) # step 2: the following is pseudo-code return the element according to its probability Here, there is a catch with the question: we can’t use the built-in method, random.choice() (Condition 3). Hypothetically, it would be a much easier question if we are allowed to import the Numpy package. Alternatively, we have to develop something to perform the same functionality as the random choice. Back then, I was clueless right on the spot. My interviewer kindly offered his first hint: you can use a uniform distribution with a range from 0 to 1 and compare the generated value (named a) to the cumulative probability sum (named cum_prob[i]) at each position i. If cum_prob[i] > a, then return the corresponding value from the sequence. The idea sounds great, and let’s check how the Python codes look like. People make a common mistake by trying to use a control flow (if-else statements) to filter out scenarios. It is doable for a small sample size but not practical if there are thousands of numbers in the sequence. We are not using 1,000+ “if, elif, else” statements to tell Python what to do with the numbers, right? After looking back at this question months later, the most challenging part is to come up with the idea of using cumulative probability sum to simulate the process. It is more doable now after the detailed step-by-step explanations. An online shopping website (e.g., Amazon, Alibaba, etc.) wants to test out two versions of banners that will appear on the website’s top. The engineering team assigns the probability of visiting version A at 0.6 and version B at 0.4. After 10,000 visits, there are 6050 visitors being exposed to version A, and 3950 people exposed to version B. What is the probability that there are 6050 cases when the randomization process is correct? In other words, the probability for version A is indeed 0.6. This is a part of a hypothesis-testing question. Let’s break it down. There are two versions, A and B, and the experiment assigns the treatment to 10,000 people. So, it is a perfect setting for the adoption of a binomial distribution. However, the probability of receiving version A is slightly higher than version B. The final answer should return the probability of more than 6050 people receiving version A out of 10,000 trials. These pieces of information remind us to combine a binomial distribution with a conditional for loop, as shown below. 0.1498 The result is close to 15%, which carries practical value. This is a hypothesis testing question. Since the probability of observing 6,000 or above visitors is 15%, we fail to reject the null hypothesis and conclude there is no statistical difference between 6,000 and 6,050 visitors out of 10,000. In other words, the probability for version A is 0.6. We are have learned hypothesis testing and how to reject or fail to reject the null hypothesis, but a question like this makes me think twice about statistical simulation. My medium blog has 500 visits per day, and the number of visits follows a Poisson distribution. Out of 1000 times, what is the ratio of more than 510 visits per day? Write a function to simulate the process. This is a rather straightforward question. Since the question asks for how many times an event occurs in a specified time, we can follow a Poisson procedure. # step 1: create a poisson distribution# step 2: use an if clause to count the number 0.318 31.8% of the simulation results have more than 510 visits. After publishing this post, the number of Medium blog skyrockets to another level. Write a function to generate X samples from a normal distribution and plot the histogram. This is a question asked by Google. It is a relatively easy coding question with two steps: # step 1: generate a normal distribution# step 2: take X samples and plot the sampling distribution Here it goes. We generate a normal distribution with 100 numbers and set X equals to 10. array([ 7.27305691, 6.98741057, 14.37357218, 14.17422672, 7.57495374, 10.39904815, 7.27305691, 7.41182935, 10.565957, 12.0081078 ]) # X_samples The complete Python code is available on my Github. As a first step, we need to understand the question before moving on to the coding part. One of the biggest mistakes that job candidates make is to jump into the programming part without asking for clarification questions. They have to re-visit the question multiple times after getting stuck. This post focuses only on the most important types of simulations without discussing others. The underlying logic is the same: dissect the question into different steps and code each step up in Python/R. Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees. leihua-ye.medium.com towardsdatascience.com towardsdatascience.com towardsdatascience.com Please find me on LinkedIn and Youtube. Also, check my other posts on Artificial Intelligence and Machine Learning.
[ { "code": null, "e": 194, "s": 171, "text": "Updated on Jan-10–2021" }, { "code": null, "e": 196, "s": 194, "text": "1" }, { "code": null, "e": 198, "s": 196, "text": "2" }, { "code": null, "e": 200, "s": 198, "text": "3" }, { "code": null, "e": 202, "s": 200, "text": "4" }, { "code": null, "e": 204, "s": 202, "text": "5" }, { "code": null, "e": 206, "s": 204, "text": "6" }, { "code": null, "e": 208, "s": 206, "text": "7" }, { "code": null, "e": 210, "s": 208, "text": "8" }, { "code": null, "e": 212, "s": 210, "text": "9" }, { "code": null, "e": 215, "s": 212, "text": "10" }, { "code": null, "e": 234, "s": 215, "text": "Powered by Play.ht" }, { "code": null, "e": 260, "s": 234, "text": "Create audio with Play.ht" }, { "code": null, "e": 279, "s": 260, "text": "Powered by Play.ht" }, { "code": null, "e": 538, "s": 279, "text": "Statistical Simulation is the most heavily tested topic in Data Science/Engineering Interviews! If we go over DS Interview questions posted at Glassdoor, statistical simulation is the key skill that all big tech companies expect their applicants to excel in." }, { "code": null, "e": 729, "s": 538, "text": "Interview scenarios may either be asked to perform a power analysis of A/B experiments or construct a binomial distribution to simulate user behaviors in a programming language, R or Python." }, { "code": null, "e": 1064, "s": 729, "text": "These are not difficult questions but require a deep understanding of fundamental statistics and fluent programming skills. Without deliberate practice, these questions may likely trip you over. This post presents 4 types of the most often tested statistical distributions in Data Science interviews and live-code solutions in Python." }, { "code": null, "e": 1196, "s": 1064, "text": "In a previous post, I have covered the fundamentals of statistical thinking and R codes. In case you missed it, here is the portal:" }, { "code": null, "e": 1219, "s": 1196, "text": "towardsdatascience.com" }, { "code": null, "e": 1510, "s": 1219, "text": "Disclaimer: I assume my fellow readers understand the statistical basics (e.g., what a binomial distribution is) and some familiarity with the Python programming environment (e.g., how to write a simple for loop). Here is a light refresher on common statistical distributions by Zijing Zhu." }, { "code": null, "e": 1564, "s": 1510, "text": "In R or Python, please answer the following question." }, { "code": null, "e": 1716, "s": 1564, "text": "For a sequence of numbers, (a1,a2,a3,a4,...,an), please write a function that randomly returns each element, ai, with probability ai/∑ai. (Condition 1)" }, { "code": null, "e": 1861, "s": 1716, "text": "For example, for a sequence (1,2,3,4), the function returns element 1 with a probability of 1/10 and 4 with a probability of 4/10. (Condition 2)" }, { "code": null, "e": 1924, "s": 1861, "text": "You can use any library, but no random.choice(). (Condition 3)" }, { "code": null, "e": 1992, "s": 1924, "text": "This is a real interview question that I asked by a travel company." }, { "code": null, "e": 2013, "s": 1992, "text": "Let’s break it down." }, { "code": null, "e": 2141, "s": 2013, "text": "The question asks for a function that returns an element proportional to its weights, ai/∑ai. It can be completed in two steps:" }, { "code": null, "e": 2326, "s": 2141, "text": "# Step 1: Calculate the probability for each element ai with respect to the total sum ∑ai.# Step 2: Simulate the process and return the element (it is more complicated than it sounds)." }, { "code": null, "e": 2371, "s": 2326, "text": "For step 1, we do something like the follow:" }, { "code": null, "e": 2637, "s": 2371, "text": "import numpy as npdef weight_func(sequence):# step 1 prob = [] total_sum = sum(sequence) for i in range(len(sequence)): prob.append(sequence[i]/total_sum) # step 2: the following is pseudo-code return the element according to its probability" }, { "code": null, "e": 2842, "s": 2637, "text": "Here, there is a catch with the question: we can’t use the built-in method, random.choice() (Condition 3). Hypothetically, it would be a much easier question if we are allowed to import the Numpy package." }, { "code": null, "e": 2942, "s": 2842, "text": "Alternatively, we have to develop something to perform the same functionality as the random choice." }, { "code": null, "e": 3284, "s": 2942, "text": "Back then, I was clueless right on the spot. My interviewer kindly offered his first hint: you can use a uniform distribution with a range from 0 to 1 and compare the generated value (named a) to the cumulative probability sum (named cum_prob[i]) at each position i. If cum_prob[i] > a, then return the corresponding value from the sequence." }, { "code": null, "e": 3355, "s": 3284, "text": "The idea sounds great, and let’s check how the Python codes look like." }, { "code": null, "e": 3671, "s": 3355, "text": "People make a common mistake by trying to use a control flow (if-else statements) to filter out scenarios. It is doable for a small sample size but not practical if there are thousands of numbers in the sequence. We are not using 1,000+ “if, elif, else” statements to tell Python what to do with the numbers, right?" }, { "code": null, "e": 3904, "s": 3671, "text": "After looking back at this question months later, the most challenging part is to come up with the idea of using cumulative probability sum to simulate the process. It is more doable now after the detailed step-by-step explanations." }, { "code": null, "e": 4138, "s": 3904, "text": "An online shopping website (e.g., Amazon, Alibaba, etc.) wants to test out two versions of banners that will appear on the website’s top. The engineering team assigns the probability of visiting version A at 0.6 and version B at 0.4." }, { "code": null, "e": 4249, "s": 4138, "text": "After 10,000 visits, there are 6050 visitors being exposed to version A, and 3950 people exposed to version B." }, { "code": null, "e": 4342, "s": 4249, "text": "What is the probability that there are 6050 cases when the randomization process is correct?" }, { "code": null, "e": 4403, "s": 4342, "text": "In other words, the probability for version A is indeed 0.6." }, { "code": null, "e": 4473, "s": 4403, "text": "This is a part of a hypothesis-testing question. Let’s break it down." }, { "code": null, "e": 4638, "s": 4473, "text": "There are two versions, A and B, and the experiment assigns the treatment to 10,000 people. So, it is a perfect setting for the adoption of a binomial distribution." }, { "code": null, "e": 4835, "s": 4638, "text": "However, the probability of receiving version A is slightly higher than version B. The final answer should return the probability of more than 6050 people receiving version A out of 10,000 trials." }, { "code": null, "e": 4953, "s": 4835, "text": "These pieces of information remind us to combine a binomial distribution with a conditional for loop, as shown below." }, { "code": null, "e": 4960, "s": 4953, "text": "0.1498" }, { "code": null, "e": 5313, "s": 4960, "text": "The result is close to 15%, which carries practical value. This is a hypothesis testing question. Since the probability of observing 6,000 or above visitors is 15%, we fail to reject the null hypothesis and conclude there is no statistical difference between 6,000 and 6,050 visitors out of 10,000. In other words, the probability for version A is 0.6." }, { "code": null, "e": 5485, "s": 5313, "text": "We are have learned hypothesis testing and how to reject or fail to reject the null hypothesis, but a question like this makes me think twice about statistical simulation." }, { "code": null, "e": 5693, "s": 5485, "text": "My medium blog has 500 visits per day, and the number of visits follows a Poisson distribution. Out of 1000 times, what is the ratio of more than 510 visits per day? Write a function to simulate the process." }, { "code": null, "e": 5851, "s": 5693, "text": "This is a rather straightforward question. Since the question asks for how many times an event occurs in a specified time, we can follow a Poisson procedure." }, { "code": null, "e": 5937, "s": 5851, "text": "# step 1: create a poisson distribution# step 2: use an if clause to count the number" }, { "code": null, "e": 5943, "s": 5937, "text": "0.318" }, { "code": null, "e": 6002, "s": 5943, "text": "31.8% of the simulation results have more than 510 visits." }, { "code": null, "e": 6085, "s": 6002, "text": "After publishing this post, the number of Medium blog skyrockets to another level." }, { "code": null, "e": 6175, "s": 6085, "text": "Write a function to generate X samples from a normal distribution and plot the histogram." }, { "code": null, "e": 6267, "s": 6175, "text": "This is a question asked by Google. It is a relatively easy coding question with two steps:" }, { "code": null, "e": 6367, "s": 6267, "text": "# step 1: generate a normal distribution# step 2: take X samples and plot the sampling distribution" }, { "code": null, "e": 6381, "s": 6367, "text": "Here it goes." }, { "code": null, "e": 6456, "s": 6381, "text": "We generate a normal distribution with 100 numbers and set X equals to 10." }, { "code": null, "e": 6604, "s": 6456, "text": "array([ 7.27305691, 6.98741057, 14.37357218, 14.17422672, 7.57495374, 10.39904815, 7.27305691, 7.41182935, 10.565957, 12.0081078 ]) # X_samples" }, { "code": null, "e": 6656, "s": 6604, "text": "The complete Python code is available on my Github." }, { "code": null, "e": 6950, "s": 6656, "text": "As a first step, we need to understand the question before moving on to the coding part. One of the biggest mistakes that job candidates make is to jump into the programming part without asking for clarification questions. They have to re-visit the question multiple times after getting stuck." }, { "code": null, "e": 7154, "s": 6950, "text": "This post focuses only on the most important types of simulations without discussing others. The underlying logic is the same: dissect the question into different steps and code each step up in Python/R." }, { "code": null, "e": 7366, "s": 7154, "text": "Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees." }, { "code": null, "e": 7387, "s": 7366, "text": "leihua-ye.medium.com" }, { "code": null, "e": 7410, "s": 7387, "text": "towardsdatascience.com" }, { "code": null, "e": 7433, "s": 7410, "text": "towardsdatascience.com" }, { "code": null, "e": 7456, "s": 7433, "text": "towardsdatascience.com" }, { "code": null, "e": 7496, "s": 7456, "text": "Please find me on LinkedIn and Youtube." } ]
Building an ApiGateway-SQS-Lambda integration using Terraform | by Daniel Da Costa | Towards Data Science
Terraform is an amazing tool for building infrastructures. This tool is used for building, changing, and versioning infrastructure safely and efficiently. Terraform is the infrastructure as code offering from HashiCorp. While using Terraform for building a project that I’m designing using Amazon Web Services (AWS), I came across the need to set up an API Gateway endpoint that takes records, put them into an SQS queue that triggers an Event Source for a Lambda function. In this post, I would like to share with you each step required to build this infrastructure. This post assumes that you are familiar with Terraform code and AWS services. First, let’s go through the input variables used in the project. The variables are stored inside the file varibles.tf. The use of these variables makes it very easy to deploy the services in different environments. Changing the environment variable to prd (a.k.a production), will create all services with the corresponding environment name. Start by creating the SQS resource. Before creating the ApiGateway resource, let’s first define the permissions so that API Gateway has the necessary permissions to SendMessage to SQS queue. I usually create a folder called policies that contains all the policies that I'll be using in the project, I recommend that you do the same, it will keep your code clean and organized. ├── iam.tf├── policies: // all policies created│ ├── api-gateway-permission.json│ └── lambda-permission.json These permissions will give API Gateway the ability to create and write to CloudWatch logs, as well as the ability to put, read, and list data from the SQS queue. With all the permissions needed for the ApiGateway-SQS interaction created, we can start creating our endpoint. Our endpoint will have a path attached to the root:/form_score , with an API Gateway POST method. We’ll also require that a query_string_parameter, called unity, is passed through the HTTP request. A validator is created in order to validate the existence of the query_string_parameter in the request parameters. Now we can define the API Gateway integration that will forward records into the SQS queue. In order to forward the Method, Body, QueryParameters and path Parameters from the endpoint to the SQS message, a request_template was added. For this integration with SQS, the HTTP header of the request has to be with the Content-Type: application/x-www-form-urlencoded . The SQS response should also be mapped for the successful responses. In this project, the SQS response is returned to the apiGateway as it is, but you can also change it in order to return a custom message, for example: 'Message Added to SQS successfully' . Here, we defined a 200 handler for successful requests. Finally, we can add the API Gateway REST Deployment in order to deploy our endpoint. A redeployment trigger was added. This configuration calculates a hash of the API’s Terraform resources to determine changes that should trigger a new deployment. When building a lambda with terraform I like to split the lambda code from the infra code, it makes the code cleaner and more organized. ├── lambda: folder for lambda code│ ├── handler.py│ └── sqs-integration-dev-lambda.zip├── lambda.tf Before building our lambda, we have to create the necessary permissions so that it can read the messages from SQS and write to CloudWatch logs. Then, we can build our lambda. Lastly, we need to add a permission so that SQS can invoke the lambda. We also need to add an event source so that SQS can trigger the lambda when new messages arrives in the queue. With everything set up, we are ready to apply all the changes to our AWS account. When deployed, we’ll have a public endpoint that will write to SQS with a Lambda function that will consume from it. This is a powerful pipeline that can be used in different scenarios. You can check the full code, with extra analysis, in Here!
[ { "code": null, "e": 392, "s": 172, "text": "Terraform is an amazing tool for building infrastructures. This tool is used for building, changing, and versioning infrastructure safely and efficiently. Terraform is the infrastructure as code offering from HashiCorp." }, { "code": null, "e": 646, "s": 392, "text": "While using Terraform for building a project that I’m designing using Amazon Web Services (AWS), I came across the need to set up an API Gateway endpoint that takes records, put them into an SQS queue that triggers an Event Source for a Lambda function." }, { "code": null, "e": 818, "s": 646, "text": "In this post, I would like to share with you each step required to build this infrastructure. This post assumes that you are familiar with Terraform code and AWS services." }, { "code": null, "e": 937, "s": 818, "text": "First, let’s go through the input variables used in the project. The variables are stored inside the file varibles.tf." }, { "code": null, "e": 1160, "s": 937, "text": "The use of these variables makes it very easy to deploy the services in different environments. Changing the environment variable to prd (a.k.a production), will create all services with the corresponding environment name." }, { "code": null, "e": 1196, "s": 1160, "text": "Start by creating the SQS resource." }, { "code": null, "e": 1537, "s": 1196, "text": "Before creating the ApiGateway resource, let’s first define the permissions so that API Gateway has the necessary permissions to SendMessage to SQS queue. I usually create a folder called policies that contains all the policies that I'll be using in the project, I recommend that you do the same, it will keep your code clean and organized." }, { "code": null, "e": 1650, "s": 1537, "text": "├── iam.tf├── policies: // all policies created│ ├── api-gateway-permission.json│ └── lambda-permission.json" }, { "code": null, "e": 1813, "s": 1650, "text": "These permissions will give API Gateway the ability to create and write to CloudWatch logs, as well as the ability to put, read, and list data from the SQS queue." }, { "code": null, "e": 1925, "s": 1813, "text": "With all the permissions needed for the ApiGateway-SQS interaction created, we can start creating our endpoint." }, { "code": null, "e": 2238, "s": 1925, "text": "Our endpoint will have a path attached to the root:/form_score , with an API Gateway POST method. We’ll also require that a query_string_parameter, called unity, is passed through the HTTP request. A validator is created in order to validate the existence of the query_string_parameter in the request parameters." }, { "code": null, "e": 2472, "s": 2238, "text": "Now we can define the API Gateway integration that will forward records into the SQS queue. In order to forward the Method, Body, QueryParameters and path Parameters from the endpoint to the SQS message, a request_template was added." }, { "code": null, "e": 2603, "s": 2472, "text": "For this integration with SQS, the HTTP header of the request has to be with the Content-Type: application/x-www-form-urlencoded ." }, { "code": null, "e": 2917, "s": 2603, "text": "The SQS response should also be mapped for the successful responses. In this project, the SQS response is returned to the apiGateway as it is, but you can also change it in order to return a custom message, for example: 'Message Added to SQS successfully' . Here, we defined a 200 handler for successful requests." }, { "code": null, "e": 3165, "s": 2917, "text": "Finally, we can add the API Gateway REST Deployment in order to deploy our endpoint. A redeployment trigger was added. This configuration calculates a hash of the API’s Terraform resources to determine changes that should trigger a new deployment." }, { "code": null, "e": 3302, "s": 3165, "text": "When building a lambda with terraform I like to split the lambda code from the infra code, it makes the code cleaner and more organized." }, { "code": null, "e": 3406, "s": 3302, "text": "├── lambda: folder for lambda code│ ├── handler.py│ └── sqs-integration-dev-lambda.zip├── lambda.tf" }, { "code": null, "e": 3550, "s": 3406, "text": "Before building our lambda, we have to create the necessary permissions so that it can read the messages from SQS and write to CloudWatch logs." }, { "code": null, "e": 3581, "s": 3550, "text": "Then, we can build our lambda." }, { "code": null, "e": 3763, "s": 3581, "text": "Lastly, we need to add a permission so that SQS can invoke the lambda. We also need to add an event source so that SQS can trigger the lambda when new messages arrives in the queue." }, { "code": null, "e": 3962, "s": 3763, "text": "With everything set up, we are ready to apply all the changes to our AWS account. When deployed, we’ll have a public endpoint that will write to SQS with a Lambda function that will consume from it." } ]
Deep Q-Network (DQN)-II. Experience Replay and Target Networks | by Jordi TORRES.AI | Towards Data Science
This is the second post devoted to Deep Q-Network (DQN), in the “Deep Reinforcement Learning Explained” series, in which we will analyse some challenges that appear when we apply Deep Learning to Reinforcement Learning. We will also present in detail the code that solves the OpenAI Gym Pong game using the DQN network introduced in the previous post. Spanish version of this publication medium.com Unfortunately, reinforcement learning is more unstable when neural networks are used to represent the action-values, despite applying the wrappers introduced in the previous section. Training such a network requires a lot of data, but even then, it is not guaranteed to converge on the optimal value function. In fact, there are situations where the network weights can oscillate or diverge, due to the high correlation between actions and states. In order to solve this, in this section we will introduce two techniques used by the Deep Q-Network: Experience Replay Target Network There are many more tips and tricks that researchers have discovered to make DQN training more stable and efficient, and we will cover the best of them in future posts in this series. We are trying to approximate a complex, nonlinear function, Q(s, a), with a Neural Network. To do this, we must calculate targets using the Bellman equation and then consider that we have a supervised learning problem at hand. However, one of the fundamental requirements for SGD optimization is that the training data is independent and identically distributed and when the Agent interacts with the Environment, the sequence of experience tuples can be highly correlated. The naive Q-learning algorithm that learns from each of these experiences tuples in sequential order runs the risk of getting swayed by the effects of this correlation. We can prevent action values from oscillating or diverging catastrophically using a large buffer of our past experience and sample training data from it, instead of using our latest experience. This technique is called replay buffer or experience buffer. The replay buffer contains a collection of experience tuples (S, A, R, S′). The tuples are gradually added to the buffer as we are interacting with the Environment. The simplest implementation is a buffer of fixed size, with new data added to the end of the buffer so that it pushes the oldest experience out of it. The act of sampling a small batch of tuples from the replay buffer in order to learn is known as experience replay. In addition to breaking harmful correlations, experience replay allows us to learn more from individual tuples multiple times, recall rare occurrences, and in general make better use of our experience. As a summary, the basic idea behind experience replay is to storing past experiences and then using a random subset of these experiences to update the Q-network, rather than using just the single most recent experience. In order to store the Agent’s experiences, we used a data structure called a deque in Python’s built-in collections library. It’s basically a list that you can set a maximum size on so that if you try to append to the list and it is already full, it will remove the first item in the list and add the new item to the end of the list. The experiences themselves are tuples of [observation, action, reward, done flag, next state] to keep the transitions obtained from the environment. Experience = collections.namedtuple(‘Experience’, field_names=[‘state’, ‘action’, ‘reward’, ‘done’, ‘new_state’])class ExperienceReplay: def __init__(self, capacity): self.buffer = collections.deque(maxlen=capacity) def __len__(self): return len(self.buffer) def append(self, experience): self.buffer.append(experience) def sample(self, batch_size): indices = np.random.choice(len(self.buffer), batch_size, replace=False) states, actions, rewards, dones, next_states = zip([self.buffer[idx] for idx in indices]) return np.array(states), np.array(actions), np.array(rewards,dtype=np.float32), np.array(dones, dtype=np.uint8), np.array(next_states) Each time the Agent does a step in the Environment, it pushes the transition into the buffer, keeping only a fixed number of steps (in our case, 10k transitions). For training, we randomly sample the batch of transitions from the replay buffer, which allows us to break the correlation between subsequent steps in the environment. Most of the experience replay buffer code is quite straightforward: it basically exploits the capability of the deque library. In the sample() method, we create a list of random indices and then repack the sampled entries into NumPy arrays for more convenient loss calculation. Remember that in Q-Learning, we update a guess with a guess, and this can potentially lead to harmful correlations. The Bellman equation provides us with the value of Q(s, a) via Q(s’, a’) . However, both the states s and s’ have only one step between them. This makes them very similar, and it’s very hard for a Neural Network to distinguish between them. When we perform an update of our Neural Networks’ parameters to make Q(s, a) closer to the desired result, we can indirectly alter the value produced for Q(s’, a’) and other states nearby. This can make our training very unstable. To make training more stable, there is a trick, called target network, by which we keep a copy of our neural network and use it for the Q(s’, a’) value in the Bellman equation. That is, the predicted Q values of this second Q-network called the target network, are used to backpropagate through and train the main Q-network. It is important to highlight that the target network’s parameters are not trained, but they are periodically synchronized with the parameters of the main Q-network. The idea is that using the target network’s Q values to train the main Q-network will improve the stability of the training. Later, when we present the code of the training loop, we will enter in more detail how to code the initialization and use of this target network. There are two main phases that are interleaved in the Deep Q-Learning Algorithm. One is where we sample the environment by performing actions and store away the observed experienced tuples in a replay memory. The other is where we select the small batch of tuples from this memory, randomly, and learn from that batch using a gradient descent (SGD) update step. These two phases are not directly dependent on each other and we could perform multiple sampling steps then one learning step, or even multiple learning steps with different random batches. In practice, you won’t be able to run the learning step immediately. You will need to wait till you have enough tuples of experiences in D. The rest of the algorithm is designed to support these steps. We can summarize the previous explanations with this pseudocode for the basic DQN algorithm that will guide our implementation of the algorithm: In the beginning, we need to create the main network and the target networks, and initialize an empty replay memory D. Note that memory is finite, so we may want to use something like a circular queue that retains the d most recent experience tuples. We also need to initialize the Agent, one of the main components, which interacts with the Environment. Note that we do not clear out the memory after each episode, this enables us to recall and build batches of experiences from across episodes. Before going into the code, mention that DeepMind’s Nature paper contained a table with all the details about hyperparameters used to train its model on all 49 Atari games used for evaluation. DeepMind kept all those parameters the same for all games, but trained individual models for every game. The team’s intention was to show that the method is robust enough to solve lots of games with varying complexity, action space, reward structure, and other details using one single model architecture and hyperparameters. However, our goal in this post is to solve just the Pong game, a quite simple and straightforward game in comparison to other games in the Atari test set, so the hyperparameters in the paper are are not the most suitable for a didactic post like this one. For this reason, we decided to use more personalized parameter values for our Pong Environment that converges to mean score of 19.0 in a reasonable wall time, depending on the GPU type that colab assigns to our execution (about a couple of hours at most). Remember that we can know the type of GPU that has been assigned to our runtime environment with the command !nvidia-smi. Let’s start introducing the code in more detail. The entire code of this post can be found on GitHub (and can be run as a Colab google notebook using this link). We skip the import details of the packages, it is quite straightforward, and we focus on the explanation of the hyperparameters: DEFAULT_ENV_NAME = “PongNoFrameskip-v4” MEAN_REWARD_BOUND = 19.0 gamma = 0.99 orbatch_size = 32 replay_size = 10000 learning_rate = 1e-4 sync_target_frames = 1000 replay_start_size = 10000 eps_start=1.0eps_decay=.999985eps_min=0.02 These DEFAULT_ENV_NAME identify the Environment to train on and MEAN_REWARD_BOUNDthe reward boundary to stop training. We will consider that the game has converged when our agent reaches an average of 19 games won (out of 21) in the last 100 games. The remaining parameters indicate: gammais the discount factor batch_size, the minibatch size learning_rateis the learning rate replay_sizethe replay buffer size (maximum number of experiences stored in replay memory) sync_target_framesindicates how frequently we sync model weights from the main DQN network to the target DQN network (how many frames in between syncing) replay_start_size the count of frames (experiences) to add to replay buffer before starting training. Finally, the hyperparameters related to the epsilon decay schedule are the same as the previous post: eps_start=1.0eps_decay=.999985eps_min=0.02 One of the main components we need is an Agent, which interacts with the Environment, and saves the result of the interaction into the experience replay buffer. The Agent class that we will design already save directly the result of the interacts with the Environment into the experience replay buffer, performing these three steps of the sample phase indicated in the portion of the previous pseudocode: First of all, during the Agent’s initialization, we need to store references to the Environment and experience replay buffer D indicated as an argument in the creation of the Agent’s object as exp_buffer: class Agent: def __init__(self, env, exp_buffer): self.env = env self.exp_buffer = exp_buffer self._reset()def _reset(self): self.state = env.reset() self.total_reward = 0.0 In order to perform Agent’s steps in the Environment and store its results in the experience replay memory we suggest the following code: def play_step(self, net, epsilon=0.0, device=”cpu”): done_reward = None if np.random.random() < epsilon: action = env.action_space.sample() else: state_a = np.array([self.state], copy=False) state_v = torch.tensor(state_a).to(device) q_vals_v = net(state_v) _, act_v = torch.max(q_vals_v, dim=1) action = int(act_v.item()) The method play_step uses an ε-greedy(Q) policy to select actions at every time step. In other words, with the probability epsilon (passed as an argument), we take the random action; otherwise, we use the past model to obtain the Q-values for all possible actions and choose the best. After obtaining the action the method performs the step in the Environment to get the next observation: next_state, reward and is_done: new_state, reward, is_done, _ = self.env.step(action) self.total_reward += reward Finally, the method stores the observation in the experience replay buffer, and then handle the end-of-episode situation: exp = Experience(self.state,action,reward,is_done,new_state) self.exp_buffer.append(exp) self.state = new_state if is_done: done_reward = self.total_reward self._reset() return done_reward The result of the function is the total accumulated reward if we have reached the end of the episode with this step, or None if not. In the initialization part, we create our environment with all required wrappers applied, the main DQN neural network that we are going to train, and our target network with the same architecture. We also create the experience replay buffer of the required size and pass it to the agent. The last things we do before the training loop are to create an optimizer, a buffer for full episode rewards, a counter of frames and a variable to track the best mean reward reached (because every time the mean reward beats the record, we will save the model in a file): env = make_env(DEFAULT_ENV_NAME)net = DQN(env.observation_space.shape, env.action_space.n).to(device)target_net = DQN(env.observation_space.shape, env.action_space.n).to(device)buffer = ExperienceReplay(replay_size)agent = Agent(env, buffer)epsilon = eps_startoptimizer = optim.Adam(net.parameters(), lr=learning_rate)total_rewards = []frame_idx = 0best_mean_reward = None At the beginning of the training loop, we count the number of iterations completed and update epsilon as we introduced in the previous post. Next, the Agent makes a single step in the Environment (using as arguments the current neural network and value for epsilon). Remember that this function returns a non-None result only if this step is the final step in the episode. In this case, we report the progress in the console (count of episodes played, mean reward for the last 100 episodes and the current value of epsilon): while True: frame_idx += 1 epsilon = max(epsilon*eps_decay, eps_min) reward = agent.play_step(net, epsilon, device=device) if reward is not None: total_rewards.append(reward) mean_reward = np.mean(total_rewards[-100:]) print(“%d: %d games, mean reward %.3f, (epsilon %.2f)” % (frame_idx, len(total_rewards), mean_reward, epsilon)) After, every time our mean reward for the last 100 episodes reaches a maximum, we report this in the console and save the current model parameters in a file. Also, if this mean rewards exceed the specified MEAN_REWARD_BOUND ( 19.0 in our case) then we stop training. The third if, helps us to ensure our experience replay buffer is large enough for training: if best_mean_reward is None or best_mean_reward < mean_reward: torch.save(net.state_dict(), DEFAULT_ENV_NAME + “-best.dat”) best_mean_reward = mean_reward if best_mean_reward is not None: print(“Best mean reward updated %.3f” % (best_mean_reward))if mean_reward > MEAN_REWARD_BOUND: print(“Solved in %d frames!” % frame_idx) breakif len(buffer) < replay_start_size: continue Now we will start to describe the part of the code, from the main loop, that refers to the phase where the network learn (a portion of the previous pseudocode): The whole code that we wrote for implementing this part is as follows: batch = buffer.sample(batch_size) states, actions, rewards, dones, next_states = batchstates_v = torch.tensor(states).to(device)next_states_v = torch.tensor(next_states).to(device)actions_v = torch.tensor(actions).to(device)rewards_v = torch.tensor(rewards).to(device)done_mask = torch.ByteTensor(dones).to(device)state_action_values = net(states_v).gather(1, actions_v.unsqueeze(-1)).squeeze(-1)next_state_values = target_net(next_states_v).max(1)[0]next_state_values[done_mask] = 0.0next_state_values = next_state_values.detach()expected_state_action_values=next_state_values * gamma + rewards_vloss_t = nn.MSELoss()(state_action_values, expected_state_action_values)optimizer.zero_grad()loss_t.backward()optimizer.step()if frame_idx % sync_target_frames == 0: target_net.load_state_dict(net.state_dict()) We are going to dissect it to facilitate its description since it is probably the most complex part to understand. The first thing to do is to sample a random mini-batch of transactions from the replay memory: batch = buffer.sample(batch_size) states, actions, rewards, dones, next_states = batch Next, the code wraps individual NumPy arrays with batch data in PyTorch tensors and copies them to GPU ( we are assuming that the CUDA device is specified in arguments): states_v = torch.tensor(states).to(device)next_states_v = torch.tensor(next_states).to(device)actions_v = torch.tensor(actions).to(device)rewards_v = torch.tensor(rewards).to(device)done_mask = torch.ByteTensor(dones).to(device) This code inspired by the code of Maxim Lapan. It is written in a form to maximally exploit the capabilities of the GPU by processing (in parallel) all batch samples with vector operations. But explained step by step it can be understood without problems. Then, we pass observations to the first model and extract the specific Q-values for the taken actions using the gather() tensor operation. The first argument to this function call is a dimension index that we want to perform gathering on. In this case, it is equal to 1, because it corresponds to actions dimension: state_action_values = net(states_v).gather(1, actions_v.unsqueeze(-1)).squeeze(-1) The second argument is a tensor of indices of elements to be chosen. Here it is a bit more complex to explain the code. Let’s try it!. Maxim Lapan suggest to use the functions unsqueeze() and squeeze(). Because the index should have the same number of dimensions as the data we are processing (2D in our case) it apply a unsqueeze()to the action_v (that is a 1D) to compute the index argument for the gather functions. Finally, to remove the extra dimensions we have created, we will use the squeeze()function. Let’s try to illustrate what a gather does in summary on a simple example case with a batch of four entries and four actions: Note that the result of gather() applied to tensors is a differentiable operation that will keep all gradients with respect to the final loss value. Now that we have calculated the state-action values for every transition in the replay buffer, we need to calculate target “y” for every transition in the replay buffer too. Both vectors are the ones we will use in the loss function. To do this, remember that we must use the target network. In the following code, we apply the target network to our next state observations and calculate the maximum Q-value along the same action dimension, 1: next_state_values = target_net(next_states_v).max(1)[0] Function max() returns both maximum values and indices of those values (so it calculates both max and argmax). Because in this case, we are interested only in values, we take the first entry of the result. Remember that if the transition in the batch is from the last step in the episode, then our value of the action doesn’t have a discounted reward of the next state, as there is no next state from which to gather the reward: next_state_values[done_mask] = 0.0 Although we cannot go into detail, it is important to highlight that the calculation of the next state value by the target neural network shouldn’t affect gradients. To achieve this, we use thedetach() function of the PyTorch tensor, which makes a copy of it without connection to the parent’s operation, to prevent gradients from flowing into the target network’s graph: next_state_values = next_state_values.detach() Now, we can calculate the Bellman approximation value for the vector of targets (“y”), that is the vector of the expected state-action value for every transition in the replay buffer: expected_state_action_values=next_state_values * gamma + rewards_v We have all the information required to calculate the mean squared error loss: loss_t = nn.MSELoss()(state_action_values, expected_state_action_values) The next piece of the training loop updates the main neural network using the SGD algorithm by minimizing the loss: optimizer.zero_grad()loss_t.backward()optimizer.step() Finally, the last line of the code syncs parameters from our main DQN network to the target DQN network every sync_target_frames: if frame_idx % sync_target_frames == 0: target_net.load_state_dict(net.state_dict()) And so far the code for the main loop! This is the second of three posts devoted to present the basics of Deep Q-Network (DQN), in which we present in detail the algorithm. In the next post, we will talk about the performance of the algorithm and also show how we can use it. by UPC Barcelona Tech and Barcelona Supercomputing Center A relaxed introductory series that gradually and with a practical approach introduces the reader to this exciting technology that is the real enabler of the latest disruptive advances in the field of Artificial Intelligence. I started to write this series in May, during the period of lockdown in Barcelona. Honestly, writing these posts in my spare time helped me to #StayAtHome because of the lockdown. Thank you for reading this publication in those days; it justifies the effort I made. Disclaimers — These posts were written during this period of lockdown in Barcelona as a personal distraction and dissemination of scientific knowledge, in case it could be of help to someone, but without the purpose of being an academic reference document in the DRL area. If the reader needs a more rigorous document, the last post in the series offers an extensive list of academic resources and books that the reader can consult. The author is aware that this series of posts may contain some errors and suffers from a revision of the English text to improve it if the purpose were an academic document. But although the author would like to improve the content in quantity and quality, his professional commitments do not leave him free time to do so. However, the author agrees to refine all those errors that readers can report as soon as he can.
[ { "code": null, "e": 524, "s": 172, "text": "This is the second post devoted to Deep Q-Network (DQN), in the “Deep Reinforcement Learning Explained” series, in which we will analyse some challenges that appear when we apply Deep Learning to Reinforcement Learning. We will also present in detail the code that solves the OpenAI Gym Pong game using the DQN network introduced in the previous post." }, { "code": null, "e": 560, "s": 524, "text": "Spanish version of this publication" }, { "code": null, "e": 571, "s": 560, "text": "medium.com" }, { "code": null, "e": 1019, "s": 571, "text": "Unfortunately, reinforcement learning is more unstable when neural networks are used to represent the action-values, despite applying the wrappers introduced in the previous section. Training such a network requires a lot of data, but even then, it is not guaranteed to converge on the optimal value function. In fact, there are situations where the network weights can oscillate or diverge, due to the high correlation between actions and states." }, { "code": null, "e": 1120, "s": 1019, "text": "In order to solve this, in this section we will introduce two techniques used by the Deep Q-Network:" }, { "code": null, "e": 1138, "s": 1120, "text": "Experience Replay" }, { "code": null, "e": 1153, "s": 1138, "text": "Target Network" }, { "code": null, "e": 1337, "s": 1153, "text": "There are many more tips and tricks that researchers have discovered to make DQN training more stable and efficient, and we will cover the best of them in future posts in this series." }, { "code": null, "e": 1979, "s": 1337, "text": "We are trying to approximate a complex, nonlinear function, Q(s, a), with a Neural Network. To do this, we must calculate targets using the Bellman equation and then consider that we have a supervised learning problem at hand. However, one of the fundamental requirements for SGD optimization is that the training data is independent and identically distributed and when the Agent interacts with the Environment, the sequence of experience tuples can be highly correlated. The naive Q-learning algorithm that learns from each of these experiences tuples in sequential order runs the risk of getting swayed by the effects of this correlation." }, { "code": null, "e": 2550, "s": 1979, "text": "We can prevent action values from oscillating or diverging catastrophically using a large buffer of our past experience and sample training data from it, instead of using our latest experience. This technique is called replay buffer or experience buffer. The replay buffer contains a collection of experience tuples (S, A, R, S′). The tuples are gradually added to the buffer as we are interacting with the Environment. The simplest implementation is a buffer of fixed size, with new data added to the end of the buffer so that it pushes the oldest experience out of it." }, { "code": null, "e": 2868, "s": 2550, "text": "The act of sampling a small batch of tuples from the replay buffer in order to learn is known as experience replay. In addition to breaking harmful correlations, experience replay allows us to learn more from individual tuples multiple times, recall rare occurrences, and in general make better use of our experience." }, { "code": null, "e": 3571, "s": 2868, "text": "As a summary, the basic idea behind experience replay is to storing past experiences and then using a random subset of these experiences to update the Q-network, rather than using just the single most recent experience. In order to store the Agent’s experiences, we used a data structure called a deque in Python’s built-in collections library. It’s basically a list that you can set a maximum size on so that if you try to append to the list and it is already full, it will remove the first item in the list and add the new item to the end of the list. The experiences themselves are tuples of [observation, action, reward, done flag, next state] to keep the transitions obtained from the environment." }, { "code": null, "e": 4354, "s": 3571, "text": "Experience = collections.namedtuple(‘Experience’, field_names=[‘state’, ‘action’, ‘reward’, ‘done’, ‘new_state’])class ExperienceReplay: def __init__(self, capacity): self.buffer = collections.deque(maxlen=capacity) def __len__(self): return len(self.buffer) def append(self, experience): self.buffer.append(experience) def sample(self, batch_size): indices = np.random.choice(len(self.buffer), batch_size, replace=False) states, actions, rewards, dones, next_states = zip([self.buffer[idx] for idx in indices]) return np.array(states), np.array(actions), np.array(rewards,dtype=np.float32), np.array(dones, dtype=np.uint8), np.array(next_states)" }, { "code": null, "e": 4685, "s": 4354, "text": "Each time the Agent does a step in the Environment, it pushes the transition into the buffer, keeping only a fixed number of steps (in our case, 10k transitions). For training, we randomly sample the batch of transitions from the replay buffer, which allows us to break the correlation between subsequent steps in the environment." }, { "code": null, "e": 4963, "s": 4685, "text": "Most of the experience replay buffer code is quite straightforward: it basically exploits the capability of the deque library. In the sample() method, we create a list of random indices and then repack the sampled entries into NumPy arrays for more convenient loss calculation." }, { "code": null, "e": 5320, "s": 4963, "text": "Remember that in Q-Learning, we update a guess with a guess, and this can potentially lead to harmful correlations. The Bellman equation provides us with the value of Q(s, a) via Q(s’, a’) . However, both the states s and s’ have only one step between them. This makes them very similar, and it’s very hard for a Neural Network to distinguish between them." }, { "code": null, "e": 5551, "s": 5320, "text": "When we perform an update of our Neural Networks’ parameters to make Q(s, a) closer to the desired result, we can indirectly alter the value produced for Q(s’, a’) and other states nearby. This can make our training very unstable." }, { "code": null, "e": 5728, "s": 5551, "text": "To make training more stable, there is a trick, called target network, by which we keep a copy of our neural network and use it for the Q(s’, a’) value in the Bellman equation." }, { "code": null, "e": 6166, "s": 5728, "text": "That is, the predicted Q values of this second Q-network called the target network, are used to backpropagate through and train the main Q-network. It is important to highlight that the target network’s parameters are not trained, but they are periodically synchronized with the parameters of the main Q-network. The idea is that using the target network’s Q values to train the main Q-network will improve the stability of the training." }, { "code": null, "e": 6312, "s": 6166, "text": "Later, when we present the code of the training loop, we will enter in more detail how to code the initialization and use of this target network." }, { "code": null, "e": 6674, "s": 6312, "text": "There are two main phases that are interleaved in the Deep Q-Learning Algorithm. One is where we sample the environment by performing actions and store away the observed experienced tuples in a replay memory. The other is where we select the small batch of tuples from this memory, randomly, and learn from that batch using a gradient descent (SGD) update step." }, { "code": null, "e": 7004, "s": 6674, "text": "These two phases are not directly dependent on each other and we could perform multiple sampling steps then one learning step, or even multiple learning steps with different random batches. In practice, you won’t be able to run the learning step immediately. You will need to wait till you have enough tuples of experiences in D." }, { "code": null, "e": 7211, "s": 7004, "text": "The rest of the algorithm is designed to support these steps. We can summarize the previous explanations with this pseudocode for the basic DQN algorithm that will guide our implementation of the algorithm:" }, { "code": null, "e": 7566, "s": 7211, "text": "In the beginning, we need to create the main network and the target networks, and initialize an empty replay memory D. Note that memory is finite, so we may want to use something like a circular queue that retains the d most recent experience tuples. We also need to initialize the Agent, one of the main components, which interacts with the Environment." }, { "code": null, "e": 7708, "s": 7566, "text": "Note that we do not clear out the memory after each episode, this enables us to recall and build batches of experiences from across episodes." }, { "code": null, "e": 8227, "s": 7708, "text": "Before going into the code, mention that DeepMind’s Nature paper contained a table with all the details about hyperparameters used to train its model on all 49 Atari games used for evaluation. DeepMind kept all those parameters the same for all games, but trained individual models for every game. The team’s intention was to show that the method is robust enough to solve lots of games with varying complexity, action space, reward structure, and other details using one single model architecture and hyperparameters." }, { "code": null, "e": 8861, "s": 8227, "text": "However, our goal in this post is to solve just the Pong game, a quite simple and straightforward game in comparison to other games in the Atari test set, so the hyperparameters in the paper are are not the most suitable for a didactic post like this one. For this reason, we decided to use more personalized parameter values for our Pong Environment that converges to mean score of 19.0 in a reasonable wall time, depending on the GPU type that colab assigns to our execution (about a couple of hours at most). Remember that we can know the type of GPU that has been assigned to our runtime environment with the command !nvidia-smi." }, { "code": null, "e": 9152, "s": 8861, "text": "Let’s start introducing the code in more detail. The entire code of this post can be found on GitHub (and can be run as a Colab google notebook using this link). We skip the import details of the packages, it is quite straightforward, and we focus on the explanation of the hyperparameters:" }, { "code": null, "e": 9454, "s": 9152, "text": "DEFAULT_ENV_NAME = “PongNoFrameskip-v4” MEAN_REWARD_BOUND = 19.0 gamma = 0.99 orbatch_size = 32 replay_size = 10000 learning_rate = 1e-4 sync_target_frames = 1000 replay_start_size = 10000 eps_start=1.0eps_decay=.999985eps_min=0.02" }, { "code": null, "e": 9738, "s": 9454, "text": "These DEFAULT_ENV_NAME identify the Environment to train on and MEAN_REWARD_BOUNDthe reward boundary to stop training. We will consider that the game has converged when our agent reaches an average of 19 games won (out of 21) in the last 100 games. The remaining parameters indicate:" }, { "code": null, "e": 9766, "s": 9738, "text": "gammais the discount factor" }, { "code": null, "e": 9797, "s": 9766, "text": "batch_size, the minibatch size" }, { "code": null, "e": 9831, "s": 9797, "text": "learning_rateis the learning rate" }, { "code": null, "e": 9921, "s": 9831, "text": "replay_sizethe replay buffer size (maximum number of experiences stored in replay memory)" }, { "code": null, "e": 10075, "s": 9921, "text": "sync_target_framesindicates how frequently we sync model weights from the main DQN network to the target DQN network (how many frames in between syncing)" }, { "code": null, "e": 10177, "s": 10075, "text": "replay_start_size the count of frames (experiences) to add to replay buffer before starting training." }, { "code": null, "e": 10279, "s": 10177, "text": "Finally, the hyperparameters related to the epsilon decay schedule are the same as the previous post:" }, { "code": null, "e": 10322, "s": 10279, "text": "eps_start=1.0eps_decay=.999985eps_min=0.02" }, { "code": null, "e": 10727, "s": 10322, "text": "One of the main components we need is an Agent, which interacts with the Environment, and saves the result of the interaction into the experience replay buffer. The Agent class that we will design already save directly the result of the interacts with the Environment into the experience replay buffer, performing these three steps of the sample phase indicated in the portion of the previous pseudocode:" }, { "code": null, "e": 10932, "s": 10727, "text": "First of all, during the Agent’s initialization, we need to store references to the Environment and experience replay buffer D indicated as an argument in the creation of the Agent’s object as exp_buffer:" }, { "code": null, "e": 11145, "s": 10932, "text": "class Agent: def __init__(self, env, exp_buffer): self.env = env self.exp_buffer = exp_buffer self._reset()def _reset(self): self.state = env.reset() self.total_reward = 0.0" }, { "code": null, "e": 11283, "s": 11145, "text": "In order to perform Agent’s steps in the Environment and store its results in the experience replay memory we suggest the following code:" }, { "code": null, "e": 11651, "s": 11283, "text": "def play_step(self, net, epsilon=0.0, device=”cpu”): done_reward = None if np.random.random() < epsilon: action = env.action_space.sample() else: state_a = np.array([self.state], copy=False) state_v = torch.tensor(state_a).to(device) q_vals_v = net(state_v) _, act_v = torch.max(q_vals_v, dim=1) action = int(act_v.item())" }, { "code": null, "e": 11936, "s": 11651, "text": "The method play_step uses an ε-greedy(Q) policy to select actions at every time step. In other words, with the probability epsilon (passed as an argument), we take the random action; otherwise, we use the past model to obtain the Q-values for all possible actions and choose the best." }, { "code": null, "e": 12072, "s": 11936, "text": "After obtaining the action the method performs the step in the Environment to get the next observation: next_state, reward and is_done:" }, { "code": null, "e": 12161, "s": 12072, "text": " new_state, reward, is_done, _ = self.env.step(action) self.total_reward += reward" }, { "code": null, "e": 12283, "s": 12161, "text": "Finally, the method stores the observation in the experience replay buffer, and then handle the end-of-episode situation:" }, { "code": null, "e": 12500, "s": 12283, "text": " exp = Experience(self.state,action,reward,is_done,new_state) self.exp_buffer.append(exp) self.state = new_state if is_done: done_reward = self.total_reward self._reset() return done_reward" }, { "code": null, "e": 12633, "s": 12500, "text": "The result of the function is the total accumulated reward if we have reached the end of the episode with this step, or None if not." }, { "code": null, "e": 13193, "s": 12633, "text": "In the initialization part, we create our environment with all required wrappers applied, the main DQN neural network that we are going to train, and our target network with the same architecture. We also create the experience replay buffer of the required size and pass it to the agent. The last things we do before the training loop are to create an optimizer, a buffer for full episode rewards, a counter of frames and a variable to track the best mean reward reached (because every time the mean reward beats the record, we will save the model in a file):" }, { "code": null, "e": 13584, "s": 13193, "text": "env = make_env(DEFAULT_ENV_NAME)net = DQN(env.observation_space.shape, env.action_space.n).to(device)target_net = DQN(env.observation_space.shape, env.action_space.n).to(device)buffer = ExperienceReplay(replay_size)agent = Agent(env, buffer)epsilon = eps_startoptimizer = optim.Adam(net.parameters(), lr=learning_rate)total_rewards = []frame_idx = 0best_mean_reward = None" }, { "code": null, "e": 14109, "s": 13584, "text": "At the beginning of the training loop, we count the number of iterations completed and update epsilon as we introduced in the previous post. Next, the Agent makes a single step in the Environment (using as arguments the current neural network and value for epsilon). Remember that this function returns a non-None result only if this step is the final step in the episode. In this case, we report the progress in the console (count of episodes played, mean reward for the last 100 episodes and the current value of epsilon):" }, { "code": null, "e": 14466, "s": 14109, "text": "while True: frame_idx += 1 epsilon = max(epsilon*eps_decay, eps_min) reward = agent.play_step(net, epsilon, device=device) if reward is not None: total_rewards.append(reward) mean_reward = np.mean(total_rewards[-100:]) print(“%d: %d games, mean reward %.3f, (epsilon %.2f)” % (frame_idx, len(total_rewards), mean_reward, epsilon))" }, { "code": null, "e": 14825, "s": 14466, "text": "After, every time our mean reward for the last 100 episodes reaches a maximum, we report this in the console and save the current model parameters in a file. Also, if this mean rewards exceed the specified MEAN_REWARD_BOUND ( 19.0 in our case) then we stop training. The third if, helps us to ensure our experience replay buffer is large enough for training:" }, { "code": null, "e": 15333, "s": 14825, "text": "if best_mean_reward is None or best_mean_reward < mean_reward: torch.save(net.state_dict(), DEFAULT_ENV_NAME + “-best.dat”) best_mean_reward = mean_reward if best_mean_reward is not None: print(“Best mean reward updated %.3f” % (best_mean_reward))if mean_reward > MEAN_REWARD_BOUND: print(“Solved in %d frames!” % frame_idx) breakif len(buffer) < replay_start_size: continue" }, { "code": null, "e": 15494, "s": 15333, "text": "Now we will start to describe the part of the code, from the main loop, that refers to the phase where the network learn (a portion of the previous pseudocode):" }, { "code": null, "e": 15565, "s": 15494, "text": "The whole code that we wrote for implementing this part is as follows:" }, { "code": null, "e": 16422, "s": 15565, "text": "batch = buffer.sample(batch_size) states, actions, rewards, dones, next_states = batchstates_v = torch.tensor(states).to(device)next_states_v = torch.tensor(next_states).to(device)actions_v = torch.tensor(actions).to(device)rewards_v = torch.tensor(rewards).to(device)done_mask = torch.ByteTensor(dones).to(device)state_action_values = net(states_v).gather(1, actions_v.unsqueeze(-1)).squeeze(-1)next_state_values = target_net(next_states_v).max(1)[0]next_state_values[done_mask] = 0.0next_state_values = next_state_values.detach()expected_state_action_values=next_state_values * gamma + rewards_vloss_t = nn.MSELoss()(state_action_values, expected_state_action_values)optimizer.zero_grad()loss_t.backward()optimizer.step()if frame_idx % sync_target_frames == 0: target_net.load_state_dict(net.state_dict())" }, { "code": null, "e": 16537, "s": 16422, "text": "We are going to dissect it to facilitate its description since it is probably the most complex part to understand." }, { "code": null, "e": 16632, "s": 16537, "text": "The first thing to do is to sample a random mini-batch of transactions from the replay memory:" }, { "code": null, "e": 16719, "s": 16632, "text": "batch = buffer.sample(batch_size) states, actions, rewards, dones, next_states = batch" }, { "code": null, "e": 16889, "s": 16719, "text": "Next, the code wraps individual NumPy arrays with batch data in PyTorch tensors and copies them to GPU ( we are assuming that the CUDA device is specified in arguments):" }, { "code": null, "e": 17118, "s": 16889, "text": "states_v = torch.tensor(states).to(device)next_states_v = torch.tensor(next_states).to(device)actions_v = torch.tensor(actions).to(device)rewards_v = torch.tensor(rewards).to(device)done_mask = torch.ByteTensor(dones).to(device)" }, { "code": null, "e": 17374, "s": 17118, "text": "This code inspired by the code of Maxim Lapan. It is written in a form to maximally exploit the capabilities of the GPU by processing (in parallel) all batch samples with vector operations. But explained step by step it can be understood without problems." }, { "code": null, "e": 17690, "s": 17374, "text": "Then, we pass observations to the first model and extract the specific Q-values for the taken actions using the gather() tensor operation. The first argument to this function call is a dimension index that we want to perform gathering on. In this case, it is equal to 1, because it corresponds to actions dimension:" }, { "code": null, "e": 17799, "s": 17690, "text": "state_action_values = net(states_v).gather(1, actions_v.unsqueeze(-1)).squeeze(-1)" }, { "code": null, "e": 18436, "s": 17799, "text": "The second argument is a tensor of indices of elements to be chosen. Here it is a bit more complex to explain the code. Let’s try it!. Maxim Lapan suggest to use the functions unsqueeze() and squeeze(). Because the index should have the same number of dimensions as the data we are processing (2D in our case) it apply a unsqueeze()to the action_v (that is a 1D) to compute the index argument for the gather functions. Finally, to remove the extra dimensions we have created, we will use the squeeze()function. Let’s try to illustrate what a gather does in summary on a simple example case with a batch of four entries and four actions:" }, { "code": null, "e": 18585, "s": 18436, "text": "Note that the result of gather() applied to tensors is a differentiable operation that will keep all gradients with respect to the final loss value." }, { "code": null, "e": 18877, "s": 18585, "text": "Now that we have calculated the state-action values for every transition in the replay buffer, we need to calculate target “y” for every transition in the replay buffer too. Both vectors are the ones we will use in the loss function. To do this, remember that we must use the target network." }, { "code": null, "e": 19029, "s": 18877, "text": "In the following code, we apply the target network to our next state observations and calculate the maximum Q-value along the same action dimension, 1:" }, { "code": null, "e": 19085, "s": 19029, "text": "next_state_values = target_net(next_states_v).max(1)[0]" }, { "code": null, "e": 19291, "s": 19085, "text": "Function max() returns both maximum values and indices of those values (so it calculates both max and argmax). Because in this case, we are interested only in values, we take the first entry of the result." }, { "code": null, "e": 19514, "s": 19291, "text": "Remember that if the transition in the batch is from the last step in the episode, then our value of the action doesn’t have a discounted reward of the next state, as there is no next state from which to gather the reward:" }, { "code": null, "e": 19549, "s": 19514, "text": "next_state_values[done_mask] = 0.0" }, { "code": null, "e": 19921, "s": 19549, "text": "Although we cannot go into detail, it is important to highlight that the calculation of the next state value by the target neural network shouldn’t affect gradients. To achieve this, we use thedetach() function of the PyTorch tensor, which makes a copy of it without connection to the parent’s operation, to prevent gradients from flowing into the target network’s graph:" }, { "code": null, "e": 19968, "s": 19921, "text": "next_state_values = next_state_values.detach()" }, { "code": null, "e": 20152, "s": 19968, "text": "Now, we can calculate the Bellman approximation value for the vector of targets (“y”), that is the vector of the expected state-action value for every transition in the replay buffer:" }, { "code": null, "e": 20219, "s": 20152, "text": "expected_state_action_values=next_state_values * gamma + rewards_v" }, { "code": null, "e": 20298, "s": 20219, "text": "We have all the information required to calculate the mean squared error loss:" }, { "code": null, "e": 20392, "s": 20298, "text": "loss_t = nn.MSELoss()(state_action_values, expected_state_action_values)" }, { "code": null, "e": 20508, "s": 20392, "text": "The next piece of the training loop updates the main neural network using the SGD algorithm by minimizing the loss:" }, { "code": null, "e": 20563, "s": 20508, "text": "optimizer.zero_grad()loss_t.backward()optimizer.step()" }, { "code": null, "e": 20693, "s": 20563, "text": "Finally, the last line of the code syncs parameters from our main DQN network to the target DQN network every sync_target_frames:" }, { "code": null, "e": 20780, "s": 20693, "text": "if frame_idx % sync_target_frames == 0: target_net.load_state_dict(net.state_dict())" }, { "code": null, "e": 20819, "s": 20780, "text": "And so far the code for the main loop!" }, { "code": null, "e": 21056, "s": 20819, "text": "This is the second of three posts devoted to present the basics of Deep Q-Network (DQN), in which we present in detail the algorithm. In the next post, we will talk about the performance of the algorithm and also show how we can use it." }, { "code": null, "e": 21114, "s": 21056, "text": "by UPC Barcelona Tech and Barcelona Supercomputing Center" }, { "code": null, "e": 21339, "s": 21114, "text": "A relaxed introductory series that gradually and with a practical approach introduces the reader to this exciting technology that is the real enabler of the latest disruptive advances in the field of Artificial Intelligence." }, { "code": null, "e": 21605, "s": 21339, "text": "I started to write this series in May, during the period of lockdown in Barcelona. Honestly, writing these posts in my spare time helped me to #StayAtHome because of the lockdown. Thank you for reading this publication in those days; it justifies the effort I made." } ]
How to Run Your First Spring Boot Application in IntelliJ IDEA? - GeeksforGeeks
07 Dec, 2021 IntelliJ IDEA is an integrated development environment(IDE) written in Java. It is used for developing computer software. This IDE is developed by Jetbrains and is available as an Apache 2 Licensed community edition and a commercial edition. It is an intelligent, context-aware IDE for working with Java and other JVM languages like Kotlin, Scala, and Groovy on all sorts of applications. Additionally, IntelliJ IDEA Ultimate can help you develop full-stack web applications, thanks to its powerful integrated tools, support for JavaScript and related technologies, and advanced support for popular frameworks like Spring, Spring Boot, Jakarta EE, Micronaut, Quarkus, Helidon. So in this article, we are going to discuss how to run your first spring boot application in IntelliJ IDEA. Prerequisite: Download and Install IntelliJ IDEA in your system. Please refer to this article Step by Step guide to install Intellij Idea to Install IntelliJ IDEA in Your System. Create and Setup Spring Boot Project in IntelliJ IDEACreate or import the Spring Boot projectRun the Spring Boot ApplicationRe-run the application again Create and Setup Spring Boot Project in IntelliJ IDEA Create or import the Spring Boot project Run the Spring Boot Application Re-run the application again Step 1: Create and Setup Spring Boot Project in IntelliJ IDEA You may refer to this article How to Create and Setup Spring Boot Project in IntelliJ IDEA and create your first Spring Boot Application in IntelliJ IDEA. Step 2: Create or import the Spring Boot project After successfully creating or importing the spring boot project a file name Application.java (Herre DemoApplication) will be created automatically and this is your entry point. You can consider it as the main method of a Spring Boot application. Step 3: Run the Spring Boot Application There do exist two methods to run the Spring boot Application which are later discussed as follows: Using Project explorer Directly running demo application file by right-clicking 3.1: Method 1 To run this application now Right-click on the Application.java > Run “DemoApplication.main()” as shown in the below image. or you may type the shortcut key combination (Ctrl + Shift + F10) to run the application. 3.2: Method 2 It is more likely a direct method where we are directly clicking on the green color triangle button and lately choosing Run ‘DemoApplication.main()’. After successfully running the application you can see the console as shown in the below image. Your Tomcat server started on port 8080, as shown in the below image. Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file by using this following line of code. server.port=8989 Step 4: Now re-run the application again and you can see Tomcat server started on the port that you have given like the below image. You can access the output screen in the following URL: http://localhost:8989/. Note that at last provide your port number. sweetyty Java-Spring-Boot Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Exceptions in Java Constructors in Java Different ways of Reading a text file in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples Introduction to Java PriorityQueue in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 25788, "s": 25760, "text": "\n07 Dec, 2021" }, { "code": null, "e": 26575, "s": 25788, "text": "IntelliJ IDEA is an integrated development environment(IDE) written in Java. It is used for developing computer software. This IDE is developed by Jetbrains and is available as an Apache 2 Licensed community edition and a commercial edition. It is an intelligent, context-aware IDE for working with Java and other JVM languages like Kotlin, Scala, and Groovy on all sorts of applications. Additionally, IntelliJ IDEA Ultimate can help you develop full-stack web applications, thanks to its powerful integrated tools, support for JavaScript and related technologies, and advanced support for popular frameworks like Spring, Spring Boot, Jakarta EE, Micronaut, Quarkus, Helidon. So in this article, we are going to discuss how to run your first spring boot application in IntelliJ IDEA. " }, { "code": null, "e": 26754, "s": 26575, "text": "Prerequisite: Download and Install IntelliJ IDEA in your system. Please refer to this article Step by Step guide to install Intellij Idea to Install IntelliJ IDEA in Your System." }, { "code": null, "e": 26907, "s": 26754, "text": "Create and Setup Spring Boot Project in IntelliJ IDEACreate or import the Spring Boot projectRun the Spring Boot ApplicationRe-run the application again" }, { "code": null, "e": 26961, "s": 26907, "text": "Create and Setup Spring Boot Project in IntelliJ IDEA" }, { "code": null, "e": 27002, "s": 26961, "text": "Create or import the Spring Boot project" }, { "code": null, "e": 27034, "s": 27002, "text": "Run the Spring Boot Application" }, { "code": null, "e": 27063, "s": 27034, "text": "Re-run the application again" }, { "code": null, "e": 27125, "s": 27063, "text": "Step 1: Create and Setup Spring Boot Project in IntelliJ IDEA" }, { "code": null, "e": 27280, "s": 27125, "text": "You may refer to this article How to Create and Setup Spring Boot Project in IntelliJ IDEA and create your first Spring Boot Application in IntelliJ IDEA." }, { "code": null, "e": 27329, "s": 27280, "text": "Step 2: Create or import the Spring Boot project" }, { "code": null, "e": 27577, "s": 27329, "text": "After successfully creating or importing the spring boot project a file name Application.java (Herre DemoApplication) will be created automatically and this is your entry point. You can consider it as the main method of a Spring Boot application. " }, { "code": null, "e": 27617, "s": 27577, "text": "Step 3: Run the Spring Boot Application" }, { "code": null, "e": 27717, "s": 27617, "text": "There do exist two methods to run the Spring boot Application which are later discussed as follows:" }, { "code": null, "e": 27740, "s": 27717, "text": "Using Project explorer" }, { "code": null, "e": 27801, "s": 27740, "text": "Directly running demo application file by right-clicking " }, { "code": null, "e": 27816, "s": 27801, "text": "3.1: Method 1 " }, { "code": null, "e": 28031, "s": 27816, "text": "To run this application now Right-click on the Application.java > Run “DemoApplication.main()” as shown in the below image. or you may type the shortcut key combination (Ctrl + Shift + F10) to run the application. " }, { "code": null, "e": 28045, "s": 28031, "text": "3.2: Method 2" }, { "code": null, "e": 28196, "s": 28045, "text": "It is more likely a direct method where we are directly clicking on the green color triangle button and lately choosing Run ‘DemoApplication.main()’. " }, { "code": null, "e": 28362, "s": 28196, "text": "After successfully running the application you can see the console as shown in the below image. Your Tomcat server started on port 8080, as shown in the below image." }, { "code": null, "e": 28507, "s": 28362, "text": "Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file by using this following line of code. " }, { "code": null, "e": 28524, "s": 28507, "text": "server.port=8989" }, { "code": null, "e": 28657, "s": 28524, "text": "Step 4: Now re-run the application again and you can see Tomcat server started on the port that you have given like the below image." }, { "code": null, "e": 28781, "s": 28657, "text": "You can access the output screen in the following URL: http://localhost:8989/. Note that at last provide your port number. " }, { "code": null, "e": 28790, "s": 28781, "text": "sweetyty" }, { "code": null, "e": 28807, "s": 28790, "text": "Java-Spring-Boot" }, { "code": null, "e": 28812, "s": 28807, "text": "Java" }, { "code": null, "e": 28817, "s": 28812, "text": "Java" }, { "code": null, "e": 28915, "s": 28817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28930, "s": 28915, "text": "Stream In Java" }, { "code": null, "e": 28949, "s": 28930, "text": "Exceptions in Java" }, { "code": null, "e": 28970, "s": 28949, "text": "Constructors in Java" }, { "code": null, "e": 29016, "s": 28970, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29046, "s": 29016, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29063, "s": 29046, "text": "Generics in Java" }, { "code": null, "e": 29106, "s": 29063, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 29127, "s": 29106, "text": "Introduction to Java" }, { "code": null, "e": 29149, "s": 29127, "text": "PriorityQueue in Java" } ]
Dynamic _Cast in C++ - GeeksforGeeks
13 May, 2021 C++ is a powerful language. In C++ we can write a structured program and object-oriented program also. In this article, we will focus on dynamic_cast in C++. Now before start dynamic_cast in C++, first understand what is type casting in C++.’ Casting is a technique by which one data type to another data type. The operator used for this purpose is known as the cast operator. It is a unary operator which forces one data type to be converted into another data type. It takes on the format: Syntax: (Cast type) expression; orCast type (expression) Program 1: C++ // C++ program to demonstrate the use// of typecasting#include <iostream>using namespace std; // Driver Codeint main(){ // Variable declaration int a, b; float c; a = 20; b = 40; // Typecasting c = (float)a * b; cout << "Result: " << c; return 0;} Result: 800 Explanation: In the above example first, the variable a is converted to float then multiplied by b, now the result is also floating float then the result is assigned to the variable c. Now, the value of c is 800. Program 2: C++ // C++ program to read the values of two// variables and stored the result in// third one#include <iostream>using namespace std; int main(){ // Variable declaration and // initialization int a = 7, b = 2; float c; c = a / b; cout << "Result:" << c; return 0;} Result:3 Explanation: In the above case, the variable c is 3, not 3.5, because variables a and b both are integer types therefore a/b is also an integer type. After calculating a/b that is int type is assigned to the variable c which is float type. But a/b is int type i.e., 7/2 is 3, not 3.5. Therefore, the value of variable c is 3. Program 3: C++ // C++ program to read two variable value// (a, b) and perform typecasting#include <iostream>using namespace std; // Driver Codeint main(){ // Variable declaration and // initialization int a = 7, b = 2; float c; // Type Casting c = (float)a / b; cout << "Result :" << c; return 0;} Result :3.5 Explanation: Now, the variable c is 3.5, because in the above expression first a is converted into float therefore a/b is also float type. 7.0/2 is 3.5. Then that is assigned to the variable c. C++ supports four types of casting: 1.Static Cast2. Dynamic Cast3. Const Cast4. Reinterpret Cast Static Cast: This is the simplest type of cast that can be used. It is a compile-time cast. It does things like implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions (or implicit ones). Dynamic Cast: A cast is an operator that converts data from one type to another type. In C++, dynamic casting is mainly used for safe downcasting at run time. To work on dynamic_cast there must be one virtual function in the base class. A dynamic_cast works only polymorphic base class because it uses this information to decide safe downcasting. Syntax: dynamic_cast <new_type>(Expression) Downcasting: Casting a base class pointer (or reference) to a derived class pointer (or reference) is known as downcasting. In figure 1 casting from the Base class pointer/reference to the “derived class 1” pointer/reference showing downcasting (Base ->Derived class). Upcasting: Casting a derived class pointer (or reference) to a base class pointer (or reference) is known as upcasting. In figure 1 Casting from Derived class 2 pointer/reference to the “Base class” pointer/reference showing Upcasting (Derived class 2 -> Base Class). As we mention above for dynamic casting there must be one Virtual function. Suppose If we do not use the virtual function, then what is the result? In that case, it generates an error message “Source type is not polymorphic”. C++ // C++ program demonstrate if there// is no virtual function used in// the Base class#include <iostream>using namespace std; // Base class declarationclass Base { void print() { cout << "Base" << endl; }}; // Derived Class 1 declarationclass Derived1 : public Base { void print() { cout << "Derived1" << endl; }}; // Derived class 2 declarationclass Derived2 : public Base { void print() { cout << "Derived2" << endl; }}; // Driver Codeint main(){ Derived1 d1; // Base class pointer hold Derived1 // class object Base* bp = dynamic_cast<Base*>(&d1); // Dynamic casting Derived2* dp2 = dynamic_cast<Derived2*>(bp); if (dp2 == nullptr) cout << "null" << endl; return 0;} not null Virtual functions include run-time type information and there is no virtual function in the base class. So this code generates an error. Case 1: Let’s take an example of dynamic_cast which demonstrates if the casting is successful, it returns a value of type new_type. C++ // C++ Program demonstrates successful// dynamic casting and it returns a// value of type new_type#include <iostream> using namespace std;// Base Class declarationclass Base { virtual void print() { cout << "Base" << endl; }}; // Derived1 class declarationclass Derived1 : public Base { void print() { cout << "Derived1" << endl; }}; // Derived2 class declarationclass Derived2 : public Base { void print() { cout << "Derived2" << endl; }}; // Driver Codeint main(){ Derived1 d1; // Base class pointer holding // Derived1 Class object Base* bp = dynamic_cast<Base*>(&d1); // Dynamic_casting Derived1* dp2 = dynamic_cast<Derived1*>(bp); if (dp2 == nullptr) cout << "null" << endl; else cout << "not null" << endl; return 0;} not null Explanation: In this program, there is one base class and two derived classes (Derived1, Derived2), here the base class pointer hold derived class 1 object (d1). At the time of dynamic_casting base class, the pointer held the Derived1 object and assigning it to derived class 1, assigned valid dynamic_casting. Case 2: Now, If the cast fails and new_type is a pointer type, it returns a null pointer of that type. C++ // C++ Program demonstrate if the cast// fails and new_type is a pointer type// it returns a null pointer of that type#include <iostream>using namespace std; // Base class declarationclass Base { virtual void print() { cout << "Base" << endl; }}; // Derived1 class declarationclass Derived1 : public Base { void print() { cout << "Derived1" << endl; }}; // Derived2 class declarationclass Derived2 : public Base { void print() { cout << "Derived2" << endl; }}; // Driver Codeint main(){ Derived1 d1; Base* bp = dynamic_cast<Base*>(&d1); // Dynamic Casting Derived2* dp2 = dynamic_cast<Derived2*>(bp); if (dp2 == nullptr) cout << "null" << endl; return 0;} null Explanation: In this program, at the time of dynamic_casting base class pointer holding the Derived1 object and assigning it to derived class 2, which is not valid dynamic_casting. So, it returns a null pointer of that type in the result. Case 3:Now take one more case of dynamic_cast, If the cast fails and new_type is a reference type, it throws an exception that matches a handler of type std::bad_cast and gives a warning: dynamic_cast of “Derived d1” to “class Derived2&” can never succeed. C++ // C++ Program demonstrate if the cast// fails and new_type is a reference// type it throws an exception#include <exception>#include <iostream>using namespace std; // Base class declarationclass Base { virtual void print() { cout << "Base" << endl; }}; // Derived1 classclass Derived1 : public Base { void print() { cout << "Derived1" << endl; }}; // Derived2 classclass Derived2 : public Base { void print() { cout << "Derived2" << endl; }}; // Driver Codeint main(){ Derived1 d1; Base* bp = dynamic_cast<Base*>(&d1); // Type casting Derived1* dp2 = dynamic_cast<Derived1*>(bp); if (dp2 == nullptr) cout << "null" << endl; else cout << "not null" << endl; // Exception handling block try { Derived2& r1 = dynamic_cast<Derived2&>(d1); } catch (std::exception& e) { cout << e.what() << endl; } return 0;} Output: warning: dynamic_cast of ‘Derived1 d1’ to ‘class Derived2&’ can never succeed Derived2& r1 = dynamic_cast<Derived2&>(d1); Note: A Dynamic_cast has runtime overhead because it checks object types at run time using “Run-Time Type Information“. If there is a surety we will never cast to wrong object then always avoid dynamic_cast and use static_cast. CPP-Basics Data Type C++ C++ Programs Data Type CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Iterators in C++ STL Friend class and function in C++ Polymorphism in C++ Sorting a vector in C++ Header files in C/C++ and its uses C++ Program for QuickSort How to return multiple values from a function in C or C++? CSV file management using C++ Program to print ASCII Value of a character
[ { "code": null, "e": 24042, "s": 24014, "text": "\n13 May, 2021" }, { "code": null, "e": 24285, "s": 24042, "text": "C++ is a powerful language. In C++ we can write a structured program and object-oriented program also. In this article, we will focus on dynamic_cast in C++. Now before start dynamic_cast in C++, first understand what is type casting in C++.’" }, { "code": null, "e": 24533, "s": 24285, "text": "Casting is a technique by which one data type to another data type. The operator used for this purpose is known as the cast operator. It is a unary operator which forces one data type to be converted into another data type. It takes on the format:" }, { "code": null, "e": 24541, "s": 24533, "text": "Syntax:" }, { "code": null, "e": 24603, "s": 24541, "text": "(Cast type) expression; orCast type (expression)" }, { "code": null, "e": 24614, "s": 24603, "text": "Program 1:" }, { "code": null, "e": 24618, "s": 24614, "text": "C++" }, { "code": "// C++ program to demonstrate the use// of typecasting#include <iostream>using namespace std; // Driver Codeint main(){ // Variable declaration int a, b; float c; a = 20; b = 40; // Typecasting c = (float)a * b; cout << \"Result: \" << c; return 0;}", "e": 24902, "s": 24618, "text": null }, { "code": null, "e": 24915, "s": 24902, "text": "Result: 800\n" }, { "code": null, "e": 25129, "s": 24915, "text": "Explanation: In the above example first, the variable a is converted to float then multiplied by b, now the result is also floating float then the result is assigned to the variable c. Now, the value of c is 800. " }, { "code": null, "e": 25140, "s": 25129, "text": "Program 2:" }, { "code": null, "e": 25144, "s": 25140, "text": "C++" }, { "code": "// C++ program to read the values of two// variables and stored the result in// third one#include <iostream>using namespace std; int main(){ // Variable declaration and // initialization int a = 7, b = 2; float c; c = a / b; cout << \"Result:\" << c; return 0;}", "e": 25430, "s": 25144, "text": null }, { "code": null, "e": 25440, "s": 25430, "text": "Result:3\n" }, { "code": null, "e": 25766, "s": 25440, "text": "Explanation: In the above case, the variable c is 3, not 3.5, because variables a and b both are integer types therefore a/b is also an integer type. After calculating a/b that is int type is assigned to the variable c which is float type. But a/b is int type i.e., 7/2 is 3, not 3.5. Therefore, the value of variable c is 3." }, { "code": null, "e": 25777, "s": 25766, "text": "Program 3:" }, { "code": null, "e": 25781, "s": 25777, "text": "C++" }, { "code": "// C++ program to read two variable value// (a, b) and perform typecasting#include <iostream>using namespace std; // Driver Codeint main(){ // Variable declaration and // initialization int a = 7, b = 2; float c; // Type Casting c = (float)a / b; cout << \"Result :\" << c; return 0;}", "e": 26093, "s": 25781, "text": null }, { "code": null, "e": 26106, "s": 26093, "text": "Result :3.5\n" }, { "code": null, "e": 26300, "s": 26106, "text": "Explanation: Now, the variable c is 3.5, because in the above expression first a is converted into float therefore a/b is also float type. 7.0/2 is 3.5. Then that is assigned to the variable c." }, { "code": null, "e": 26336, "s": 26300, "text": "C++ supports four types of casting:" }, { "code": null, "e": 26397, "s": 26336, "text": "1.Static Cast2. Dynamic Cast3. Const Cast4. Reinterpret Cast" }, { "code": null, "e": 26660, "s": 26397, "text": "Static Cast: This is the simplest type of cast that can be used. It is a compile-time cast. It does things like implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions (or implicit ones)." }, { "code": null, "e": 27007, "s": 26660, "text": "Dynamic Cast: A cast is an operator that converts data from one type to another type. In C++, dynamic casting is mainly used for safe downcasting at run time. To work on dynamic_cast there must be one virtual function in the base class. A dynamic_cast works only polymorphic base class because it uses this information to decide safe downcasting." }, { "code": null, "e": 27015, "s": 27007, "text": "Syntax:" }, { "code": null, "e": 27051, "s": 27015, "text": "dynamic_cast <new_type>(Expression)" }, { "code": null, "e": 27321, "s": 27051, "text": "Downcasting: Casting a base class pointer (or reference) to a derived class pointer (or reference) is known as downcasting. In figure 1 casting from the Base class pointer/reference to the “derived class 1” pointer/reference showing downcasting (Base ->Derived class)." }, { "code": null, "e": 27589, "s": 27321, "text": "Upcasting: Casting a derived class pointer (or reference) to a base class pointer (or reference) is known as upcasting. In figure 1 Casting from Derived class 2 pointer/reference to the “Base class” pointer/reference showing Upcasting (Derived class 2 -> Base Class)." }, { "code": null, "e": 27737, "s": 27589, "text": "As we mention above for dynamic casting there must be one Virtual function. Suppose If we do not use the virtual function, then what is the result?" }, { "code": null, "e": 27815, "s": 27737, "text": "In that case, it generates an error message “Source type is not polymorphic”." }, { "code": null, "e": 27819, "s": 27815, "text": "C++" }, { "code": "// C++ program demonstrate if there// is no virtual function used in// the Base class#include <iostream>using namespace std; // Base class declarationclass Base { void print() { cout << \"Base\" << endl; }}; // Derived Class 1 declarationclass Derived1 : public Base { void print() { cout << \"Derived1\" << endl; }}; // Derived class 2 declarationclass Derived2 : public Base { void print() { cout << \"Derived2\" << endl; }}; // Driver Codeint main(){ Derived1 d1; // Base class pointer hold Derived1 // class object Base* bp = dynamic_cast<Base*>(&d1); // Dynamic casting Derived2* dp2 = dynamic_cast<Derived2*>(bp); if (dp2 == nullptr) cout << \"null\" << endl; return 0;}", "e": 28577, "s": 27819, "text": null }, { "code": null, "e": 28587, "s": 28577, "text": "not null\n" }, { "code": null, "e": 28724, "s": 28587, "text": "Virtual functions include run-time type information and there is no virtual function in the base class. So this code generates an error." }, { "code": null, "e": 28856, "s": 28724, "text": "Case 1: Let’s take an example of dynamic_cast which demonstrates if the casting is successful, it returns a value of type new_type." }, { "code": null, "e": 28860, "s": 28856, "text": "C++" }, { "code": "// C++ Program demonstrates successful// dynamic casting and it returns a// value of type new_type#include <iostream> using namespace std;// Base Class declarationclass Base { virtual void print() { cout << \"Base\" << endl; }}; // Derived1 class declarationclass Derived1 : public Base { void print() { cout << \"Derived1\" << endl; }}; // Derived2 class declarationclass Derived2 : public Base { void print() { cout << \"Derived2\" << endl; }}; // Driver Codeint main(){ Derived1 d1; // Base class pointer holding // Derived1 Class object Base* bp = dynamic_cast<Base*>(&d1); // Dynamic_casting Derived1* dp2 = dynamic_cast<Derived1*>(bp); if (dp2 == nullptr) cout << \"null\" << endl; else cout << \"not null\" << endl; return 0;}", "e": 29683, "s": 28860, "text": null }, { "code": null, "e": 29693, "s": 29683, "text": "not null\n" }, { "code": null, "e": 30005, "s": 29693, "text": "Explanation: In this program, there is one base class and two derived classes (Derived1, Derived2), here the base class pointer hold derived class 1 object (d1). At the time of dynamic_casting base class, the pointer held the Derived1 object and assigning it to derived class 1, assigned valid dynamic_casting. " }, { "code": null, "e": 30108, "s": 30005, "text": "Case 2: Now, If the cast fails and new_type is a pointer type, it returns a null pointer of that type." }, { "code": null, "e": 30112, "s": 30108, "text": "C++" }, { "code": "// C++ Program demonstrate if the cast// fails and new_type is a pointer type// it returns a null pointer of that type#include <iostream>using namespace std; // Base class declarationclass Base { virtual void print() { cout << \"Base\" << endl; }}; // Derived1 class declarationclass Derived1 : public Base { void print() { cout << \"Derived1\" << endl; }}; // Derived2 class declarationclass Derived2 : public Base { void print() { cout << \"Derived2\" << endl; }}; // Driver Codeint main(){ Derived1 d1; Base* bp = dynamic_cast<Base*>(&d1); // Dynamic Casting Derived2* dp2 = dynamic_cast<Derived2*>(bp); if (dp2 == nullptr) cout << \"null\" << endl; return 0;}", "e": 30849, "s": 30112, "text": null }, { "code": null, "e": 30855, "s": 30849, "text": "null\n" }, { "code": null, "e": 31094, "s": 30855, "text": "Explanation: In this program, at the time of dynamic_casting base class pointer holding the Derived1 object and assigning it to derived class 2, which is not valid dynamic_casting. So, it returns a null pointer of that type in the result." }, { "code": null, "e": 31353, "s": 31094, "text": "Case 3:Now take one more case of dynamic_cast, If the cast fails and new_type is a reference type, it throws an exception that matches a handler of type std::bad_cast and gives a warning: dynamic_cast of “Derived d1” to “class Derived2&” can never succeed. " }, { "code": null, "e": 31357, "s": 31353, "text": "C++" }, { "code": "// C++ Program demonstrate if the cast// fails and new_type is a reference// type it throws an exception#include <exception>#include <iostream>using namespace std; // Base class declarationclass Base { virtual void print() { cout << \"Base\" << endl; }}; // Derived1 classclass Derived1 : public Base { void print() { cout << \"Derived1\" << endl; }}; // Derived2 classclass Derived2 : public Base { void print() { cout << \"Derived2\" << endl; }}; // Driver Codeint main(){ Derived1 d1; Base* bp = dynamic_cast<Base*>(&d1); // Type casting Derived1* dp2 = dynamic_cast<Derived1*>(bp); if (dp2 == nullptr) cout << \"null\" << endl; else cout << \"not null\" << endl; // Exception handling block try { Derived2& r1 = dynamic_cast<Derived2&>(d1); } catch (std::exception& e) { cout << e.what() << endl; } return 0;}", "e": 32283, "s": 31357, "text": null }, { "code": null, "e": 32291, "s": 32283, "text": "Output:" }, { "code": null, "e": 32413, "s": 32291, "text": "warning: dynamic_cast of ‘Derived1 d1’ to ‘class Derived2&’ can never succeed Derived2& r1 = dynamic_cast<Derived2&>(d1);" }, { "code": null, "e": 32419, "s": 32413, "text": "Note:" }, { "code": null, "e": 32533, "s": 32419, "text": "A Dynamic_cast has runtime overhead because it checks object types at run time using “Run-Time Type Information“." }, { "code": null, "e": 32643, "s": 32533, "text": "If there is a surety we will never cast to wrong object then always avoid dynamic_cast and use static_cast. " }, { "code": null, "e": 32654, "s": 32643, "text": "CPP-Basics" }, { "code": null, "e": 32664, "s": 32654, "text": "Data Type" }, { "code": null, "e": 32668, "s": 32664, "text": "C++" }, { "code": null, "e": 32681, "s": 32668, "text": "C++ Programs" }, { "code": null, "e": 32691, "s": 32681, "text": "Data Type" }, { "code": null, "e": 32695, "s": 32691, "text": "CPP" }, { "code": null, "e": 32793, "s": 32695, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32802, "s": 32793, "text": "Comments" }, { "code": null, "e": 32815, "s": 32802, "text": "Old Comments" }, { "code": null, "e": 32843, "s": 32815, "text": "Operator Overloading in C++" }, { "code": null, "e": 32864, "s": 32843, "text": "Iterators in C++ STL" }, { "code": null, "e": 32897, "s": 32864, "text": "Friend class and function in C++" }, { "code": null, "e": 32917, "s": 32897, "text": "Polymorphism in C++" }, { "code": null, "e": 32941, "s": 32917, "text": "Sorting a vector in C++" }, { "code": null, "e": 32976, "s": 32941, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 33002, "s": 32976, "text": "C++ Program for QuickSort" }, { "code": null, "e": 33061, "s": 33002, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 33091, "s": 33061, "text": "CSV file management using C++" } ]
How to pass a lambda expression as a method parameter in Java?
A lambda expression is an anonymous or unnamed method in Java. It doesn't execute on its own and used to implement methods that are declared in a functional interface. If we want to pass a lambda expression as a method parameter in java, the type of method parameter that receives must be of functional interface type. interface Algebra { int operate(int a, int b); } enum Operation { ADD, SUB, MUL, DIV } public class LambdaMethodArgTest { public static void main(String[] args) { print((a, b) -> a + b, Operation.ADD); print((a, b) -> a - b, Operation.SUB); print((a, b) -> a * b, Operation.MUL); print((a, b) -> a / b, Operation.DIV); } static void print(Algebra alg, Operation op) { switch (op) { case ADD: System.out.println("The addition of a and b is: " + alg.operate(40, 20)); break; case SUB: System.out.println("The subtraction of a and b is: " + alg.operate(40, 20)); break; case MUL: System.out.println("The multiplication of a and b is: " + alg.operate(40, 20)); break; case DIV: System.out.println("The division of a and b is: " + alg.operate(40, 20)); break; default: throw new AssertionError(); } } } The addition of a and b is: 60 The subtraction of a and b is: 20 The multiplication of a and b is: 800 The division of a and b is: 2
[ { "code": null, "e": 1381, "s": 1062, "text": "A lambda expression is an anonymous or unnamed method in Java. It doesn't execute on its own and used to implement methods that are declared in a functional interface. If we want to pass a lambda expression as a method parameter in java, the type of method parameter that receives must be of functional interface type." }, { "code": null, "e": 2386, "s": 1381, "text": "interface Algebra {\n int operate(int a, int b);\n}\nenum Operation {\n ADD, SUB, MUL, DIV\n}\npublic class LambdaMethodArgTest {\n public static void main(String[] args) {\n print((a, b) -> a + b, Operation.ADD);\n print((a, b) -> a - b, Operation.SUB);\n print((a, b) -> a * b, Operation.MUL);\n print((a, b) -> a / b, Operation.DIV);\n }\n static void print(Algebra alg, Operation op) {\n switch (op) {\n case ADD:\n System.out.println(\"The addition of a and b is: \" + alg.operate(40, 20));\n break;\n case SUB:\n System.out.println(\"The subtraction of a and b is: \" + alg.operate(40, 20));\n break;\n case MUL:\n System.out.println(\"The multiplication of a and b is: \" + alg.operate(40, 20));\n break;\n case DIV:\n System.out.println(\"The division of a and b is: \" + alg.operate(40, 20));\n break;\n default:\n throw new AssertionError();\n }\n }\n}" }, { "code": null, "e": 2519, "s": 2386, "text": "The addition of a and b is: 60\nThe subtraction of a and b is: 20\nThe multiplication of a and b is: 800\nThe division of a and b is: 2" } ]
What is Lazy Evaluation in Python? | by Xiaoxu Gao | Towards Data Science
If you’ve never heard of Lazy Evaluation before, Lazy Evaluation is an evaluation strategy which delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations (From Wikipedia). It’s usually being considered as a strategy to optimize your code. Let’s turn this theory into an example. For example, you have a simple expression sum = 1 + 2, Python would try to understand the real meaning of this expression and get the conclusion that sum = 3. This process is called Evaluation and it needs some sort of computation power. In this case, the evaluation is done immediately, therefore it has another name: Strict Evaluation. On the other hand, we have a non-strict evaluation which is called Lazy Evaluation. The difference is that Lazy Evaluation will not immediately evaluate the expression but only does it when the outcome is needed. It’s a bit like a lazy student who only does the homework when it needs to be submitted to the teacher. But being lazy here is not necessarily a bad thing, it can improve the efficiency of your code and save plenty of resources. Luckily, Python has silently applied Lazy Evaluation to many built-in functions in order to optimize your code. And I’m sure that you must be familiar with those functions even without being aware of Lazy Evaluation. In this article, I will explain how Lazy Evaluation works in Python, which functions benefit from it, and the reason behind it. In the end, I will show you how you can write your own Lazy functions/classes. Let’s get started! Most of the time, Python still evaluates expression immediately. Let’s look at this example. How long do you think it’s gonna take? print([time.sleep(0), time.sleep(1), time.sleep(2)][0]) The answer is 3 seconds. This is because when you create a list, Python will immediately evaluate every item inside the list, even though you only need the first element. Since Python3, there has been a big improvement in making such list traversal more memory-efficient and time-efficient, which is range() function. I bet every Python developer has used this function at lease once in their life. In Python2, range(5) would return a list of 5 elements. As the size of the list increases, more memory is used. Python 2.7.16>>> range(5)[0, 1, 2, 3, 4]>>> import sys>>> sys.getsizeof(range(5))112>>> sys.getsizeof(range(500))4072 However in Python 3, range(5) returns a range type. This object can be iterated over to yield a sequence of numbers. No matter how big the range is, the object always has the same size. This is due to the fact that range(5) only stores the start, stop, step values, and calculates each item when it’s needed. Python 3.7.7>>> range(5)range(0, 5)>>> import sys>>> sys.getsizeof(range(5))48>>> sys.getsizeof(range(500))48 If you are not familiar with generator, iterator and their benefits, please continue reading this section. Otherwise, feel free to skip this section. iterator > generator To make it simple, iterator is a bigger concept than generator. Iterator is an object whose class has a __next__ and __iter__ method. Every time you do next() call to the iterator object, you would get the next item in the sequence until the iterator object is exhausted and raise StopIteration. However, generator is a function that returns an iterator. It looks like a normal function except that it uses yield instead of return. When the yield statement is executed, the program would suspend the current function execution and returns the yielded value to the caller. This is the key idea of Lazy Evaluation where the value is calculated and returned when the caller is needed and the next value will still be quiet and doing nothing in the program. To create a generator, there can be 2 ways: Then, let’s improve the first example using range(). Before we get to the final result, there is another “trap”. The following example has 2 functions: use_generator() and use_list(). They look almost the same except use_generator() uses () in islice() function, while use_list() uses []. Such small difference can, however, make a huge impact on the running time. The answer to this behaviour is already present in the function name. (time.sleep(x) for x in range(3)) is a generator while [time.sleep(x) for x in range(3)] is a list even though it uses range(). Because of that, the function that uses list takes way more time than the other one. If you understand this part, then congratulations, you’ve already known 50% about Lazy Evaluation. A very similar use case is zip() which merges 2 iterables to produce a sequence of tuples. In Python2, zip(*iterables) would return a list of tuples. Python 2.7.16>>> type(zip([1,2],[3,4]))<type 'list'>>>> import sys>>> sys.getsizeof(zip([1,2],[3,4]))88>>> sys.getsizeof(zip([i for i in range(500)],[i for i in range(500)]))4072 While since Python3, it has been improved to return a zip object which is similar to range object that can be iterated over. Python 3.7.7 >>> type(zip([1,2],[3,4]))<class 'zip'>>>> import sys>>> sys.getsizeof(zip([1,2],[3,4]))72>>> sys.getsizeof(zip([i for i in range(500)],[i for i in range(500)]))72 I will not repeat the reason again because it has the same idea of range(). But if you want to know other aspects of zip, feel free to read my another article. towardsdatascience.com This is another built-in function that we probably use everyday and take it for granted. When we open a file, we normally do: with open("file.csv", "r") as f: for line in f: print(line) with open(...) doesn’t read the entire file and store it in memory, instead it returns a file object that can be iterated over. Because of that, it’s able to efficiently read huge files and not hurt the memory. A couple of weeks ago, I received a question from a reader about Lambda expression which actually triggered me to write this article. His question is: Why does a lambda map object like x = map(lambda x: x*2, [1,2,3,4,5]) doesn’t take any space? But if you do list(x), it will print all the values and take space in the memory? I hope by far, you should have a clue on what’s going on here. The map object is also a lazy object that can be iterated over. The computation x*2 will be done for only 1 item in each loop. When you do list(x), you basically compute all the values at one time. If you just want to iterate over the map object, you don’t have to do list(x). In the last part of the article, I want to bring us to the next level where we write our own Lazy Evaluation function/class. This helps us to extend the capability beyond the built-in functions. As we have understood that a key part of Lazy Evaluation is nothing more than a generator. Therefore, we can simply write our function as a generator. Lazy function — generator Lazy property — decorator Another common use case of customized Lazy Evaluation is the initialization of class properties. When we initialize a class, certain properties might take long time to calculate. In the following example, the property cities takes longer time because it needs to invoke an API to get a list of city names. Therefore, it would be a waste of time if we don’t actually need this value for some country objects. A nice solution present in this blog is to create a decorator for such lazy properties, so that the expensive operation will be done only if this property is needed. As you can see from the console output, cities property is called is printed out after we print out china.cities. I hope this article can inspire you to have a new view on code optimization.
[ { "code": null, "e": 462, "s": 172, "text": "If you’ve never heard of Lazy Evaluation before, Lazy Evaluation is an evaluation strategy which delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations (From Wikipedia). It’s usually being considered as a strategy to optimize your code." }, { "code": null, "e": 840, "s": 462, "text": "Let’s turn this theory into an example. For example, you have a simple expression sum = 1 + 2, Python would try to understand the real meaning of this expression and get the conclusion that sum = 3. This process is called Evaluation and it needs some sort of computation power. In this case, the evaluation is done immediately, therefore it has another name: Strict Evaluation." }, { "code": null, "e": 1157, "s": 840, "text": "On the other hand, we have a non-strict evaluation which is called Lazy Evaluation. The difference is that Lazy Evaluation will not immediately evaluate the expression but only does it when the outcome is needed. It’s a bit like a lazy student who only does the homework when it needs to be submitted to the teacher." }, { "code": null, "e": 1499, "s": 1157, "text": "But being lazy here is not necessarily a bad thing, it can improve the efficiency of your code and save plenty of resources. Luckily, Python has silently applied Lazy Evaluation to many built-in functions in order to optimize your code. And I’m sure that you must be familiar with those functions even without being aware of Lazy Evaluation." }, { "code": null, "e": 1725, "s": 1499, "text": "In this article, I will explain how Lazy Evaluation works in Python, which functions benefit from it, and the reason behind it. In the end, I will show you how you can write your own Lazy functions/classes. Let’s get started!" }, { "code": null, "e": 1857, "s": 1725, "text": "Most of the time, Python still evaluates expression immediately. Let’s look at this example. How long do you think it’s gonna take?" }, { "code": null, "e": 1913, "s": 1857, "text": "print([time.sleep(0), time.sleep(1), time.sleep(2)][0])" }, { "code": null, "e": 2084, "s": 1913, "text": "The answer is 3 seconds. This is because when you create a list, Python will immediately evaluate every item inside the list, even though you only need the first element." }, { "code": null, "e": 2424, "s": 2084, "text": "Since Python3, there has been a big improvement in making such list traversal more memory-efficient and time-efficient, which is range() function. I bet every Python developer has used this function at lease once in their life. In Python2, range(5) would return a list of 5 elements. As the size of the list increases, more memory is used." }, { "code": null, "e": 2542, "s": 2424, "text": "Python 2.7.16>>> range(5)[0, 1, 2, 3, 4]>>> import sys>>> sys.getsizeof(range(5))112>>> sys.getsizeof(range(500))4072" }, { "code": null, "e": 2851, "s": 2542, "text": "However in Python 3, range(5) returns a range type. This object can be iterated over to yield a sequence of numbers. No matter how big the range is, the object always has the same size. This is due to the fact that range(5) only stores the start, stop, step values, and calculates each item when it’s needed." }, { "code": null, "e": 2961, "s": 2851, "text": "Python 3.7.7>>> range(5)range(0, 5)>>> import sys>>> sys.getsizeof(range(5))48>>> sys.getsizeof(range(500))48" }, { "code": null, "e": 3111, "s": 2961, "text": "If you are not familiar with generator, iterator and their benefits, please continue reading this section. Otherwise, feel free to skip this section." }, { "code": null, "e": 3132, "s": 3111, "text": "iterator > generator" }, { "code": null, "e": 3564, "s": 3132, "text": "To make it simple, iterator is a bigger concept than generator. Iterator is an object whose class has a __next__ and __iter__ method. Every time you do next() call to the iterator object, you would get the next item in the sequence until the iterator object is exhausted and raise StopIteration. However, generator is a function that returns an iterator. It looks like a normal function except that it uses yield instead of return." }, { "code": null, "e": 3886, "s": 3564, "text": "When the yield statement is executed, the program would suspend the current function execution and returns the yielded value to the caller. This is the key idea of Lazy Evaluation where the value is calculated and returned when the caller is needed and the next value will still be quiet and doing nothing in the program." }, { "code": null, "e": 3930, "s": 3886, "text": "To create a generator, there can be 2 ways:" }, { "code": null, "e": 4295, "s": 3930, "text": "Then, let’s improve the first example using range(). Before we get to the final result, there is another “trap”. The following example has 2 functions: use_generator() and use_list(). They look almost the same except use_generator() uses () in islice() function, while use_list() uses []. Such small difference can, however, make a huge impact on the running time." }, { "code": null, "e": 4578, "s": 4295, "text": "The answer to this behaviour is already present in the function name. (time.sleep(x) for x in range(3)) is a generator while [time.sleep(x) for x in range(3)] is a list even though it uses range(). Because of that, the function that uses list takes way more time than the other one." }, { "code": null, "e": 4677, "s": 4578, "text": "If you understand this part, then congratulations, you’ve already known 50% about Lazy Evaluation." }, { "code": null, "e": 4827, "s": 4677, "text": "A very similar use case is zip() which merges 2 iterables to produce a sequence of tuples. In Python2, zip(*iterables) would return a list of tuples." }, { "code": null, "e": 5006, "s": 4827, "text": "Python 2.7.16>>> type(zip([1,2],[3,4]))<type 'list'>>>> import sys>>> sys.getsizeof(zip([1,2],[3,4]))88>>> sys.getsizeof(zip([i for i in range(500)],[i for i in range(500)]))4072" }, { "code": null, "e": 5131, "s": 5006, "text": "While since Python3, it has been improved to return a zip object which is similar to range object that can be iterated over." }, { "code": null, "e": 5308, "s": 5131, "text": "Python 3.7.7 >>> type(zip([1,2],[3,4]))<class 'zip'>>>> import sys>>> sys.getsizeof(zip([1,2],[3,4]))72>>> sys.getsizeof(zip([i for i in range(500)],[i for i in range(500)]))72" }, { "code": null, "e": 5468, "s": 5308, "text": "I will not repeat the reason again because it has the same idea of range(). But if you want to know other aspects of zip, feel free to read my another article." }, { "code": null, "e": 5491, "s": 5468, "text": "towardsdatascience.com" }, { "code": null, "e": 5617, "s": 5491, "text": "This is another built-in function that we probably use everyday and take it for granted. When we open a file, we normally do:" }, { "code": null, "e": 5685, "s": 5617, "text": "with open(\"file.csv\", \"r\") as f: for line in f: print(line)" }, { "code": null, "e": 5896, "s": 5685, "text": "with open(...) doesn’t read the entire file and store it in memory, instead it returns a file object that can be iterated over. Because of that, it’s able to efficiently read huge files and not hurt the memory." }, { "code": null, "e": 6047, "s": 5896, "text": "A couple of weeks ago, I received a question from a reader about Lambda expression which actually triggered me to write this article. His question is:" }, { "code": null, "e": 6223, "s": 6047, "text": "Why does a lambda map object like x = map(lambda x: x*2, [1,2,3,4,5]) doesn’t take any space? But if you do list(x), it will print all the values and take space in the memory?" }, { "code": null, "e": 6563, "s": 6223, "text": "I hope by far, you should have a clue on what’s going on here. The map object is also a lazy object that can be iterated over. The computation x*2 will be done for only 1 item in each loop. When you do list(x), you basically compute all the values at one time. If you just want to iterate over the map object, you don’t have to do list(x)." }, { "code": null, "e": 6758, "s": 6563, "text": "In the last part of the article, I want to bring us to the next level where we write our own Lazy Evaluation function/class. This helps us to extend the capability beyond the built-in functions." }, { "code": null, "e": 6909, "s": 6758, "text": "As we have understood that a key part of Lazy Evaluation is nothing more than a generator. Therefore, we can simply write our function as a generator." }, { "code": null, "e": 6935, "s": 6909, "text": "Lazy function — generator" }, { "code": null, "e": 6961, "s": 6935, "text": "Lazy property — decorator" }, { "code": null, "e": 7369, "s": 6961, "text": "Another common use case of customized Lazy Evaluation is the initialization of class properties. When we initialize a class, certain properties might take long time to calculate. In the following example, the property cities takes longer time because it needs to invoke an API to get a list of city names. Therefore, it would be a waste of time if we don’t actually need this value for some country objects." }, { "code": null, "e": 7649, "s": 7369, "text": "A nice solution present in this blog is to create a decorator for such lazy properties, so that the expensive operation will be done only if this property is needed. As you can see from the console output, cities property is called is printed out after we print out china.cities." } ]
How do you click on an element which is hidden using Selenium WebDriver?
We can click on an element which is hidden with Selenium webdriver. The hidden elements are the ones which are present in the DOM but not visible on the page. Mostly the hidden elements are defined by the CSS property style="display:none;". In case an element is a part of the form tag, it can be hidden by setting the attribute type to the value hidden. Selenium by default cannot handle hidden elements and throws ElementNotVisibleException while working with them. Javascript Executor is used to handle hidden elements on the page. Selenium runs the Javascript commands with the executeScript method. The commands to be run are passed as arguments to the method. First of all, the getElementById method can be used to identify the element. Next to enter text to the field, the value method is used to set value to the field. executor.executeScript ("document.getElementById('txt').value='Selenium'"); Let’s take an example where there are two buttons Hide and Show. Also there is an edit box below the buttons. Once we click on the Hide button, the edit box disappears from the page. Now let us enter some text inside the hidden text box. Code Implementation. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class ElementHidden{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://learn.letskodeit.com/p/practice"); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // identify element and click driver.findElement(By.id("hide-textbox")).click(); // Javascript executor class with executeScript method JavascriptExecutor j = (JavascriptExecutor) driver; // identify element and set value j.executeScript ("document.getElementById('displayed-text').value='Selenium';"); String s = (String) j.executeScript("return document.getElementById('displayed-text').value"); System.out.print("Value entered in hidden field: " +s); driver.close() } }
[ { "code": null, "e": 1542, "s": 1187, "text": "We can click on an element which is hidden with Selenium webdriver. The hidden elements are the ones which are present in the DOM but not visible on the page. Mostly the hidden elements are defined by the CSS property style=\"display:none;\". In case an element is a part of the form tag, it can be hidden by setting the attribute type to the value hidden." }, { "code": null, "e": 1853, "s": 1542, "text": "Selenium by default cannot handle hidden elements and throws ElementNotVisibleException while working with them. Javascript Executor is used to handle hidden elements on the page. Selenium runs the Javascript commands with the executeScript method. The commands to be run are passed as arguments to the method." }, { "code": null, "e": 2015, "s": 1853, "text": "First of all, the getElementById method can be used to identify the element. Next to enter text to the field, the value method is used to set value to the field." }, { "code": null, "e": 2091, "s": 2015, "text": "executor.executeScript\n(\"document.getElementById('txt').value='Selenium'\");" }, { "code": null, "e": 2274, "s": 2091, "text": "Let’s take an example where there are two buttons Hide and Show. Also there is an edit box below the buttons. Once we click on the Hide button, the edit box disappears from the page." }, { "code": null, "e": 2329, "s": 2274, "text": "Now let us enter some text inside the hidden text box." }, { "code": null, "e": 2350, "s": 2329, "text": "Code Implementation." }, { "code": null, "e": 3477, "s": 2350, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class ElementHidden{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://learn.letskodeit.com/p/practice\");\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify element and click\n driver.findElement(By.id(\"hide-textbox\")).click();\n // Javascript executor class with executeScript method\n JavascriptExecutor j = (JavascriptExecutor) driver;\n // identify element and set value\n j.executeScript (\"document.getElementById('displayed-text').value='Selenium';\");\n String s = (String) j.executeScript(\"return document.getElementById('displayed-text').value\");\n System.out.print(\"Value entered in hidden field: \" +s);\n driver.close()\n }\n}" } ]
Python PIL | ImageDraw.Draw.pieslice()
02 Aug, 2019 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use. ImageDraw.Draw.pieslice() Same as arc, but also draws straight lines between the end points and the center of the bounding box. Syntax: PIL.ImageDraw.Draw.pieslice(xy, start, end, fill=None, outline=None) Parameters:xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].start – Starting angle, in degrees. Angles are measured from 3 o’clock, increasing clockwise.end – Ending angle, in degrees.fill – Color to use for the fill.outline – Color to use for the outline. Returns: An Image object in pieslice shape. # importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new("RGB", (w, h)) # create pieslice imageimg1 = ImageDraw.Draw(img) img1.pieslice(shape, start = 50, end = 250, fill ="# ffff33", outline ="red")img.show() Output: Another Example: Here we use different colour for filling. # importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new("RGB", (w, h)) # create pieslice imageimg1 = ImageDraw.Draw(img) img1.pieslice(shape, start = 50, end = 250, fill ="# 800080", outline ="white")img.show() Output: Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Aug, 2019" }, { "code": null, "e": 332, "s": 28, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use." }, { "code": null, "e": 460, "s": 332, "text": "ImageDraw.Draw.pieslice() Same as arc, but also draws straight lines between the end points and the center of the bounding box." }, { "code": null, "e": 537, "s": 460, "text": "Syntax: PIL.ImageDraw.Draw.pieslice(xy, start, end, fill=None, outline=None)" }, { "code": null, "e": 843, "s": 537, "text": "Parameters:xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].start – Starting angle, in degrees. Angles are measured from 3 o’clock, increasing clockwise.end – Ending angle, in degrees.fill – Color to use for the fill.outline – Color to use for the outline." }, { "code": null, "e": 887, "s": 843, "text": "Returns: An Image object in pieslice shape." }, { "code": " # importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new(\"RGB\", (w, h)) # create pieslice imageimg1 = ImageDraw.Draw(img) img1.pieslice(shape, start = 50, end = 250, fill =\"# ffff33\", outline =\"red\")img.show()", "e": 1224, "s": 887, "text": null }, { "code": null, "e": 1232, "s": 1224, "text": "Output:" }, { "code": null, "e": 1291, "s": 1232, "text": "Another Example: Here we use different colour for filling." }, { "code": " # importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new(\"RGB\", (w, h)) # create pieslice imageimg1 = ImageDraw.Draw(img) img1.pieslice(shape, start = 50, end = 250, fill =\"# 800080\", outline =\"white\")img.show()", "e": 1628, "s": 1291, "text": null }, { "code": null, "e": 1636, "s": 1628, "text": "Output:" }, { "code": null, "e": 1647, "s": 1636, "text": "Python-pil" }, { "code": null, "e": 1654, "s": 1647, "text": "Python" }, { "code": null, "e": 1752, "s": 1654, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1784, "s": 1752, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1811, "s": 1784, "text": "Python Classes and Objects" }, { "code": null, "e": 1832, "s": 1811, "text": "Python OOPs Concepts" }, { "code": null, "e": 1863, "s": 1832, "text": "Python | os.path.join() method" }, { "code": null, "e": 1919, "s": 1863, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1942, "s": 1919, "text": "Introduction To PYTHON" }, { "code": null, "e": 1984, "s": 1942, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2026, "s": 1984, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2065, "s": 2026, "text": "Python | datetime.timedelta() function" } ]
Python hasattr() method
05 Jul, 2022 Python hasattr() function is an inbuilt utility function, which is used to check if an object has the given named attribute and return true if present, else false. In this article, we will see how to check if an object has an attribute in Python. Syntax : hasattr(obj, key) Parameters : obj : The object whose which attribute has to be checked. key : Attribute which needs to be checked. Returns : Returns True, if attribute is present else returns False. Here we will check if an object has an attribute, to find attributes of the object in python we have demonstrated the following code. Python3 # declaring classclass GfG: name = "GeeksforGeeks" age = 24 # initializing objectobj = GfG() # using hasattr() to check nameprint("Does name exist ? " + str(hasattr(obj, 'name'))) # using hasattr() to check mottoprint("Does motto exist ? " + str(hasattr(obj, 'motto'))) Output: Does name exist ? True Does motto exist ? False This is the Simple Ways to Check if an Object has Attribute in Python or not using performance analysis between hasattr() function and try statement. Python3 import time # declaring classclass GfG: name = "GeeksforGeeks" age = 24 # initializing objectobj = GfG() # use of hasattr to check mottostart_hasattr = time.time()if(hasattr(obj, 'motto')): print("Motto is there")else: print("No Motto") print("Time to execute hasattr : " + str(time.time() - start_hasattr)) # use of try/except to check mottostart_try = time.time()try: print(obj.motto) print("Motto is there")except AttributeError: print("No Motto")print("Time to execute try : " + str(time.time() - start_try)) Output: No Motto Time to execute hasattr : 5.245208740234375e-06 No Motto Time to execute try : 2.6226043701171875e-06 Result: Conventional try/except takes lesser time than hasattr(), but for readability of code, hasattr() is always a better choice. Applications: This function can be used to check keys to avoid unnecessary errors in case of accessing absent keys. Chaining of hasattr() is used sometimes to avoid entry of one associated attribute if the other is not present. kumar_satyam prachisoda1234 surajkumarguptaintern Python-Built-in-functions python-object Python-OOP Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 53, "s": 25, "text": "\n05 Jul, 2022" }, { "code": null, "e": 300, "s": 53, "text": "Python hasattr() function is an inbuilt utility function, which is used to check if an object has the given named attribute and return true if present, else false. In this article, we will see how to check if an object has an attribute in Python." }, { "code": null, "e": 327, "s": 300, "text": "Syntax : hasattr(obj, key)" }, { "code": null, "e": 341, "s": 327, "text": "Parameters : " }, { "code": null, "e": 399, "s": 341, "text": "obj : The object whose which attribute has to be checked." }, { "code": null, "e": 442, "s": 399, "text": "key : Attribute which needs to be checked." }, { "code": null, "e": 511, "s": 442, "text": "Returns : Returns True, if attribute is present else returns False. " }, { "code": null, "e": 645, "s": 511, "text": "Here we will check if an object has an attribute, to find attributes of the object in python we have demonstrated the following code." }, { "code": null, "e": 653, "s": 645, "text": "Python3" }, { "code": "# declaring classclass GfG: name = \"GeeksforGeeks\" age = 24 # initializing objectobj = GfG() # using hasattr() to check nameprint(\"Does name exist ? \" + str(hasattr(obj, 'name'))) # using hasattr() to check mottoprint(\"Does motto exist ? \" + str(hasattr(obj, 'motto')))", "e": 930, "s": 653, "text": null }, { "code": null, "e": 939, "s": 930, "text": "Output: " }, { "code": null, "e": 987, "s": 939, "text": "Does name exist ? True\nDoes motto exist ? False" }, { "code": null, "e": 1137, "s": 987, "text": "This is the Simple Ways to Check if an Object has Attribute in Python or not using performance analysis between hasattr() function and try statement." }, { "code": null, "e": 1145, "s": 1137, "text": "Python3" }, { "code": "import time # declaring classclass GfG: name = \"GeeksforGeeks\" age = 24 # initializing objectobj = GfG() # use of hasattr to check mottostart_hasattr = time.time()if(hasattr(obj, 'motto')): print(\"Motto is there\")else: print(\"No Motto\") print(\"Time to execute hasattr : \" + str(time.time() - start_hasattr)) # use of try/except to check mottostart_try = time.time()try: print(obj.motto) print(\"Motto is there\")except AttributeError: print(\"No Motto\")print(\"Time to execute try : \" + str(time.time() - start_try))", "e": 1679, "s": 1145, "text": null }, { "code": null, "e": 1688, "s": 1679, "text": "Output: " }, { "code": null, "e": 1799, "s": 1688, "text": "No Motto\nTime to execute hasattr : 5.245208740234375e-06\nNo Motto\nTime to execute try : 2.6226043701171875e-06" }, { "code": null, "e": 1931, "s": 1799, "text": "Result: Conventional try/except takes lesser time than hasattr(), but for readability of code, hasattr() is always a better choice." }, { "code": null, "e": 2159, "s": 1931, "text": "Applications: This function can be used to check keys to avoid unnecessary errors in case of accessing absent keys. Chaining of hasattr() is used sometimes to avoid entry of one associated attribute if the other is not present." }, { "code": null, "e": 2172, "s": 2159, "text": "kumar_satyam" }, { "code": null, "e": 2187, "s": 2172, "text": "prachisoda1234" }, { "code": null, "e": 2209, "s": 2187, "text": "surajkumarguptaintern" }, { "code": null, "e": 2235, "s": 2209, "text": "Python-Built-in-functions" }, { "code": null, "e": 2249, "s": 2235, "text": "python-object" }, { "code": null, "e": 2260, "s": 2249, "text": "Python-OOP" }, { "code": null, "e": 2267, "s": 2260, "text": "Python" }, { "code": null, "e": 2365, "s": 2267, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2397, "s": 2365, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2424, "s": 2397, "text": "Python Classes and Objects" }, { "code": null, "e": 2445, "s": 2424, "text": "Python OOPs Concepts" }, { "code": null, "e": 2468, "s": 2445, "text": "Introduction To PYTHON" }, { "code": null, "e": 2524, "s": 2468, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2555, "s": 2524, "text": "Python | os.path.join() method" }, { "code": null, "e": 2597, "s": 2555, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2639, "s": 2597, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2678, "s": 2639, "text": "Python | datetime.timedelta() function" } ]
The Lazy-Code-Motion problem
17 Jun, 2021 The Lazy-Code-Motion problem :To avoid redundant calculations, reduce code size, or save resources, code mobility optimizations move computations across a control-flow graph (CFG). For example, loop invariant code motion recognizes expressions computed within loops that have the same value iteration after iteration and hoists them out of the loop so that they are only computed once. Instead of computing a subexpression ‘e’ twice in expressions f(e) and g(e), compute it once and store it in a temporary register. main { one: int = const 1; do_nothing compute: y: int = add x one; gfgdone; do_nothing: gfgdone; done: z: int = add x one; ret; } All paths through the program now include only one x+1 calculation. This is optimal code, at least in that dimension, and a reasonable outcome from partial redundancy removal or lazy code motion. So, what distinguishes lazy code motion from eager alternatives? Make a note of the pressure :In an architecture with a finite and fixed number of registers, compilers must allocate storage for a limited but unlimited number of variables when reducing IR code to assembly. Some variables will wind up on the stack if there are more variables than registers. Memory is slower than registers, therefore “spilling” to the stack is expensive.The compiler should aim to reduce the amount of spills introduced during register allocation in earlier passes. The exact amount of spills introduced into a program is determined by the register allocation technique in use, making optimizing against this statistic a fool’s errand. Variable definitions (computations) are moved further away from their uses by eager code motion, extending their life ranges. Any performance benefits owing to code motion can be easily clawed out due to the accompanying register pressure. Lazy code motion, rather than making computations as early as feasible, shifts them down to a later program point, avoiding unnecessary processing. In reality, one study establishes that lazy code motion places calculations “as late as possible, although this phrase is misleading when taken out of context. The system does a static analysis to find potential safe moves before selecting the most recent possibilities. The Lazy Code Problem Limitations :Lexically equal expressions should always be placed in the same pseudoregister, according to the optimization. Later studies may make changes to the dataflow analyses to weaken this assumption. This causes superfluous move instructions to fetch computed values from temporaries, which increases register pressure. A more intelligent rewriting pass may be able to reduce these expenses. The compute placement algorithm is inefficient at the other end of the optimization spectrum. Lazy code motion moves computations to the CFG’s edges, requiring new basic blocks to be stitched into the edges. While they are required in most cases, an inserted basic block can be securely merged with its predecessor or successor block on many edges. Because the amount of leaps would be reduced, this might improve performance. Similarly, the pretty-printer for CFGs does not omit leaps where fall-through would work—this may appear to be a trivial matter, but it could affect performance or code size. Both of these problems could be solved by running a simplification pass after the lazy code move. Conclusion :The amount of computations never rises after optimization, since lazy code motion is meant to avoid redundant expression computations. The cost of the cautious temporary allocation technique and basic block insertion appears to have a detrimental influence on the total number of calculations by adding movements and jumps. Due to computations being hoisted out of loops, loopy benchmarks (basic, hoist-thru-loop) show considerable speedups. Picked Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unit Testing | Software Testing Software Engineering | Black box testing System Testing Software Engineering | Integration Testing Equivalence Partitioning Method Software Engineering | Calculation of Function Point (FP) Software Development Life Cycle (SDLC) What is DFD(Data Flow Diagram)? Software Processes in Software Engineering Software Measurement and Metrics
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jun, 2021" }, { "code": null, "e": 571, "s": 54, "text": "The Lazy-Code-Motion problem :To avoid redundant calculations, reduce code size, or save resources, code mobility optimizations move computations across a control-flow graph (CFG). For example, loop invariant code motion recognizes expressions computed within loops that have the same value iteration after iteration and hoists them out of the loop so that they are only computed once. Instead of computing a subexpression ‘e’ twice in expressions f(e) and g(e), compute it once and store it in a temporary register." }, { "code": null, "e": 715, "s": 571, "text": "main {\n one: int = const 1;\n do_nothing\ncompute:\n y: int = add x one;\n gfgdone;\ndo_nothing:\n gfgdone;\ndone:\n z: int = add x one;\n ret;\n}" }, { "code": null, "e": 976, "s": 715, "text": "All paths through the program now include only one x+1 calculation. This is optimal code, at least in that dimension, and a reasonable outcome from partial redundancy removal or lazy code motion. So, what distinguishes lazy code motion from eager alternatives?" }, { "code": null, "e": 1631, "s": 976, "text": "Make a note of the pressure :In an architecture with a finite and fixed number of registers, compilers must allocate storage for a limited but unlimited number of variables when reducing IR code to assembly. Some variables will wind up on the stack if there are more variables than registers. Memory is slower than registers, therefore “spilling” to the stack is expensive.The compiler should aim to reduce the amount of spills introduced during register allocation in earlier passes. The exact amount of spills introduced into a program is determined by the register allocation technique in use, making optimizing against this statistic a fool’s errand." }, { "code": null, "e": 2290, "s": 1631, "text": "Variable definitions (computations) are moved further away from their uses by eager code motion, extending their life ranges. Any performance benefits owing to code motion can be easily clawed out due to the accompanying register pressure. Lazy code motion, rather than making computations as early as feasible, shifts them down to a later program point, avoiding unnecessary processing. In reality, one study establishes that lazy code motion places calculations “as late as possible, although this phrase is misleading when taken out of context. The system does a static analysis to find potential safe moves before selecting the most recent possibilities." }, { "code": null, "e": 2312, "s": 2290, "text": "The Lazy Code Problem" }, { "code": null, "e": 2711, "s": 2312, "text": "Limitations :Lexically equal expressions should always be placed in the same pseudoregister, according to the optimization. Later studies may make changes to the dataflow analyses to weaken this assumption. This causes superfluous move instructions to fetch computed values from temporaries, which increases register pressure. A more intelligent rewriting pass may be able to reduce these expenses." }, { "code": null, "e": 3411, "s": 2711, "text": "The compute placement algorithm is inefficient at the other end of the optimization spectrum. Lazy code motion moves computations to the CFG’s edges, requiring new basic blocks to be stitched into the edges. While they are required in most cases, an inserted basic block can be securely merged with its predecessor or successor block on many edges. Because the amount of leaps would be reduced, this might improve performance. Similarly, the pretty-printer for CFGs does not omit leaps where fall-through would work—this may appear to be a trivial matter, but it could affect performance or code size. Both of these problems could be solved by running a simplification pass after the lazy code move." }, { "code": null, "e": 3865, "s": 3411, "text": "Conclusion :The amount of computations never rises after optimization, since lazy code motion is meant to avoid redundant expression computations. The cost of the cautious temporary allocation technique and basic block insertion appears to have a detrimental influence on the total number of calculations by adding movements and jumps. Due to computations being hoisted out of loops, loopy benchmarks (basic, hoist-thru-loop) show considerable speedups." }, { "code": null, "e": 3872, "s": 3865, "text": "Picked" }, { "code": null, "e": 3893, "s": 3872, "text": "Software Engineering" }, { "code": null, "e": 3991, "s": 3893, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4023, "s": 3991, "text": "Unit Testing | Software Testing" }, { "code": null, "e": 4064, "s": 4023, "text": "Software Engineering | Black box testing" }, { "code": null, "e": 4079, "s": 4064, "text": "System Testing" }, { "code": null, "e": 4122, "s": 4079, "text": "Software Engineering | Integration Testing" }, { "code": null, "e": 4154, "s": 4122, "text": "Equivalence Partitioning Method" }, { "code": null, "e": 4212, "s": 4154, "text": "Software Engineering | Calculation of Function Point (FP)" }, { "code": null, "e": 4251, "s": 4212, "text": "Software Development Life Cycle (SDLC)" }, { "code": null, "e": 4283, "s": 4251, "text": "What is DFD(Data Flow Diagram)?" }, { "code": null, "e": 4326, "s": 4283, "text": "Software Processes in Software Engineering" } ]
Maximize jobs that can be completed under given constraint
07 Apr, 2022 Given an integer N denoting number of jobs and a matrix ranges[] consisting of a range [start day, end day] for each job within which it needs to be completed, the task is to find the maximum possible jobs that can be completed.Examples: Input: N = 5, Ranges = {{1, 5}, {1, 5}, {1, 5}, {2, 3}, {2, 3}} Output: 5 Explanation: Job 1 on day 1, Job 4 on day 2, Job 5 on day 3, Job 2 on day 4, Job 3 on day 5 Input: N=6, Ranges = {{1, 3}, {1, 3}, {2, 3}, {2, 3}, {1, 4}, {2, 5}} Output: 5 Approach: The above problem can be solved using a Priority Queue. Follow the steps below to solve the problems: Find the minimum and maximum day in the range of jobs. Sort all jobs in increasing order of start day. Iterate from the minimum to maximum day, and for every ith day, select the job having least end day which can be completed on that day. In order to perform the above step, maintain a Min Heap, and on every ith day, insert the jobs that can be completed on that day, into the Min Heap sorted by end day. If any job can completed on the ith day, consider the one with the lowest end day and increase the count of jobs completed. Repeat this process for all the days and finally print the count of jobs completed. Below is an implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement the// above approach #include <bits/stdc++.h>using namespace std; // Function to find maximum// number of jobsint find_maximum_jobs( int N, vector<pair<int, int> > ranges){ // Min Heap priority_queue<int, vector<int>, greater<int> > queue; // Sort ranges by start day sort(ranges.begin(), ranges.end()); // Stores the minimum and maximum // day in the ranges int min_day = ranges[0].first; int max_day = 0; for (int i = 0; i < N; i++) max_day = max(max_day, ranges[i].second); int index = 0, count_jobs = 0; // Iterating from min_day to max_day for (int i = min_day; i <= max_day; i++) { // Insert the end day of the jobs // which can be completed on // i-th day in a priority queue while (index < ranges.size() && ranges[index].first <= i) { queue.push(ranges[index].second); index++; } // Pop all jobs whose end day // is less than current day while (!queue.empty() && queue.top() < i) queue.pop(); // If queue is empty, no job // can be completed on // the i-th day if (queue.empty()) continue; // Increment the count of // jobs completed count_jobs++; // Pop the job with // least end day queue.pop(); } // Return the jobs // on the last day return count_jobs;} // Driver Codeint main(){ int N = 5; vector<pair<int, int> > ranges; ranges.push_back({ 1, 5 }); ranges.push_back({ 1, 5 }); ranges.push_back({ 1, 5 }); ranges.push_back({ 2, 3 }); ranges.push_back({ 2, 3 }); cout << find_maximum_jobs(N, ranges);} // Java Program to implement the// above approachimport java.io.*;import java.util.*; class GFG { // Function to find maximum // number of jobs static int find_maximum_jobs(int N, ArrayList<ArrayList<Integer>> ranges) { // Min Heap ArrayList<Integer> queue = new ArrayList<Integer>(); // Sort ranges by start day Collections.sort(ranges, new Comparator<ArrayList<Integer>>() { @Override public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) { return o1.get(0).compareTo(o2.get(0)); } }); // Stores the minimum and maximum // day in the ranges int min_day = ranges.get(0).get(0); int max_day = 0; for (int i = 0; i < N; i++) max_day = Math.max(max_day, ranges.get(i).get(1)); int index = 0, count_jobs = 0; // Iterating from min_day to max_day for (int i = min_day; i <= max_day; i++) { // Insert the end day of the jobs // which can be completed on // i-th day in a priority queue while (index < ranges.size() && ranges.get(index).get(0) <= i) { queue.add(ranges.get(index).get(1)); index++; } Collections.sort(queue); // Pop all jobs whose end day // is less than current day while (queue.size() > 0 && queue.get(0) < i) queue.remove(0); // If queue is empty, no job // can be completed on // the i-th day if (queue.size() == 0) continue; // Increment the count of // jobs completed count_jobs++; // Pop the job with // least end day queue.remove(0); } // Return the jobs // on the last day return count_jobs; } // Driver code public static void main (String[] args) { int N = 5; ArrayList<ArrayList<Integer>> ranges = new ArrayList<ArrayList<Integer>>(); ranges.add(new ArrayList<Integer>(Arrays.asList(1, 5))); ranges.add(new ArrayList<Integer>(Arrays.asList(1, 5))); ranges.add(new ArrayList<Integer>(Arrays.asList(1, 5))); ranges.add(new ArrayList<Integer>(Arrays.asList(2, 3))); ranges.add(new ArrayList<Integer>(Arrays.asList(2, 3))); System.out.println(find_maximum_jobs(N, ranges)); }}// This code is contributed by avanitrachhadiya2155 # Python3 Program to implement the# above approach # Function to find maximum# number of jobsdef find_maximum_jobs(N, ranges) : # Min Heap queue = [] # Sort ranges by start day ranges.sort() # Stores the minimum and maximum # day in the ranges min_day = ranges[0][0] max_day = 0 for i in range(N) : max_day = max(max_day, ranges[i][1]) index, count_jobs = 0, 0 # Iterating from min_day to max_day for i in range(min_day, max_day + 1) : # Insert the end day of the jobs # which can be completed on # i-th day in a priority queue while (index < len(ranges) and ranges[index][0] <= i) : queue.append(ranges[index][1]) index += 1 queue.sort() # Pop all jobs whose end day # is less than current day while (len(queue) > 0 and queue[0] < i) : queue.pop(0) # If queue is empty, no job # can be completed on # the i-th day if (len(queue) == 0) : continue # Increment the count of # jobs completed count_jobs += 1 # Pop the job with # least end day queue.pop(0) # Return the jobs # on the last day return count_jobs # Driver codeN = 5ranges = []ranges.append((1, 5))ranges.append((1, 5))ranges.append((1, 5))ranges.append((2, 3))ranges.append((2, 3)) print(find_maximum_jobs(N, ranges)) # This code is contributed by divyeshrabadiya07. // C# Program to implement the// above approachusing System;using System.Collections.Generic;class GFG { // Function to find maximum // number of jobs static int find_maximum_jobs(int N, List<Tuple<int, int>> ranges) { // Min Heap List<int> queue = new List<int>(); // Sort ranges by start day ranges.Sort(); // Stores the minimum and maximum // day in the ranges int min_day = ranges[0].Item1; int max_day = 0; for (int i = 0; i < N; i++) max_day = Math.Max(max_day, ranges[i].Item2); int index = 0, count_jobs = 0; // Iterating from min_day to max_day for (int i = min_day; i <= max_day; i++) { // Insert the end day of the jobs // which can be completed on // i-th day in a priority queue while (index < ranges.Count && ranges[index].Item1 <= i) { queue.Add(ranges[index].Item2); index++; } queue.Sort(); // Pop all jobs whose end day // is less than current day while (queue.Count > 0 && queue[0] < i) queue.RemoveAt(0); // If queue is empty, no job // can be completed on // the i-th day if (queue.Count == 0) continue; // Increment the count of // jobs completed count_jobs++; // Pop the job with // least end day queue.RemoveAt(0); } // Return the jobs // on the last day return count_jobs; } // Driver code static void Main() { int N = 5; List<Tuple<int, int>> ranges = new List<Tuple<int, int>>(); ranges.Add(new Tuple<int,int>(1, 5)); ranges.Add(new Tuple<int,int>(1, 5)); ranges.Add(new Tuple<int,int>(1, 5)); ranges.Add(new Tuple<int,int>(2, 3)); ranges.Add(new Tuple<int,int>(2, 3)); Console.Write(find_maximum_jobs(N, ranges)); }} // This code is contributed by divyesh072019. <script> // JavaScript program for the above approach // Function to find maximum// number of jobsfunction find_maximum_jobs(N, ranges){ // Min Heap let queue = [] // Sort ranges by start day ranges.sort() // Stores the minimum && maximum // day in the ranges let min_day = ranges[0][0] let max_day = 0 for(let i = 0;i<N ; i++){ max_day = Math.max(max_day, ranges[i][1]) } let index = 0, count_jobs = 0 // Iterating from min_day to max_day for(let i = min_day;i< max_day + 1;i++) { // Insert the end day of the jobs // which can be completed on // i-th day in a priority queue while (index < ranges.length && ranges[index][0] <= i){ queue.push(ranges[index][1]) index += 1 } queue.sort() // Pop all jobs whose end day // is less than current day while (queue.length > 0 && queue[0] < i) queue.shift() // If queue is empty, no job // can be completed on // the i-th day if (queue.length == 0) continue // Increment the count of // jobs completed count_jobs += 1 // Pop the job with // least end day queue.shift() } // Return the jobs // on the last day return count_jobs} // Driver codelet N = 5let ranges = []ranges.push([1, 5])ranges.push([1, 5])ranges.push([1, 5])ranges.push([2, 3])ranges.push([2, 3]) document.write(find_maximum_jobs(N, ranges)) // This code is contributed by shinjanpatra </script> 5 Time Complexity: O(Xlog(N)), where X is the difference between maximum and minimum day and N is the number of jobs. Auxiliary Space: O(N2) divyesh072019 divyeshrabadiya07 avanitrachhadiya2155 sumitgumber28 shinjanpatra cpp-priority-queue interview-preparation min-heap Algorithms Competitive Programming Greedy Heap Sorting Greedy Sorting Heap Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Apr, 2022" }, { "code": null, "e": 294, "s": 54, "text": "Given an integer N denoting number of jobs and a matrix ranges[] consisting of a range [start day, end day] for each job within which it needs to be completed, the task is to find the maximum possible jobs that can be completed.Examples: " }, { "code": null, "e": 460, "s": 294, "text": "Input: N = 5, Ranges = {{1, 5}, {1, 5}, {1, 5}, {2, 3}, {2, 3}} Output: 5 Explanation: Job 1 on day 1, Job 4 on day 2, Job 5 on day 3, Job 2 on day 4, Job 3 on day 5" }, { "code": null, "e": 542, "s": 460, "text": "Input: N=6, Ranges = {{1, 3}, {1, 3}, {2, 3}, {2, 3}, {1, 4}, {2, 5}} Output: 5 " }, { "code": null, "e": 658, "s": 544, "text": "Approach: The above problem can be solved using a Priority Queue. Follow the steps below to solve the problems: " }, { "code": null, "e": 713, "s": 658, "text": "Find the minimum and maximum day in the range of jobs." }, { "code": null, "e": 761, "s": 713, "text": "Sort all jobs in increasing order of start day." }, { "code": null, "e": 897, "s": 761, "text": "Iterate from the minimum to maximum day, and for every ith day, select the job having least end day which can be completed on that day." }, { "code": null, "e": 1188, "s": 897, "text": "In order to perform the above step, maintain a Min Heap, and on every ith day, insert the jobs that can be completed on that day, into the Min Heap sorted by end day. If any job can completed on the ith day, consider the one with the lowest end day and increase the count of jobs completed." }, { "code": null, "e": 1272, "s": 1188, "text": "Repeat this process for all the days and finally print the count of jobs completed." }, { "code": null, "e": 1323, "s": 1272, "text": "Below is an implementation of the above approach: " }, { "code": null, "e": 1327, "s": 1323, "text": "C++" }, { "code": null, "e": 1332, "s": 1327, "text": "Java" }, { "code": null, "e": 1340, "s": 1332, "text": "Python3" }, { "code": null, "e": 1343, "s": 1340, "text": "C#" }, { "code": null, "e": 1354, "s": 1343, "text": "Javascript" }, { "code": "// C++ Program to implement the// above approach #include <bits/stdc++.h>using namespace std; // Function to find maximum// number of jobsint find_maximum_jobs( int N, vector<pair<int, int> > ranges){ // Min Heap priority_queue<int, vector<int>, greater<int> > queue; // Sort ranges by start day sort(ranges.begin(), ranges.end()); // Stores the minimum and maximum // day in the ranges int min_day = ranges[0].first; int max_day = 0; for (int i = 0; i < N; i++) max_day = max(max_day, ranges[i].second); int index = 0, count_jobs = 0; // Iterating from min_day to max_day for (int i = min_day; i <= max_day; i++) { // Insert the end day of the jobs // which can be completed on // i-th day in a priority queue while (index < ranges.size() && ranges[index].first <= i) { queue.push(ranges[index].second); index++; } // Pop all jobs whose end day // is less than current day while (!queue.empty() && queue.top() < i) queue.pop(); // If queue is empty, no job // can be completed on // the i-th day if (queue.empty()) continue; // Increment the count of // jobs completed count_jobs++; // Pop the job with // least end day queue.pop(); } // Return the jobs // on the last day return count_jobs;} // Driver Codeint main(){ int N = 5; vector<pair<int, int> > ranges; ranges.push_back({ 1, 5 }); ranges.push_back({ 1, 5 }); ranges.push_back({ 1, 5 }); ranges.push_back({ 2, 3 }); ranges.push_back({ 2, 3 }); cout << find_maximum_jobs(N, ranges);}", "e": 3146, "s": 1354, "text": null }, { "code": "// Java Program to implement the// above approachimport java.io.*;import java.util.*; class GFG { // Function to find maximum // number of jobs static int find_maximum_jobs(int N, ArrayList<ArrayList<Integer>> ranges) { // Min Heap ArrayList<Integer> queue = new ArrayList<Integer>(); // Sort ranges by start day Collections.sort(ranges, new Comparator<ArrayList<Integer>>() { @Override public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) { return o1.get(0).compareTo(o2.get(0)); } }); // Stores the minimum and maximum // day in the ranges int min_day = ranges.get(0).get(0); int max_day = 0; for (int i = 0; i < N; i++) max_day = Math.max(max_day, ranges.get(i).get(1)); int index = 0, count_jobs = 0; // Iterating from min_day to max_day for (int i = min_day; i <= max_day; i++) { // Insert the end day of the jobs // which can be completed on // i-th day in a priority queue while (index < ranges.size() && ranges.get(index).get(0) <= i) { queue.add(ranges.get(index).get(1)); index++; } Collections.sort(queue); // Pop all jobs whose end day // is less than current day while (queue.size() > 0 && queue.get(0) < i) queue.remove(0); // If queue is empty, no job // can be completed on // the i-th day if (queue.size() == 0) continue; // Increment the count of // jobs completed count_jobs++; // Pop the job with // least end day queue.remove(0); } // Return the jobs // on the last day return count_jobs; } // Driver code public static void main (String[] args) { int N = 5; ArrayList<ArrayList<Integer>> ranges = new ArrayList<ArrayList<Integer>>(); ranges.add(new ArrayList<Integer>(Arrays.asList(1, 5))); ranges.add(new ArrayList<Integer>(Arrays.asList(1, 5))); ranges.add(new ArrayList<Integer>(Arrays.asList(1, 5))); ranges.add(new ArrayList<Integer>(Arrays.asList(2, 3))); ranges.add(new ArrayList<Integer>(Arrays.asList(2, 3))); System.out.println(find_maximum_jobs(N, ranges)); }}// This code is contributed by avanitrachhadiya2155", "e": 5370, "s": 3146, "text": null }, { "code": "# Python3 Program to implement the# above approach # Function to find maximum# number of jobsdef find_maximum_jobs(N, ranges) : # Min Heap queue = [] # Sort ranges by start day ranges.sort() # Stores the minimum and maximum # day in the ranges min_day = ranges[0][0] max_day = 0 for i in range(N) : max_day = max(max_day, ranges[i][1]) index, count_jobs = 0, 0 # Iterating from min_day to max_day for i in range(min_day, max_day + 1) : # Insert the end day of the jobs # which can be completed on # i-th day in a priority queue while (index < len(ranges) and ranges[index][0] <= i) : queue.append(ranges[index][1]) index += 1 queue.sort() # Pop all jobs whose end day # is less than current day while (len(queue) > 0 and queue[0] < i) : queue.pop(0) # If queue is empty, no job # can be completed on # the i-th day if (len(queue) == 0) : continue # Increment the count of # jobs completed count_jobs += 1 # Pop the job with # least end day queue.pop(0) # Return the jobs # on the last day return count_jobs # Driver codeN = 5ranges = []ranges.append((1, 5))ranges.append((1, 5))ranges.append((1, 5))ranges.append((2, 3))ranges.append((2, 3)) print(find_maximum_jobs(N, ranges)) # This code is contributed by divyeshrabadiya07.", "e": 6833, "s": 5370, "text": null }, { "code": "// C# Program to implement the// above approachusing System;using System.Collections.Generic;class GFG { // Function to find maximum // number of jobs static int find_maximum_jobs(int N, List<Tuple<int, int>> ranges) { // Min Heap List<int> queue = new List<int>(); // Sort ranges by start day ranges.Sort(); // Stores the minimum and maximum // day in the ranges int min_day = ranges[0].Item1; int max_day = 0; for (int i = 0; i < N; i++) max_day = Math.Max(max_day, ranges[i].Item2); int index = 0, count_jobs = 0; // Iterating from min_day to max_day for (int i = min_day; i <= max_day; i++) { // Insert the end day of the jobs // which can be completed on // i-th day in a priority queue while (index < ranges.Count && ranges[index].Item1 <= i) { queue.Add(ranges[index].Item2); index++; } queue.Sort(); // Pop all jobs whose end day // is less than current day while (queue.Count > 0 && queue[0] < i) queue.RemoveAt(0); // If queue is empty, no job // can be completed on // the i-th day if (queue.Count == 0) continue; // Increment the count of // jobs completed count_jobs++; // Pop the job with // least end day queue.RemoveAt(0); } // Return the jobs // on the last day return count_jobs; } // Driver code static void Main() { int N = 5; List<Tuple<int, int>> ranges = new List<Tuple<int, int>>(); ranges.Add(new Tuple<int,int>(1, 5)); ranges.Add(new Tuple<int,int>(1, 5)); ranges.Add(new Tuple<int,int>(1, 5)); ranges.Add(new Tuple<int,int>(2, 3)); ranges.Add(new Tuple<int,int>(2, 3)); Console.Write(find_maximum_jobs(N, ranges)); }} // This code is contributed by divyesh072019.", "e": 8653, "s": 6833, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find maximum// number of jobsfunction find_maximum_jobs(N, ranges){ // Min Heap let queue = [] // Sort ranges by start day ranges.sort() // Stores the minimum && maximum // day in the ranges let min_day = ranges[0][0] let max_day = 0 for(let i = 0;i<N ; i++){ max_day = Math.max(max_day, ranges[i][1]) } let index = 0, count_jobs = 0 // Iterating from min_day to max_day for(let i = min_day;i< max_day + 1;i++) { // Insert the end day of the jobs // which can be completed on // i-th day in a priority queue while (index < ranges.length && ranges[index][0] <= i){ queue.push(ranges[index][1]) index += 1 } queue.sort() // Pop all jobs whose end day // is less than current day while (queue.length > 0 && queue[0] < i) queue.shift() // If queue is empty, no job // can be completed on // the i-th day if (queue.length == 0) continue // Increment the count of // jobs completed count_jobs += 1 // Pop the job with // least end day queue.shift() } // Return the jobs // on the last day return count_jobs} // Driver codelet N = 5let ranges = []ranges.push([1, 5])ranges.push([1, 5])ranges.push([1, 5])ranges.push([2, 3])ranges.push([2, 3]) document.write(find_maximum_jobs(N, ranges)) // This code is contributed by shinjanpatra </script>", "e": 10200, "s": 8653, "text": null }, { "code": null, "e": 10202, "s": 10200, "text": "5" }, { "code": null, "e": 10344, "s": 10204, "text": "Time Complexity: O(Xlog(N)), where X is the difference between maximum and minimum day and N is the number of jobs. Auxiliary Space: O(N2) " }, { "code": null, "e": 10358, "s": 10344, "text": "divyesh072019" }, { "code": null, "e": 10376, "s": 10358, "text": "divyeshrabadiya07" }, { "code": null, "e": 10397, "s": 10376, "text": "avanitrachhadiya2155" }, { "code": null, "e": 10411, "s": 10397, "text": "sumitgumber28" }, { "code": null, "e": 10424, "s": 10411, "text": "shinjanpatra" }, { "code": null, "e": 10443, "s": 10424, "text": "cpp-priority-queue" }, { "code": null, "e": 10465, "s": 10443, "text": "interview-preparation" }, { "code": null, "e": 10474, "s": 10465, "text": "min-heap" }, { "code": null, "e": 10485, "s": 10474, "text": "Algorithms" }, { "code": null, "e": 10509, "s": 10485, "text": "Competitive Programming" }, { "code": null, "e": 10516, "s": 10509, "text": "Greedy" }, { "code": null, "e": 10521, "s": 10516, "text": "Heap" }, { "code": null, "e": 10529, "s": 10521, "text": "Sorting" }, { "code": null, "e": 10536, "s": 10529, "text": "Greedy" }, { "code": null, "e": 10544, "s": 10536, "text": "Sorting" }, { "code": null, "e": 10549, "s": 10544, "text": "Heap" }, { "code": null, "e": 10560, "s": 10549, "text": "Algorithms" } ]
Object Class in Java
03 Jan, 2022 Object class is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of Object and if extends another class then it is indirectly derived. Therefore the Object class methods are available to all Java classes. Hence Object class acts as a root of inheritance hierarchy in any Java Program. There are methods in the Object class: 1. toString(): The toString() provides a String representation of an object and is used to convert an object to String. The default toString() method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash code of the object. In other words, it is defined as: // Default behavior of toString() is to print class name, then // @, then unsigned hexadecimal representation of the hash code // of the object public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } It is always recommended to override the toString() method to get our own String representation of Object. For more on override of toString() method refer – Overriding toString() in Java Note: Whenever we try to print any Object reference, then internally toString() method is called. Student s = new Student(); // Below two statements are equivalent System.out.println(s); System.out.println(s.toString()); 2. hashCode(): For every object, JVM generates a unique number which is hashcode. It returns distinct integers for distinct objects. A common misconception about this method is that the hashCode() method returns the address of the object, which is not correct. It converts the internal address of the object to an integer by using an algorithm. The hashCode() method is native because in Java it is impossible to find the address of an object, so it uses native languages like C/C++ to find the address of the object. Use of hashCode() method: It returns a hash value that is used to search objects in a collection. JVM(Java Virtual Machine) uses the hashcode method while saving objects into hashing-related data structures like HashSet, HashMap, Hashtable, etc. The main advantage of saving objects based on hash code is that searching becomes easy. Note: Override of hashCode() method needs to be done such that for every object we generate a unique number. For example, for a Student class, we can return the roll no. of a student from the hashCode() method as it is unique. Java // Java program to demonstrate working of// hashCode() and toString() public class Student { static int last_roll = 100; int roll_no; // Constructor Student() { roll_no = last_roll; last_roll++; } // Overriding hashCode() @Override public int hashCode() { return roll_no; } // Driver code public static void main(String args[]) { Student s = new Student(); // Below two statements are equivalent System.out.println(s); System.out.println(s.toString()); }} Output : Student@64 Student@64 Note that 4*160 + 6*161 = 100 3. equals(Object obj): It compares the given object to “this” object (the object on which the method is called). It gives a generic way to compare objects for equality. It is recommended to override the equals(Object obj) method to get our own equality condition on Objects. For more on override of equals(Object obj) method refer – Overriding equals method in Java Note: It is generally necessary to override the hashCode() method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes. 4. getClass(): It returns the class object of “this” object and is used to get the actual runtime class of the object. It can also be used to get metadata of this class. The returned Class object is the object that is locked by static synchronized methods of the represented class. As it is final so we don’t override it. Java // Java program to demonstrate working of getClass() public class Test { public static void main(String[] args) { Object obj = new String("GeeksForGeeks"); Class c = obj.getClass(); System.out.println("Class of Object obj is : " + c.getName()); }} Output: Class of Object obj is : java.lang.String Note: After loading a .class file, JVM will create an object of the type java.lang.Class in the Heap area. We can use this class object to get Class level information. It is widely used in Reflection 5. finalize() method: This method is called just before an object is garbage collected. It is called the Garbage Collector on an object when the garbage collector determines that there are no more references to the object. We should override finalize() method to dispose of system resources, perform clean-up activities and minimize memory leaks. For example, before destroying Servlet objects web container, always called finalize method to perform clean-up activities of the session. Note: The finalize method is called just once on an object even though that object is eligible for garbage collection multiple times. Java // Java program to demonstrate working of finalize() public class Test { public static void main(String[] args) { Test t = new Test(); System.out.println(t.hashCode()); t = null; // calling garbage collector System.gc(); System.out.println("end"); } @Override protected void finalize() { System.out.println("finalize method called"); }} Output: 366712642 finalize method called end 6. clone(): It returns a new object that is exactly the same as this object. For clone() method refer Clone(). The remaining three methods wait(), notify() notifyAll() are related to Concurrency. Refer to Inter-thread Communication in Java for details. JobAlert HariCharanReddy_V adnanirshad158 nishkarshgandhi Java-Class and Object Java Java-Class and Object Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jan, 2022" }, { "code": null, "e": 472, "s": 54, "text": "Object class is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of Object and if extends another class then it is indirectly derived. Therefore the Object class methods are available to all Java classes. Hence Object class acts as a root of inheritance hierarchy in any Java Program." }, { "code": null, "e": 512, "s": 472, "text": "There are methods in the Object class: " }, { "code": null, "e": 905, "s": 512, "text": "1. toString(): The toString() provides a String representation of an object and is used to convert an object to String. The default toString() method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash code of the object. In other words, it is defined as:" }, { "code": null, "e": 1152, "s": 905, "text": "// Default behavior of toString() is to print class name, then\n// @, then unsigned hexadecimal representation of the hash code\n// of the object\n\npublic String toString()\n{\n return getClass().getName() + \"@\" + Integer.toHexString(hashCode());\n}" }, { "code": null, "e": 1340, "s": 1152, "text": "It is always recommended to override the toString() method to get our own String representation of Object. For more on override of toString() method refer – Overriding toString() in Java " }, { "code": null, "e": 1438, "s": 1340, "text": "Note: Whenever we try to print any Object reference, then internally toString() method is called." }, { "code": null, "e": 1562, "s": 1438, "text": "Student s = new Student();\n\n// Below two statements are equivalent\nSystem.out.println(s);\nSystem.out.println(s.toString());" }, { "code": null, "e": 2080, "s": 1562, "text": "2. hashCode(): For every object, JVM generates a unique number which is hashcode. It returns distinct integers for distinct objects. A common misconception about this method is that the hashCode() method returns the address of the object, which is not correct. It converts the internal address of the object to an integer by using an algorithm. The hashCode() method is native because in Java it is impossible to find the address of an object, so it uses native languages like C/C++ to find the address of the object." }, { "code": null, "e": 2415, "s": 2080, "text": "Use of hashCode() method: It returns a hash value that is used to search objects in a collection. JVM(Java Virtual Machine) uses the hashcode method while saving objects into hashing-related data structures like HashSet, HashMap, Hashtable, etc. The main advantage of saving objects based on hash code is that searching becomes easy. " }, { "code": null, "e": 2643, "s": 2415, "text": "Note: Override of hashCode() method needs to be done such that for every object we generate a unique number. For example, for a Student class, we can return the roll no. of a student from the hashCode() method as it is unique. " }, { "code": null, "e": 2648, "s": 2643, "text": "Java" }, { "code": "// Java program to demonstrate working of// hashCode() and toString() public class Student { static int last_roll = 100; int roll_no; // Constructor Student() { roll_no = last_roll; last_roll++; } // Overriding hashCode() @Override public int hashCode() { return roll_no; } // Driver code public static void main(String args[]) { Student s = new Student(); // Below two statements are equivalent System.out.println(s); System.out.println(s.toString()); }}", "e": 3186, "s": 2648, "text": null }, { "code": null, "e": 3195, "s": 3186, "text": "Output :" }, { "code": null, "e": 3217, "s": 3195, "text": "Student@64\nStudent@64" }, { "code": null, "e": 3248, "s": 3217, "text": "Note that 4*160 + 6*161 = 100 " }, { "code": null, "e": 3614, "s": 3248, "text": "3. equals(Object obj): It compares the given object to “this” object (the object on which the method is called). It gives a generic way to compare objects for equality. It is recommended to override the equals(Object obj) method to get our own equality condition on Objects. For more on override of equals(Object obj) method refer – Overriding equals method in Java" }, { "code": null, "e": 3841, "s": 3614, "text": "Note: It is generally necessary to override the hashCode() method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes. " }, { "code": null, "e": 4163, "s": 3841, "text": "4. getClass(): It returns the class object of “this” object and is used to get the actual runtime class of the object. It can also be used to get metadata of this class. The returned Class object is the object that is locked by static synchronized methods of the represented class. As it is final so we don’t override it." }, { "code": null, "e": 4168, "s": 4163, "text": "Java" }, { "code": "// Java program to demonstrate working of getClass() public class Test { public static void main(String[] args) { Object obj = new String(\"GeeksForGeeks\"); Class c = obj.getClass(); System.out.println(\"Class of Object obj is : \" + c.getName()); }}", "e": 4472, "s": 4168, "text": null }, { "code": null, "e": 4481, "s": 4472, "text": "Output: " }, { "code": null, "e": 4523, "s": 4481, "text": "Class of Object obj is : java.lang.String" }, { "code": null, "e": 4724, "s": 4523, "text": "Note: After loading a .class file, JVM will create an object of the type java.lang.Class in the Heap area. We can use this class object to get Class level information. It is widely used in Reflection " }, { "code": null, "e": 5211, "s": 4724, "text": "5. finalize() method: This method is called just before an object is garbage collected. It is called the Garbage Collector on an object when the garbage collector determines that there are no more references to the object. We should override finalize() method to dispose of system resources, perform clean-up activities and minimize memory leaks. For example, before destroying Servlet objects web container, always called finalize method to perform clean-up activities of the session. " }, { "code": null, "e": 5346, "s": 5211, "text": "Note: The finalize method is called just once on an object even though that object is eligible for garbage collection multiple times. " }, { "code": null, "e": 5351, "s": 5346, "text": "Java" }, { "code": "// Java program to demonstrate working of finalize() public class Test { public static void main(String[] args) { Test t = new Test(); System.out.println(t.hashCode()); t = null; // calling garbage collector System.gc(); System.out.println(\"end\"); } @Override protected void finalize() { System.out.println(\"finalize method called\"); }}", "e": 5759, "s": 5351, "text": null }, { "code": null, "e": 5768, "s": 5759, "text": "Output: " }, { "code": null, "e": 5805, "s": 5768, "text": "366712642\nfinalize method called\nend" }, { "code": null, "e": 5916, "s": 5805, "text": "6. clone(): It returns a new object that is exactly the same as this object. For clone() method refer Clone()." }, { "code": null, "e": 6059, "s": 5916, "text": "The remaining three methods wait(), notify() notifyAll() are related to Concurrency. Refer to Inter-thread Communication in Java for details." }, { "code": null, "e": 6068, "s": 6059, "text": "JobAlert" }, { "code": null, "e": 6086, "s": 6068, "text": "HariCharanReddy_V" }, { "code": null, "e": 6101, "s": 6086, "text": "adnanirshad158" }, { "code": null, "e": 6117, "s": 6101, "text": "nishkarshgandhi" }, { "code": null, "e": 6139, "s": 6117, "text": "Java-Class and Object" }, { "code": null, "e": 6144, "s": 6139, "text": "Java" }, { "code": null, "e": 6166, "s": 6144, "text": "Java-Class and Object" }, { "code": null, "e": 6171, "s": 6166, "text": "Java" }, { "code": null, "e": 6269, "s": 6171, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6320, "s": 6269, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 6351, "s": 6320, "text": "How to iterate any Map in Java" }, { "code": null, "e": 6381, "s": 6351, "text": "HashMap in Java with Examples" }, { "code": null, "e": 6396, "s": 6381, "text": "Stream In Java" }, { "code": null, "e": 6414, "s": 6396, "text": "ArrayList in Java" }, { "code": null, "e": 6434, "s": 6414, "text": "Collections in Java" }, { "code": null, "e": 6458, "s": 6434, "text": "Singleton Class in Java" }, { "code": null, "e": 6490, "s": 6458, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 6502, "s": 6490, "text": "Set in Java" } ]
Referencing Subclass objects with Subclass vs Superclass reference
29 Mar, 2017 Prerequisite : InheritanceIn Java, all non-static methods are based on the runtime type of the underlying object rather than the type of the reference that points to that object. Therefore, it doesn’t matter which type you use in the declaration of the object, the behavior will be the same. How to Refer a subclass object There are two approaches to refer a subclass object. Both have some advantages/disadvantages over the other. The declaration affect is seen on methods that are visible at compile-time. First approach (Referencing using Superclass reference): A reference variable of a superclass can be used to a refer any subclass object derived from that superclass. If the methods are present in SuperClass, but overridden by SubClass, it will be the overridden method that will be executed.Second approach (Referencing using subclass reference) : A subclass reference can be used to refer its object. First approach (Referencing using Superclass reference): A reference variable of a superclass can be used to a refer any subclass object derived from that superclass. If the methods are present in SuperClass, but overridden by SubClass, it will be the overridden method that will be executed. Second approach (Referencing using subclass reference) : A subclass reference can be used to refer its object. Consider an example explaining both the approaches. // Java program to illustrate // referring to a subclass// base classclass Bicycle { // the Bicycle class has two fields public int gear; public int speed; // the Bicycle class has one constructor public Bicycle(int gear, int speed) { this.gear = gear; this.speed = speed; } // the Bicycle class has three methods public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } // toString() method to print info of Bicycle public String toString() { return("No of gears are "+gear +"\n" + "speed of bicycle is "+speed); } } // derived classclass MountainBike extends Bicycle { // the MountainBike subclass adds one more field public int seatHeight; // the MountainBike subclass has one constructor public MountainBike(int gear,int speed, int startHeight) { // invoking base-class(Bicycle) constructor super(gear, speed); seatHeight = startHeight; } // the MountainBike subclass adds one more method public void setHeight(int newValue) { seatHeight = newValue; } // overriding toString() method // of Bicycle to print more info @Override public String toString() { return (super.toString()+ "\nseat height is "+seatHeight); } } // driver classpublic class Test { public static void main(String args[]) { // using superclass reference // first approach Bicycle mb2 = new MountainBike(4, 200, 20); // using subclass reference( ) // second approach MountainBike mb1 = new MountainBike(3, 100, 25); System.out.println("seat height of first bicycle is " + mb1.seatHeight); // In case of overridden methods // always subclass // method will be executed System.out.println(mb1.toString()); System.out.println(mb2.toString()); /* The following statement is invalid because Bicycle does not define a seatHeight. // System.out.println("seat height of second bicycle is " + mb2.seatHeight); */ /* The following statement is invalid because Bicycle does not define setHeight() method. mb2.setHeight(21);*/ }} Output: seat height of first bicycle is 25 No of gears are 3 speed of bicycle is 100 seat height is 25 No of gears are 4 speed of bicycle is 200 seat height is 20 Explanation of above program : The object of MountainBike class is created which is referred by using subclass reference ‘mb1’. Using this reference we will have access both parts(methods and variables) of the object defined by the superclass or subclass. See below image for clear understanding.MountainBike mb1 = new MountainBike(3, 100, 25); MountainBike mb1 = new MountainBike(3, 100, 25); Now we again create object of MountainBike class but this time it is referred by using superclass Bicycle reference ‘mb2’. Using this reference we will have access only to those parts(methods and variables) of the object defined by the superclass.Bicycle mb2 = new MountainBike(4, 200, 20); Bicycle mb2 = new MountainBike(4, 200, 20); Since the reference ‘mb1’ have access to field ‘seatHeight’, so we print this on console.System.out.println("seat height of first bicycle is " + mb1.seatHeight); System.out.println("seat height of first bicycle is " + mb1.seatHeight); If there are methods present in super class, but overridden by subclass, and if object of subclass is created, then whatever reference we use(either subclass or superclass), it will always be the overridden method in subclass that will be executed. So below two statements will call toString() method of MountainBike class.System.out.println(mb1.toString()); System.out.println(mb2.toString()); System.out.println(mb1.toString()); System.out.println(mb2.toString()); Since the reference made by ‘mb2’ is of type Bicycle , so we will get compile time error in below statement.System.out.println("seat height of second bicycle is " + mb2.seatHeight); System.out.println("seat height of second bicycle is " + mb2.seatHeight); Again the reference made by ‘mb2’ is of type Bicycle , so we will get compile time error in below statement.mb2.setHeight(21); Use of type castingIn above example, we have seen that by using reference ‘mb2’ of type Bicycle, we are unable to call subclass specific methods or access subclass fields. This problem can be solved using type casting in java. For example, we can declare another reference say ‘mb3’ of type MountainBike and assign it to ‘mb2’ using typecasting.// declaring MountainBike reference MountainBike mb3; // assigning mb3 to mb2 using typecasting. mb3 = (MountainBike)mb2; So, now the following statements are valid.System.out.println("seat height of second bicycle is " + mb3.seatHeight); mb3.setHeight(21); mb2.setHeight(21); Use of type casting In above example, we have seen that by using reference ‘mb2’ of type Bicycle, we are unable to call subclass specific methods or access subclass fields. This problem can be solved using type casting in java. For example, we can declare another reference say ‘mb3’ of type MountainBike and assign it to ‘mb2’ using typecasting. // declaring MountainBike reference MountainBike mb3; // assigning mb3 to mb2 using typecasting. mb3 = (MountainBike)mb2; So, now the following statements are valid. System.out.println("seat height of second bicycle is " + mb3.seatHeight); mb3.setHeight(21); When to go for first approach (Referencing using superclass reference) If we don’t know exact runtime type of an object, then we should use this approach. For example, consider an ArrayList containing different objects at different indices. Now when we try to get elements of arraylist using ArrayList.get(int index) method then we must use Object reference, as in this case, we don’t know exact runtime type of an object. For example : /* Java program to illustrate referring to a subclassusing superclass reference variable */import java.util.ArrayList; public class Test { public static void main(String args[]) { ArrayList al = new ArrayList(2); // adding String object to al al.add(new String("GeeksForGeeks")); // adding Integer object to al al.add(new Integer(5)); // getting all elements using Object reference for (Object object : al) { System.out.println(object); } }} Output: GeeksForGeeks 5 Advantage : We can use superclass reference to hold any subclass object derived from it. Disadvantage : By using superclass reference, we will have access only to those parts(methods and variables) of the object defined by the superclass. For example, we can not access seatHeight variable or call setHeight(int newValue) method using Bicycle reference in above first example. This is because they are defined in subclass not in the superclass. When to go for second approach (Referencing using subclass reference) If we know the exact runtime type of an object, then this approach is better. Using this approach, we can also call a particular object specific methods. For example : /* Java program to illustrate referring to a subclassusing subclass reference variable */import java.util.ArrayList; public class Test { public static void main(String args[]) { ArrayList al = new ArrayList(2); // adding String objects to al al.add(new String("GeeksForGeeks")); al.add(new String("for java archives")); // getting elements using String reference String str1 = (String)al.get(0); String str2 = (String)al.get(1); System.out.println(str1); System.out.println(str2); // using String class specific method System.out.println(str1.length()); System.out.println(str2.substring(4,8)); }} Output: GeeksForGeeks for java archives 13 java Advantage : By using subclass reference, we will have access to both parts(methods and variables) of the object defined by the superclass or subclass. For example, we can call setHeight(int newValue) method or speedUp(int increment) method using MountainBike reference in above first example. Disadvantage : We can use subclass reference to hold only for that particular subclass objects only. Reference: StackOverflow This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. java-inheritance Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Mar, 2017" }, { "code": null, "e": 344, "s": 52, "text": "Prerequisite : InheritanceIn Java, all non-static methods are based on the runtime type of the underlying object rather than the type of the reference that points to that object. Therefore, it doesn’t matter which type you use in the declaration of the object, the behavior will be the same." }, { "code": null, "e": 375, "s": 344, "text": "How to Refer a subclass object" }, { "code": null, "e": 560, "s": 375, "text": "There are two approaches to refer a subclass object. Both have some advantages/disadvantages over the other. The declaration affect is seen on methods that are visible at compile-time." }, { "code": null, "e": 963, "s": 560, "text": "First approach (Referencing using Superclass reference): A reference variable of a superclass can be used to a refer any subclass object derived from that superclass. If the methods are present in SuperClass, but overridden by SubClass, it will be the overridden method that will be executed.Second approach (Referencing using subclass reference) : A subclass reference can be used to refer its object." }, { "code": null, "e": 1256, "s": 963, "text": "First approach (Referencing using Superclass reference): A reference variable of a superclass can be used to a refer any subclass object derived from that superclass. If the methods are present in SuperClass, but overridden by SubClass, it will be the overridden method that will be executed." }, { "code": null, "e": 1367, "s": 1256, "text": "Second approach (Referencing using subclass reference) : A subclass reference can be used to refer its object." }, { "code": null, "e": 1419, "s": 1367, "text": "Consider an example explaining both the approaches." }, { "code": "// Java program to illustrate // referring to a subclass// base classclass Bicycle { // the Bicycle class has two fields public int gear; public int speed; // the Bicycle class has one constructor public Bicycle(int gear, int speed) { this.gear = gear; this.speed = speed; } // the Bicycle class has three methods public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } // toString() method to print info of Bicycle public String toString() { return(\"No of gears are \"+gear +\"\\n\" + \"speed of bicycle is \"+speed); } } // derived classclass MountainBike extends Bicycle { // the MountainBike subclass adds one more field public int seatHeight; // the MountainBike subclass has one constructor public MountainBike(int gear,int speed, int startHeight) { // invoking base-class(Bicycle) constructor super(gear, speed); seatHeight = startHeight; } // the MountainBike subclass adds one more method public void setHeight(int newValue) { seatHeight = newValue; } // overriding toString() method // of Bicycle to print more info @Override public String toString() { return (super.toString()+ \"\\nseat height is \"+seatHeight); } } // driver classpublic class Test { public static void main(String args[]) { // using superclass reference // first approach Bicycle mb2 = new MountainBike(4, 200, 20); // using subclass reference( ) // second approach MountainBike mb1 = new MountainBike(3, 100, 25); System.out.println(\"seat height of first bicycle is \" + mb1.seatHeight); // In case of overridden methods // always subclass // method will be executed System.out.println(mb1.toString()); System.out.println(mb2.toString()); /* The following statement is invalid because Bicycle does not define a seatHeight. // System.out.println(\"seat height of second bicycle is \" + mb2.seatHeight); */ /* The following statement is invalid because Bicycle does not define setHeight() method. mb2.setHeight(21);*/ }}", "e": 3985, "s": 1419, "text": null }, { "code": null, "e": 3993, "s": 3985, "text": "Output:" }, { "code": null, "e": 4149, "s": 3993, "text": "seat height of first bicycle is 25\nNo of gears are 3\nspeed of bicycle is 100\nseat height is 25\nNo of gears are 4\nspeed of bicycle is 200\nseat height is 20\n" }, { "code": null, "e": 4180, "s": 4149, "text": "Explanation of above program :" }, { "code": null, "e": 4495, "s": 4180, "text": "The object of MountainBike class is created which is referred by using subclass reference ‘mb1’. Using this reference we will have access both parts(methods and variables) of the object defined by the superclass or subclass. See below image for clear understanding.MountainBike mb1 = new MountainBike(3, 100, 25);\n" }, { "code": null, "e": 4545, "s": 4495, "text": "MountainBike mb1 = new MountainBike(3, 100, 25);\n" }, { "code": null, "e": 4837, "s": 4545, "text": "Now we again create object of MountainBike class but this time it is referred by using superclass Bicycle reference ‘mb2’. Using this reference we will have access only to those parts(methods and variables) of the object defined by the superclass.Bicycle mb2 = new MountainBike(4, 200, 20);\n" }, { "code": null, "e": 4882, "s": 4837, "text": "Bicycle mb2 = new MountainBike(4, 200, 20);\n" }, { "code": null, "e": 5046, "s": 4882, "text": "Since the reference ‘mb1’ have access to field ‘seatHeight’, so we print this on console.System.out.println(\"seat height of first bicycle is \" + mb1.seatHeight);\n" }, { "code": null, "e": 5121, "s": 5046, "text": "System.out.println(\"seat height of first bicycle is \" + mb1.seatHeight);\n" }, { "code": null, "e": 5517, "s": 5121, "text": "If there are methods present in super class, but overridden by subclass, and if object of subclass is created, then whatever reference we use(either subclass or superclass), it will always be the overridden method in subclass that will be executed. So below two statements will call toString() method of MountainBike class.System.out.println(mb1.toString());\nSystem.out.println(mb2.toString());\n" }, { "code": null, "e": 5590, "s": 5517, "text": "System.out.println(mb1.toString());\nSystem.out.println(mb2.toString());\n" }, { "code": null, "e": 5774, "s": 5590, "text": "Since the reference made by ‘mb2’ is of type Bicycle , so we will get compile time error in below statement.System.out.println(\"seat height of second bicycle is \" + mb2.seatHeight);\n" }, { "code": null, "e": 5850, "s": 5774, "text": "System.out.println(\"seat height of second bicycle is \" + mb2.seatHeight);\n" }, { "code": null, "e": 6584, "s": 5850, "text": "Again the reference made by ‘mb2’ is of type Bicycle , so we will get compile time error in below statement.mb2.setHeight(21);\nUse of type castingIn above example, we have seen that by using reference ‘mb2’ of type Bicycle, we are unable to call subclass specific methods or access subclass fields. This problem can be solved using type casting in java. For example, we can declare another reference say ‘mb3’ of type MountainBike and assign it to ‘mb2’ using typecasting.// declaring MountainBike reference\nMountainBike mb3;\n\n// assigning mb3 to mb2 using typecasting.\n mb3 = (MountainBike)mb2;\nSo, now the following statements are valid.System.out.println(\"seat height of second bicycle is \" + mb3.seatHeight);\nmb3.setHeight(21);\n" }, { "code": null, "e": 6604, "s": 6584, "text": "mb2.setHeight(21);\n" }, { "code": null, "e": 6624, "s": 6604, "text": "Use of type casting" }, { "code": null, "e": 6951, "s": 6624, "text": "In above example, we have seen that by using reference ‘mb2’ of type Bicycle, we are unable to call subclass specific methods or access subclass fields. This problem can be solved using type casting in java. For example, we can declare another reference say ‘mb3’ of type MountainBike and assign it to ‘mb2’ using typecasting." }, { "code": null, "e": 7076, "s": 6951, "text": "// declaring MountainBike reference\nMountainBike mb3;\n\n// assigning mb3 to mb2 using typecasting.\n mb3 = (MountainBike)mb2;\n" }, { "code": null, "e": 7120, "s": 7076, "text": "So, now the following statements are valid." }, { "code": null, "e": 7215, "s": 7120, "text": "System.out.println(\"seat height of second bicycle is \" + mb3.seatHeight);\nmb3.setHeight(21);\n" }, { "code": null, "e": 7286, "s": 7215, "text": "When to go for first approach (Referencing using superclass reference)" }, { "code": null, "e": 7652, "s": 7286, "text": "If we don’t know exact runtime type of an object, then we should use this approach. For example, consider an ArrayList containing different objects at different indices. Now when we try to get elements of arraylist using ArrayList.get(int index) method then we must use Object reference, as in this case, we don’t know exact runtime type of an object. For example :" }, { "code": "/* Java program to illustrate referring to a subclassusing superclass reference variable */import java.util.ArrayList; public class Test { public static void main(String args[]) { ArrayList al = new ArrayList(2); // adding String object to al al.add(new String(\"GeeksForGeeks\")); // adding Integer object to al al.add(new Integer(5)); // getting all elements using Object reference for (Object object : al) { System.out.println(object); } }}", "e": 8261, "s": 7652, "text": null }, { "code": null, "e": 8269, "s": 8261, "text": "Output:" }, { "code": null, "e": 8286, "s": 8269, "text": "GeeksForGeeks\n5\n" }, { "code": null, "e": 8375, "s": 8286, "text": "Advantage : We can use superclass reference to hold any subclass object derived from it." }, { "code": null, "e": 8731, "s": 8375, "text": "Disadvantage : By using superclass reference, we will have access only to those parts(methods and variables) of the object defined by the superclass. For example, we can not access seatHeight variable or call setHeight(int newValue) method using Bicycle reference in above first example. This is because they are defined in subclass not in the superclass." }, { "code": null, "e": 8801, "s": 8731, "text": "When to go for second approach (Referencing using subclass reference)" }, { "code": null, "e": 8969, "s": 8801, "text": "If we know the exact runtime type of an object, then this approach is better. Using this approach, we can also call a particular object specific methods. For example :" }, { "code": "/* Java program to illustrate referring to a subclassusing subclass reference variable */import java.util.ArrayList; public class Test { public static void main(String args[]) { ArrayList al = new ArrayList(2); // adding String objects to al al.add(new String(\"GeeksForGeeks\")); al.add(new String(\"for java archives\")); // getting elements using String reference String str1 = (String)al.get(0); String str2 = (String)al.get(1); System.out.println(str1); System.out.println(str2); // using String class specific method System.out.println(str1.length()); System.out.println(str2.substring(4,8)); }}", "e": 9783, "s": 8969, "text": null }, { "code": null, "e": 9791, "s": 9783, "text": "Output:" }, { "code": null, "e": 9832, "s": 9791, "text": "GeeksForGeeks\nfor java archives\n13\njava\n" }, { "code": null, "e": 10125, "s": 9832, "text": "Advantage : By using subclass reference, we will have access to both parts(methods and variables) of the object defined by the superclass or subclass. For example, we can call setHeight(int newValue) method or speedUp(int increment) method using MountainBike reference in above first example." }, { "code": null, "e": 10226, "s": 10125, "text": "Disadvantage : We can use subclass reference to hold only for that particular subclass objects only." }, { "code": null, "e": 10251, "s": 10226, "text": "Reference: StackOverflow" }, { "code": null, "e": 10553, "s": 10251, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 10678, "s": 10553, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 10695, "s": 10678, "text": "java-inheritance" }, { "code": null, "e": 10700, "s": 10695, "text": "Java" }, { "code": null, "e": 10705, "s": 10700, "text": "Java" }, { "code": null, "e": 10803, "s": 10705, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10834, "s": 10803, "text": "How to iterate any Map in Java" }, { "code": null, "e": 10853, "s": 10834, "text": "Interfaces in Java" }, { "code": null, "e": 10883, "s": 10853, "text": "HashMap in Java with Examples" }, { "code": null, "e": 10898, "s": 10883, "text": "Stream In Java" }, { "code": null, "e": 10916, "s": 10898, "text": "ArrayList in Java" }, { "code": null, "e": 10936, "s": 10916, "text": "Collections in Java" }, { "code": null, "e": 10960, "s": 10936, "text": "Singleton Class in Java" }, { "code": null, "e": 10992, "s": 10960, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 11004, "s": 10992, "text": "Set in Java" } ]
Minimum increment/decrement to make array non-Increasing
26 May, 2022 Given an array a, your task is to convert it into a non-increasing form such that we can either increment or decrement the array value by 1 in the minimum changes possible. Examples : Input : a[] = {3, 1, 2, 1}Output : 1Explanation : We can convert the array into 3 1 1 1 by changing 3rd element of array i.e. 2 into its previous integer 1 in one step hence only one step is required. Input : a[] = {3, 1, 5, 1}Output : 4Explanation : We need to decrease 5 to 1 to make array sorted in non-increasing order. Input : a[] = {1, 5, 5, 5}Output : 4Explanation : We need to increase 1 to 5. Brute-Force approach: We consider both possibilities for every element and find a minimum of two possibilities. Efficient Approach Method 1 (Using Min-Heap):Calculate the sum of absolute differences between the final array elements and the current array elements. Thus, the answer will be the sum of the difference between the ith element and the smallest element that occurred until then. For this, we can maintain a min-heap to find the smallest element encountered till then. In the min-priority queue, we will put the elements, and new elements are compared with the previous minimum. If the new minimum is found we will update it, this is done because each of the next elements which are coming should be smaller than the current minimum element found till now. Here, we calculate the difference so that we can get how much we have to change the current number so that it will be equal or less than previous numbers encountered. Lastly, the sum of all these differences will be our answer as this will give the final value up to which we have to change the elements. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // CPP code to count the change required to// convert the array into non-increasing array#include <bits/stdc++.h>using namespace std; int DecreasingArray(int a[], int n){ int sum = 0, dif = 0; // min heap priority_queue<int, vector<int>, greater<int> > pq; // Here in the loop we will check that whether // the top of priority queue is less than // the upcoming array element. If yes then // we calculate the difference. After that // we will remove that element and push the // current element in queue. And the sum // is incremented by the value of difference for (int i = 0; i < n; i++) { if (!pq.empty() && pq.top() < a[i]) { dif = a[i] - pq.top(); sum += dif; // Removing that minimum element // which does follow the decreasing // property and replacing it with a[i] // to maintain the condition pq.pop(); pq.push(a[i]); } // Push the current element as well pq.push(a[i]); } return sum;} // Driver Codeint main(){ int a[] = { 3, 1, 2, 1 }; int n = sizeof(a) / sizeof(a[0]); cout << DecreasingArray(a, n); return 0;} // Java code to count the change required to// convert the array into non-increasing arrayimport java.util.PriorityQueue; class GFG{ public static int DecreasingArray(int a[], int n) { int sum = 0, dif = 0; PriorityQueue<Integer> pq = new PriorityQueue<>(); // Here in the loop we will // check that whether the upcoming // element of array is less than top // of priority queue. If yes then we // calculate the difference. After // that we will remove that element // and push the current element in // queue. And the sum is incremented // by the value of difference for (int i = 0; i < n; i++) { if (!pq.isEmpty() && pq.element() < a[i]) { dif = a[i] - pq.element(); sum += dif; pq.remove(); pq.add(a[i]); } pq.add(a[i]); } return sum; } // Driver Code public static void main(String[] args) { int[] a = {3, 1, 2, 1}; int n = a.length; System.out.println(DecreasingArray(a, n)); }} // This Code is contributed by sanjeev2552 # Python3 code to count the change required to# convert the array into non-increasing arrayfrom queue import PriorityQueue def DecreasingArray(a, n): ss, dif = (0,0) # min heap pq = PriorityQueue() # Here in the loop we will # check that whether the upcoming # element of array is less than top # of priority queue. If yes then we # calculate the difference. After # that we will remove that element # and push the current element in # queue. And the sum is incremented # by the value of difference for i in range(n): tmp = 0 if not pq.empty(): tmp = pq.get() pq.put(tmp) if not pq.empty() and tmp < a[i]: dif = a[i] - tmp ss += dif pq.get() pq.put(a[i]) pq.put(a[i]) return ss # Driver code if __name__=="__main__": a = [ 3, 1, 2, 1 ] n = len(a) print(DecreasingArray(a, n)) # This code is contributed by rutvik_56 // C# code to count the change required to// convert the array into non-increasing arrayusing System;using System.Collections.Generic;class GFG{ static int DecreasingArray(int[] a, int n) { int sum = 0, dif = 0; // min heap List<int> pq = new List<int>(); // Here in the loop we will // check that whether the upcoming // element of array is less than top // of priority queue. If yes then we // calculate the difference. After // that we will remove that element // and push the current element in // queue. And the sum is incremented // by the value of difference for (int i = 0; i < n; i++) { if (pq.Count > 0 && pq[0] < a[i]) { dif = a[i] - pq[0]; sum += dif; pq.RemoveAt(0); pq.Add(a[i]); } pq.Add(a[i]); pq.Sort(); } return sum; } // Driver code static void Main() { int[] a = { 3, 1, 2, 1 }; int n = a.Length; Console.Write(DecreasingArray(a, n)); }} // This code is contributed by divyeshrabadiya07. <script> // Javascript code to count the change required to// convert the array into non-increasing arrayfunction DecreasingArray(a, n){ var sum = 0, dif = 0; // min heap var pq = []; // Here in the loop we will // check that whether the upcoming // element of array is less than top // of priority queue. If yes then we // calculate the difference. After // that we will remove that element // and push the current element in // queue. And the sum is incremented // by the value of difference for (var i = 0; i < n; i++) { if (pq.length != 0 && pq[pq.length - 1] < a[i]) { dif = a[i] - pq[pq.length - 1]; sum += dif; pq.pop(); pq.push(a[i]); } pq.push(a[i]); pq.sort((a, b)=>b - a); } return sum;} // Driver Codevar a = [3, 1, 2, 1];var n = a.length;document.write(DecreasingArray(a, n)); // This code is contributed by rrrtnx.</script> 1 Time Complexity: O(n log(n)) Auxiliary Space: O(n) Method 2: Using Max-HeapTraverse in reverse order in the given array and keep maintaining the increasing property. If any element is smaller than the maximum of existing elements till that index then, we need to make some decrement operation on that maximum element so that it also follows the increasing property from back traversal and add the required operation in the answer. C++ Java // CPP code to count the change required to// convert the array into non-increasing array#include <bits/stdc++.h>using namespace std; int DecreasingArray(int arr[], int n){ int ans = 0; // max heap priority_queue<int> pq; // Here in the loop we will // check that whether the top // of priority queue is greater than the upcoming array // element. If yes then we calculate the difference. // After that we will remove that element and push the // current element in queue. And the sum is incremented // by the value of difference for (int i = n - 1; i >= 0; i--) { if (!pq.empty() and pq.top() > arr[i]) { ans += abs(arr[i] - pq.top()); pq.pop(); pq.push(arr[i]); } pq.push(arr[i]); } return ans;} // Driver Codeint main(){ int a[] = { 3, 1, 2, 1 }; int n = sizeof(a) / sizeof(a[0]); cout << DecreasingArray(a, n); return 0;} // Java code to count the change required to// convert the array into non-increasing arrayimport java.io.*;import java.util.*; class GFG { public static int DecreasingArray(int arr[], int n) { int ans = 0; // max heap PriorityQueue<Integer> pq = new PriorityQueue<>( Collections.reverseOrder()); // Here in the loop we will // check that whether the top // of priority queue is greater than the upcoming // array element. If yes then we calculate the // difference. After that we will remove that // element and push the current element in queue. // And the sum is incremented by the value of // difference for (int i = n - 1; i >= 0; i--) { if (!pq.isEmpty() && pq.peek() > arr[i]) { ans += Math.abs(arr[i] - pq.peek()); pq.poll(); pq.add(arr[i]); } pq.add(arr[i]); } return ans; } // Driver Code public static void main(String[] args) { int a[] = { 3, 1, 2, 1 }; int n = a.length; System.out.print(DecreasingArray(a, n)); }} // This code is contributed by Rohit Pradhan Output: 1 Time Complexity: O(n log(n)) Auxiliary Space: O(n) Also see : Convert to strictly increasing array with minimum changes. sanskar27jain sanjeev2552 rutvik_56 karthikgrsoft divyeshrabadiya07 rrrtnx ritobroto11 ishankhandelwals rohit768 cpp-priority-queue priority-queue Algorithms Greedy Heap Greedy Heap priority-queue Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 May, 2022" }, { "code": null, "e": 225, "s": 52, "text": "Given an array a, your task is to convert it into a non-increasing form such that we can either increment or decrement the array value by 1 in the minimum changes possible." }, { "code": null, "e": 237, "s": 225, "text": "Examples : " }, { "code": null, "e": 439, "s": 237, "text": "Input : a[] = {3, 1, 2, 1}Output : 1Explanation : We can convert the array into 3 1 1 1 by changing 3rd element of array i.e. 2 into its previous integer 1 in one step hence only one step is required." }, { "code": null, "e": 562, "s": 439, "text": "Input : a[] = {3, 1, 5, 1}Output : 4Explanation : We need to decrease 5 to 1 to make array sorted in non-increasing order." }, { "code": null, "e": 640, "s": 562, "text": "Input : a[] = {1, 5, 5, 5}Output : 4Explanation : We need to increase 1 to 5." }, { "code": null, "e": 753, "s": 640, "text": "Brute-Force approach: We consider both possibilities for every element and find a minimum of two possibilities. " }, { "code": null, "e": 1713, "s": 753, "text": "Efficient Approach Method 1 (Using Min-Heap):Calculate the sum of absolute differences between the final array elements and the current array elements. Thus, the answer will be the sum of the difference between the ith element and the smallest element that occurred until then. For this, we can maintain a min-heap to find the smallest element encountered till then. In the min-priority queue, we will put the elements, and new elements are compared with the previous minimum. If the new minimum is found we will update it, this is done because each of the next elements which are coming should be smaller than the current minimum element found till now. Here, we calculate the difference so that we can get how much we have to change the current number so that it will be equal or less than previous numbers encountered. Lastly, the sum of all these differences will be our answer as this will give the final value up to which we have to change the elements." }, { "code": null, "e": 1764, "s": 1713, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1770, "s": 1764, "text": "C++14" }, { "code": null, "e": 1775, "s": 1770, "text": "Java" }, { "code": null, "e": 1783, "s": 1775, "text": "Python3" }, { "code": null, "e": 1786, "s": 1783, "text": "C#" }, { "code": null, "e": 1797, "s": 1786, "text": "Javascript" }, { "code": "// CPP code to count the change required to// convert the array into non-increasing array#include <bits/stdc++.h>using namespace std; int DecreasingArray(int a[], int n){ int sum = 0, dif = 0; // min heap priority_queue<int, vector<int>, greater<int> > pq; // Here in the loop we will check that whether // the top of priority queue is less than // the upcoming array element. If yes then // we calculate the difference. After that // we will remove that element and push the // current element in queue. And the sum // is incremented by the value of difference for (int i = 0; i < n; i++) { if (!pq.empty() && pq.top() < a[i]) { dif = a[i] - pq.top(); sum += dif; // Removing that minimum element // which does follow the decreasing // property and replacing it with a[i] // to maintain the condition pq.pop(); pq.push(a[i]); } // Push the current element as well pq.push(a[i]); } return sum;} // Driver Codeint main(){ int a[] = { 3, 1, 2, 1 }; int n = sizeof(a) / sizeof(a[0]); cout << DecreasingArray(a, n); return 0;}", "e": 2994, "s": 1797, "text": null }, { "code": "// Java code to count the change required to// convert the array into non-increasing arrayimport java.util.PriorityQueue; class GFG{ public static int DecreasingArray(int a[], int n) { int sum = 0, dif = 0; PriorityQueue<Integer> pq = new PriorityQueue<>(); // Here in the loop we will // check that whether the upcoming // element of array is less than top // of priority queue. If yes then we // calculate the difference. After // that we will remove that element // and push the current element in // queue. And the sum is incremented // by the value of difference for (int i = 0; i < n; i++) { if (!pq.isEmpty() && pq.element() < a[i]) { dif = a[i] - pq.element(); sum += dif; pq.remove(); pq.add(a[i]); } pq.add(a[i]); } return sum; } // Driver Code public static void main(String[] args) { int[] a = {3, 1, 2, 1}; int n = a.length; System.out.println(DecreasingArray(a, n)); }} // This Code is contributed by sanjeev2552", "e": 4197, "s": 2994, "text": null }, { "code": "# Python3 code to count the change required to# convert the array into non-increasing arrayfrom queue import PriorityQueue def DecreasingArray(a, n): ss, dif = (0,0) # min heap pq = PriorityQueue() # Here in the loop we will # check that whether the upcoming # element of array is less than top # of priority queue. If yes then we # calculate the difference. After # that we will remove that element # and push the current element in # queue. And the sum is incremented # by the value of difference for i in range(n): tmp = 0 if not pq.empty(): tmp = pq.get() pq.put(tmp) if not pq.empty() and tmp < a[i]: dif = a[i] - tmp ss += dif pq.get() pq.put(a[i]) pq.put(a[i]) return ss # Driver code if __name__==\"__main__\": a = [ 3, 1, 2, 1 ] n = len(a) print(DecreasingArray(a, n)) # This code is contributed by rutvik_56", "e": 5220, "s": 4197, "text": null }, { "code": "// C# code to count the change required to// convert the array into non-increasing arrayusing System;using System.Collections.Generic;class GFG{ static int DecreasingArray(int[] a, int n) { int sum = 0, dif = 0; // min heap List<int> pq = new List<int>(); // Here in the loop we will // check that whether the upcoming // element of array is less than top // of priority queue. If yes then we // calculate the difference. After // that we will remove that element // and push the current element in // queue. And the sum is incremented // by the value of difference for (int i = 0; i < n; i++) { if (pq.Count > 0 && pq[0] < a[i]) { dif = a[i] - pq[0]; sum += dif; pq.RemoveAt(0); pq.Add(a[i]); } pq.Add(a[i]); pq.Sort(); } return sum; } // Driver code static void Main() { int[] a = { 3, 1, 2, 1 }; int n = a.Length; Console.Write(DecreasingArray(a, n)); }} // This code is contributed by divyeshrabadiya07.", "e": 6402, "s": 5220, "text": null }, { "code": "<script> // Javascript code to count the change required to// convert the array into non-increasing arrayfunction DecreasingArray(a, n){ var sum = 0, dif = 0; // min heap var pq = []; // Here in the loop we will // check that whether the upcoming // element of array is less than top // of priority queue. If yes then we // calculate the difference. After // that we will remove that element // and push the current element in // queue. And the sum is incremented // by the value of difference for (var i = 0; i < n; i++) { if (pq.length != 0 && pq[pq.length - 1] < a[i]) { dif = a[i] - pq[pq.length - 1]; sum += dif; pq.pop(); pq.push(a[i]); } pq.push(a[i]); pq.sort((a, b)=>b - a); } return sum;} // Driver Codevar a = [3, 1, 2, 1];var n = a.length;document.write(DecreasingArray(a, n)); // This code is contributed by rrrtnx.</script>", "e": 7363, "s": 6402, "text": null }, { "code": null, "e": 7365, "s": 7363, "text": "1" }, { "code": null, "e": 7416, "s": 7365, "text": "Time Complexity: O(n log(n)) Auxiliary Space: O(n)" }, { "code": null, "e": 7796, "s": 7416, "text": "Method 2: Using Max-HeapTraverse in reverse order in the given array and keep maintaining the increasing property. If any element is smaller than the maximum of existing elements till that index then, we need to make some decrement operation on that maximum element so that it also follows the increasing property from back traversal and add the required operation in the answer." }, { "code": null, "e": 7800, "s": 7796, "text": "C++" }, { "code": null, "e": 7805, "s": 7800, "text": "Java" }, { "code": "// CPP code to count the change required to// convert the array into non-increasing array#include <bits/stdc++.h>using namespace std; int DecreasingArray(int arr[], int n){ int ans = 0; // max heap priority_queue<int> pq; // Here in the loop we will // check that whether the top // of priority queue is greater than the upcoming array // element. If yes then we calculate the difference. // After that we will remove that element and push the // current element in queue. And the sum is incremented // by the value of difference for (int i = n - 1; i >= 0; i--) { if (!pq.empty() and pq.top() > arr[i]) { ans += abs(arr[i] - pq.top()); pq.pop(); pq.push(arr[i]); } pq.push(arr[i]); } return ans;} // Driver Codeint main(){ int a[] = { 3, 1, 2, 1 }; int n = sizeof(a) / sizeof(a[0]); cout << DecreasingArray(a, n); return 0;}", "e": 8741, "s": 7805, "text": null }, { "code": "// Java code to count the change required to// convert the array into non-increasing arrayimport java.io.*;import java.util.*; class GFG { public static int DecreasingArray(int arr[], int n) { int ans = 0; // max heap PriorityQueue<Integer> pq = new PriorityQueue<>( Collections.reverseOrder()); // Here in the loop we will // check that whether the top // of priority queue is greater than the upcoming // array element. If yes then we calculate the // difference. After that we will remove that // element and push the current element in queue. // And the sum is incremented by the value of // difference for (int i = n - 1; i >= 0; i--) { if (!pq.isEmpty() && pq.peek() > arr[i]) { ans += Math.abs(arr[i] - pq.peek()); pq.poll(); pq.add(arr[i]); } pq.add(arr[i]); } return ans; } // Driver Code public static void main(String[] args) { int a[] = { 3, 1, 2, 1 }; int n = a.length; System.out.print(DecreasingArray(a, n)); }} // This code is contributed by Rohit Pradhan", "e": 9947, "s": 8741, "text": null }, { "code": null, "e": 9955, "s": 9947, "text": "Output:" }, { "code": null, "e": 9957, "s": 9955, "text": "1" }, { "code": null, "e": 10008, "s": 9957, "text": "Time Complexity: O(n log(n)) Auxiliary Space: O(n)" }, { "code": null, "e": 10079, "s": 10008, "text": "Also see : Convert to strictly increasing array with minimum changes. " }, { "code": null, "e": 10093, "s": 10079, "text": "sanskar27jain" }, { "code": null, "e": 10105, "s": 10093, "text": "sanjeev2552" }, { "code": null, "e": 10115, "s": 10105, "text": "rutvik_56" }, { "code": null, "e": 10129, "s": 10115, "text": "karthikgrsoft" }, { "code": null, "e": 10147, "s": 10129, "text": "divyeshrabadiya07" }, { "code": null, "e": 10154, "s": 10147, "text": "rrrtnx" }, { "code": null, "e": 10166, "s": 10154, "text": "ritobroto11" }, { "code": null, "e": 10183, "s": 10166, "text": "ishankhandelwals" }, { "code": null, "e": 10192, "s": 10183, "text": "rohit768" }, { "code": null, "e": 10211, "s": 10192, "text": "cpp-priority-queue" }, { "code": null, "e": 10226, "s": 10211, "text": "priority-queue" }, { "code": null, "e": 10237, "s": 10226, "text": "Algorithms" }, { "code": null, "e": 10244, "s": 10237, "text": "Greedy" }, { "code": null, "e": 10249, "s": 10244, "text": "Heap" }, { "code": null, "e": 10256, "s": 10249, "text": "Greedy" }, { "code": null, "e": 10261, "s": 10256, "text": "Heap" }, { "code": null, "e": 10276, "s": 10261, "text": "priority-queue" }, { "code": null, "e": 10287, "s": 10276, "text": "Algorithms" } ]
How to create animated banner links using HTML and CSS?
09 Jul, 2021 Links are one of the most important parts of any component that is used in website making. Almost every component had some form of links in it. A common example is a menu/nav-bar. All we see is some button like home, about, etc. but under the hood they all are links. Sometimes there comes a situation where you don’t want to wrap the link inside a button. So, in that case, the banner link can be really useful. It has a really simplistic look and animation which makes it easy to design and implement and it also looks great because of it’s a simple and clean design. Approach: The approach is to give some border around the link and then elongating the whole link on mouse-hover. Now, there are many ways to implement the same but we will be manipulating letter-spacing to achieve our goal. HTML Code: In this section, we have created a simple link which take us to no-where. You should add your desired link in the href attribute of the tag. html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Animated Link</title></head> <body> <a href="#">GeeksforGeeks</a> </body></html> CSS Code: For CSS, follow the below given steps. Step 1: Apply some basic styling link font-size, font-family etc. Step 2: Apply top and bottom border of any color and width. Step 3: Use hover selector and increase the letter spacing. Note: The letter spacing should be increased atleast 2-3 times of the original value of letter-spacing. CSS a{ position: absolute; top: 50%; left:50%; padding: 15px 0; font-size: 24px; font-family: Arial, Helvetica, sans-serif; text-decoration: none; color: #262626; border-top: 2px solid #262626; border-bottom: 2px solid #262626; letter-spacing: 2px; transition: .5s; } a:hover{ letter-spacing: 10px; } Complete Code: It is the combination of the above two sections of code. html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Animated Link</title> <style> a{ position: absolute; top: 50%; left:50%; padding: 15px 0; font-size: 24px; font-family: Arial, Helvetica, sans-serif; text-decoration: none; color: #262626; border-top: 2px solid #262626; border-bottom: 2px solid #262626; letter-spacing: 2px; transition: .5s; } a:hover{ letter-spacing: 10px; } </style> </head> <body> <a href="#">GeeksforGeeks</a> </body></html> Output: sagartomar9927 CSS-Advanced CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jul, 2021" }, { "code": null, "e": 976, "s": 28, "text": "Links are one of the most important parts of any component that is used in website making. Almost every component had some form of links in it. A common example is a menu/nav-bar. All we see is some button like home, about, etc. but under the hood they all are links. Sometimes there comes a situation where you don’t want to wrap the link inside a button. So, in that case, the banner link can be really useful. It has a really simplistic look and animation which makes it easy to design and implement and it also looks great because of it’s a simple and clean design. Approach: The approach is to give some border around the link and then elongating the whole link on mouse-hover. Now, there are many ways to implement the same but we will be manipulating letter-spacing to achieve our goal. HTML Code: In this section, we have created a simple link which take us to no-where. You should add your desired link in the href attribute of the tag. " }, { "code": null, "e": 981, "s": 976, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Animated Link</title></head> <body> <a href=\"#\">GeeksforGeeks</a> </body></html>", "e": 1230, "s": 981, "text": null }, { "code": null, "e": 1281, "s": 1230, "text": "CSS Code: For CSS, follow the below given steps. " }, { "code": null, "e": 1347, "s": 1281, "text": "Step 1: Apply some basic styling link font-size, font-family etc." }, { "code": null, "e": 1407, "s": 1347, "text": "Step 2: Apply top and bottom border of any color and width." }, { "code": null, "e": 1467, "s": 1407, "text": "Step 3: Use hover selector and increase the letter spacing." }, { "code": null, "e": 1573, "s": 1467, "text": "Note: The letter spacing should be increased atleast 2-3 times of the original value of letter-spacing. " }, { "code": null, "e": 1577, "s": 1573, "text": "CSS" }, { "code": "a{ position: absolute; top: 50%; left:50%; padding: 15px 0; font-size: 24px; font-family: Arial, Helvetica, sans-serif; text-decoration: none; color: #262626; border-top: 2px solid #262626; border-bottom: 2px solid #262626; letter-spacing: 2px; transition: .5s; } a:hover{ letter-spacing: 10px; }", "e": 1981, "s": 1577, "text": null }, { "code": null, "e": 2055, "s": 1981, "text": "Complete Code: It is the combination of the above two sections of code. " }, { "code": null, "e": 2060, "s": 2055, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Animated Link</title> <style> a{ position: absolute; top: 50%; left:50%; padding: 15px 0; font-size: 24px; font-family: Arial, Helvetica, sans-serif; text-decoration: none; color: #262626; border-top: 2px solid #262626; border-bottom: 2px solid #262626; letter-spacing: 2px; transition: .5s; } a:hover{ letter-spacing: 10px; } </style> </head> <body> <a href=\"#\">GeeksforGeeks</a> </body></html>", "e": 2743, "s": 2060, "text": null }, { "code": null, "e": 2753, "s": 2743, "text": "Output: " }, { "code": null, "e": 2770, "s": 2755, "text": "sagartomar9927" }, { "code": null, "e": 2783, "s": 2770, "text": "CSS-Advanced" }, { "code": null, "e": 2787, "s": 2783, "text": "CSS" }, { "code": null, "e": 2792, "s": 2787, "text": "HTML" }, { "code": null, "e": 2809, "s": 2792, "text": "Web Technologies" }, { "code": null, "e": 2814, "s": 2809, "text": "HTML" }, { "code": null, "e": 2912, "s": 2814, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2951, "s": 2912, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2990, "s": 2951, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3029, "s": 2990, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3066, "s": 3029, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 3095, "s": 3066, "text": "Form validation using jQuery" }, { "code": null, "e": 3119, "s": 3095, "text": "REST API (Introduction)" }, { "code": null, "e": 3172, "s": 3119, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3232, "s": 3172, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 3293, "s": 3232, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
13 Jun, 2022 We have discussed Kruskal’s algorithm for Minimum Spanning Tree. Like Kruskal’s algorithm, Prim’s algorithm is also a Greedy algorithm. It starts with an empty spanning tree. The idea is to maintain two sets of vertices. The first set contains the vertices already included in the MST, the other set contains the vertices not yet included. At every step, it considers all the edges that connect the two sets and picks the minimum weight edge from these edges. After picking the edge, it moves the other endpoint of the edge to the set containing MST. A group of edges that connects two sets of vertices in a graph is called cut in graph theory. So, at every step of Prim’s algorithm, we find a cut (of two sets, one contains the vertices already included in MST and the other contains the rest of the vertices), pick the minimum weight edge from the cut, and include this vertex to MST Set (the set that contains already included vertices). How does Prim’s Algorithm Work? The idea behind Prim’s algorithm is simple, a spanning tree means all vertices must be connected. So the two disjoint subsets (discussed above) of vertices must be connected to make a Spanning Tree. And they must be connected with the minimum weight edge to make it a Minimum Spanning Tree. Algorithm 1) Create a set mstSet that keeps track of vertices already included in MST. 2) Assign a key value to all vertices in the input graph. Initialize all key values as INFINITE. Assign the key value as 0 for the first vertex so that it is picked first. 3) While mstSet doesn’t include all vertices ....a) Pick a vertex u which is not there in mstSet and has a minimum key value. ....b) Include u to mstSet. ....c) Update key value of all adjacent vertices of u. To update the key values, iterate through all adjacent vertices. For every adjacent vertex v, if the weight of edge u-v is less than the previous key value of v, update the key value as the weight of u-vThe idea of using key values is to pick the minimum weight edge from cut. The key values are used only for vertices that are not yet included in MST, the key value for these vertices indicates the minimum weight edges connecting them to the set of vertices included in MST. Let us understand with the following example: The set mstSet is initially empty and keys assigned to vertices are {0, INF, INF, INF, INF, INF, INF, INF} where INF indicates infinite. Now pick the vertex with the minimum key value. The vertex 0 is picked, include it in mstSet. So mstSet becomes {0}. After including to mstSet, update key values of adjacent vertices. Adjacent vertices of 0 are 1 and 7. The key values of 1 and 7 are updated as 4 and 8. Following subgraph shows vertices and their key values, only the vertices with finite key values are shown. The vertices included in MST are shown in green color. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Pick the vertex with minimum key value and not already included in MST (not in mstSET). The vertex 1 is picked and added to mstSet. So mstSet now becomes {0, 1}. Update the key values of adjacent vertices of 1. The key value of vertex 2 becomes 8. Pick the vertex with minimum key value and not already included in MST (not in mstSET). We can either pick vertex 7 or vertex 2, let vertex 7 is picked. So mstSet now becomes {0, 1, 7}. Update the key values of adjacent vertices of 7. The key value of vertex 6 and 8 becomes finite (1 and 7 respectively). Pick the vertex with minimum key value and not already included in MST (not in mstSET). Vertex 6 is picked. So mstSet now becomes {0, 1, 7, 6}. Update the key values of adjacent vertices of 6. The key value of vertex 5 and 8 are updated. We repeat the above steps until mstSet includes all vertices of given graph. Finally, we get the following graph. How to implement the above algorithm? We use a boolean array mstSet[] to represent the set of vertices included in MST. If a value mstSet[v] is true, then vertex v is included in MST, otherwise not. Array key[] is used to store key values of all vertices. Another array parent[] to store indexes of parent nodes in MST. The parent array is the output array which is used to show the constructed MST. C++ C Java Python3 C# Javascript // A C++ program for Prim's Minimum// Spanning Tree (MST) algorithm. The program is// for adjacency matrix representation of the graph#include <bits/stdc++.h>using namespace std; // Number of vertices in the graph#define V 5 // A utility function to find the vertex with// minimum key value, from the set of vertices// not yet included in MSTint minKey(int key[], bool mstSet[]){ // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (mstSet[v] == false && key[v] < min) min = key[v], min_index = v; return min_index;} // A utility function to print the// constructed MST stored in parent[]void printMST(int parent[], int graph[V][V]){ cout<<"Edge \tWeight\n"; for (int i = 1; i < V; i++) cout<<parent[i]<<" - "<<i<<" \t"<<graph[i][parent[i]]<<" \n";} // Function to construct and print MST for// a graph represented using adjacency// matrix representationvoid primMST(int graph[V][V]){ // Array to store constructed MST int parent[V]; // Key values used to pick minimum weight edge in cut int key[V]; // To represent set of vertices included in MST bool mstSet[V]; // Initialize all keys as INFINITE for (int i = 0; i < V; i++) key[i] = INT_MAX, mstSet[i] = false; // Always include first 1st vertex in MST. // Make key 0 so that this vertex is picked as first vertex. key[0] = 0; parent[0] = -1; // First node is always root of MST // The MST will have V vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum key vertex from the // set of vertices not yet included in MST int u = minKey(key, mstSet); // Add the picked vertex to the MST Set mstSet[u] = true; // Update key value and parent index of // the adjacent vertices of the picked vertex. // Consider only those vertices which are not // yet included in MST for (int v = 0; v < V; v++) // graph[u][v] is non zero only for adjacent vertices of m // mstSet[v] is false for vertices not yet included in MST // Update the key only if graph[u][v] is smaller than key[v] if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) parent[v] = u, key[v] = graph[u][v]; } // print the constructed MST printMST(parent, graph);} // Driver codeint main(){ /* Let us create the following graph 2 3 (0)--(1)--(2) | / \ | 6| 8/ \5 |7 | / \ | (3)-------(4) 9 */ int graph[V][V] = { { 0, 2, 0, 6, 0 }, { 2, 0, 3, 8, 5 }, { 0, 3, 0, 0, 7 }, { 6, 8, 0, 0, 9 }, { 0, 5, 7, 9, 0 } }; // Print the solution primMST(graph); return 0;} // This code is contributed by rathbhupendra // A C program for Prim's Minimum// Spanning Tree (MST) algorithm. The program is// for adjacency matrix representation of the graph#include <limits.h>#include <stdbool.h>#include <stdio.h>// Number of vertices in the graph#define V 5 // A utility function to find the vertex with// minimum key value, from the set of vertices// not yet included in MSTint minKey(int key[], bool mstSet[]){ // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (mstSet[v] == false && key[v] < min) min = key[v], min_index = v; return min_index;} // A utility function to print the// constructed MST stored in parent[]int printMST(int parent[], int graph[V][V]){ printf("Edge \tWeight\n"); for (int i = 1; i < V; i++) printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);} // Function to construct and print MST for// a graph represented using adjacency// matrix representationvoid primMST(int graph[V][V]){ // Array to store constructed MST int parent[V]; // Key values used to pick minimum weight edge in cut int key[V]; // To represent set of vertices included in MST bool mstSet[V]; // Initialize all keys as INFINITE for (int i = 0; i < V; i++) key[i] = INT_MAX, mstSet[i] = false; // Always include first 1st vertex in MST. // Make key 0 so that this vertex is picked as first vertex. key[0] = 0; parent[0] = -1; // First node is always root of MST // The MST will have V vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum key vertex from the // set of vertices not yet included in MST int u = minKey(key, mstSet); // Add the picked vertex to the MST Set mstSet[u] = true; // Update key value and parent index of // the adjacent vertices of the picked vertex. // Consider only those vertices which are not // yet included in MST for (int v = 0; v < V; v++) // graph[u][v] is non zero only for adjacent vertices of m // mstSet[v] is false for vertices not yet included in MST // Update the key only if graph[u][v] is smaller than key[v] if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) parent[v] = u, key[v] = graph[u][v]; } // print the constructed MST printMST(parent, graph);} // driver program to test above functionint main(){ /* Let us create the following graph 2 3 (0)--(1)--(2) | / \ | 6| 8/ \5 |7 | / \ | (3)-------(4) 9 */ int graph[V][V] = { { 0, 2, 0, 6, 0 }, { 2, 0, 3, 8, 5 }, { 0, 3, 0, 0, 7 }, { 6, 8, 0, 0, 9 }, { 0, 5, 7, 9, 0 } }; // Print the solution primMST(graph); return 0;} // A Java program for Prim's Minimum Spanning Tree (MST) algorithm.// The program is for adjacency matrix representation of the graph import java.util.*;import java.lang.*;import java.io.*; class MST { // Number of vertices in the graph private static final int V = 5; // A utility function to find the vertex with minimum key // value, from the set of vertices not yet included in MST int minKey(int key[], Boolean mstSet[]) { // Initialize min value int min = Integer.MAX_VALUE, min_index = -1; for (int v = 0; v < V; v++) if (mstSet[v] == false && key[v] < min) { min = key[v]; min_index = v; } return min_index; } // A utility function to print the constructed MST stored in // parent[] void printMST(int parent[], int graph[][]) { System.out.println("Edge \tWeight"); for (int i = 1; i < V; i++) System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]); } // Function to construct and print MST for a graph represented // using adjacency matrix representation void primMST(int graph[][]) { // Array to store constructed MST int parent[] = new int[V]; // Key values used to pick minimum weight edge in cut int key[] = new int[V]; // To represent set of vertices included in MST Boolean mstSet[] = new Boolean[V]; // Initialize all keys as INFINITE for (int i = 0; i < V; i++) { key[i] = Integer.MAX_VALUE; mstSet[i] = false; } // Always include first 1st vertex in MST. key[0] = 0; // Make key 0 so that this vertex is // picked as first vertex parent[0] = -1; // First node is always root of MST // The MST will have V vertices for (int count = 0; count < V - 1; count++) { // Pick thd minimum key vertex from the set of vertices // not yet included in MST int u = minKey(key, mstSet); // Add the picked vertex to the MST Set mstSet[u] = true; // Update key value and parent index of the adjacent // vertices of the picked vertex. Consider only those // vertices which are not yet included in MST for (int v = 0; v < V; v++) // graph[u][v] is non zero only for adjacent vertices of m // mstSet[v] is false for vertices not yet included in MST // Update the key only if graph[u][v] is smaller than key[v] if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) { parent[v] = u; key[v] = graph[u][v]; } } // print the constructed MST printMST(parent, graph); } public static void main(String[] args) { /* Let us create the following graph 2 3 (0)--(1)--(2) | / \ | 6| 8/ \5 |7 | / \ | (3)-------(4) 9 */ MST t = new MST(); int graph[][] = new int[][] { { 0, 2, 0, 6, 0 }, { 2, 0, 3, 8, 5 }, { 0, 3, 0, 0, 7 }, { 6, 8, 0, 0, 9 }, { 0, 5, 7, 9, 0 } }; // Print the solution t.primMST(graph); }}// This code is contributed by Aakash Hasija # A Python program for Prim's Minimum Spanning Tree (MST) algorithm.# The program is for adjacency matrix representation of the graph import sys # Library for INT_MAX class Graph(): def __init__(self, vertices): self.V = vertices self.graph = [[0 for column in range(vertices)] for row in range(vertices)] # A utility function to print the constructed MST stored in parent[] def printMST(self, parent): print ("Edge \tWeight") for i in range(1, self.V): print (parent[i], "-", i, "\t", self.graph[i][parent[i]]) # A utility function to find the vertex with # minimum distance value, from the set of vertices # not yet included in shortest path tree def minKey(self, key, mstSet): # Initialize min value min = sys.maxsize for v in range(self.V): if key[v] < min and mstSet[v] == False: min = key[v] min_index = v return min_index # Function to construct and print MST for a graph # represented using adjacency matrix representation def primMST(self): # Key values used to pick minimum weight edge in cut key = [sys.maxsize] * self.V parent = [None] * self.V # Array to store constructed MST # Make key 0 so that this vertex is picked as first vertex key[0] = 0 mstSet = [False] * self.V parent[0] = -1 # First node is always the root of for cout in range(self.V): # Pick the minimum distance vertex from # the set of vertices not yet processed. # u is always equal to src in first iteration u = self.minKey(key, mstSet) # Put the minimum distance vertex in # the shortest path tree mstSet[u] = True # Update dist value of the adjacent vertices # of the picked vertex only if the current # distance is greater than new distance and # the vertex in not in the shortest path tree for v in range(self.V): # graph[u][v] is non zero only for adjacent vertices of m # mstSet[v] is false for vertices not yet included in MST # Update the key only if graph[u][v] is smaller than key[v] if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]: key[v] = self.graph[u][v] parent[v] = u self.printMST(parent) g = Graph(5)g.graph = [ [0, 2, 0, 6, 0], [2, 0, 3, 8, 5], [0, 3, 0, 0, 7], [6, 8, 0, 0, 9], [0, 5, 7, 9, 0]] g.primMST(); # Contributed by Divyanshu Mehta // A C# program for Prim's Minimum// Spanning Tree (MST) algorithm.// The program is for adjacency// matrix representation of the graphusing System;class MST { // Number of vertices in the graph static int V = 5; // A utility function to find // the vertex with minimum key // value, from the set of vertices // not yet included in MST static int minKey(int[] key, bool[] mstSet) { // Initialize min value int min = int.MaxValue, min_index = -1; for (int v = 0; v < V; v++) if (mstSet[v] == false && key[v] < min) { min = key[v]; min_index = v; } return min_index; } // A utility function to print // the constructed MST stored in // parent[] static void printMST(int[] parent, int[, ] graph) { Console.WriteLine("Edge \tWeight"); for (int i = 1; i < V; i++) Console.WriteLine(parent[i] + " - " + i + "\t" + graph[i, parent[i]]); } // Function to construct and // print MST for a graph represented // using adjacency matrix representation static void primMST(int[, ] graph) { // Array to store constructed MST int[] parent = new int[V]; // Key values used to pick // minimum weight edge in cut int[] key = new int[V]; // To represent set of vertices // included in MST bool[] mstSet = new bool[V]; // Initialize all keys // as INFINITE for (int i = 0; i < V; i++) { key[i] = int.MaxValue; mstSet[i] = false; } // Always include first 1st vertex in MST. // Make key 0 so that this vertex is // picked as first vertex // First node is always root of MST key[0] = 0; parent[0] = -1; // The MST will have V vertices for (int count = 0; count < V - 1; count++) { // Pick thd minimum key vertex // from the set of vertices // not yet included in MST int u = minKey(key, mstSet); // Add the picked vertex // to the MST Set mstSet[u] = true; // Update key value and parent // index of the adjacent vertices // of the picked vertex. Consider // only those vertices which are // not yet included in MST for (int v = 0; v < V; v++) // graph[u][v] is non zero only // for adjacent vertices of m // mstSet[v] is false for vertices // not yet included in MST Update // the key only if graph[u][v] is // smaller than key[v] if (graph[u, v] != 0 && mstSet[v] == false && graph[u, v] < key[v]) { parent[v] = u; key[v] = graph[u, v]; } } // print the constructed MST printMST(parent, graph); } // Driver Code public static void Main() { /* Let us create the following graph 2 3 (0)--(1)--(2) | / \ | 6| 8/ \5 |7 | / \ | (3)-------(4) 9 */ int[, ] graph = new int[, ] { { 0, 2, 0, 6, 0 }, { 2, 0, 3, 8, 5 }, { 0, 3, 0, 0, 7 }, { 6, 8, 0, 0, 9 }, { 0, 5, 7, 9, 0 } }; // Print the solution primMST(graph); }} // This code is contributed by anuj_67. <script> // Number of vertices in the graphlet V = 5; // A utility function to find the vertex with// minimum key value, from the set of vertices// not yet included in MSTfunction minKey(key, mstSet){ // Initialize min value let min = Number.MAX_VALUE, min_index; for (let v = 0; v < V; v++) if (mstSet[v] == false && key[v] < min) min = key[v], min_index = v; return min_index;} // A utility function to print the// constructed MST stored in parent[]function printMST(parent, graph){ document.write("Edge Weight" + "<br>"); for (let i = 1; i < V; i++) document.write(parent[i] + " - " + i + " " + graph[i][parent[i]] + "<br>");} // Function to construct and print MST for// a graph represented using adjacency// matrix representationfunction primMST(graph){ // Array to store constructed MST let parent = []; // Key values used to pick minimum weight edge in cut let key = []; // To represent set of vertices included in MST let mstSet = []; // Initialize all keys as INFINITE for (let i = 0; i < V; i++) key[i] = Number.MAX_VALUE, mstSet[i] = false; // Always include first 1st vertex in MST. // Make key 0 so that this vertex is picked as first vertex. key[0] = 0; parent[0] = -1; // First node is always root of MST // The MST will have V vertices for (let count = 0; count < V - 1; count++) { // Pick the minimum key vertex from the // set of vertices not yet included in MST let u = minKey(key, mstSet); // Add the picked vertex to the MST Set mstSet[u] = true; // Update key value and parent index of // the adjacent vertices of the picked vertex. // Consider only those vertices which are not // yet included in MST for (let v = 0; v < V; v++) // graph[u][v] is non zero only for adjacent vertices of m // mstSet[v] is false for vertices not yet included in MST // Update the key only if graph[u][v] is smaller than key[v] if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) parent[v] = u, key[v] = graph[u][v]; } // print the constructed MST printMST(parent, graph);} // Driver code /* Let us create the following graph 2 3 (0)--(1)--(2) | / \ | 6| 8/ \5 |7 | / \ | (3)-------(4) 9 */ let graph = [ [ 0, 2, 0, 6, 0 ],[ 2, 0, 3, 8, 5 ],[ 0, 3, 0, 0, 7 ],[ 6, 8, 0, 0, 9 ],[ 0, 5, 7, 9, 0 ] ]; // Print the solutionprimMST(graph); // This code is contributed by Dharanendra L V.</script> Output: Edge Weight 0 - 1 2 1 - 2 3 0 - 3 6 1 - 4 5 The Time Complexity of the above program is O(V^2). If the input graph is represented using adjacency list, then the time complexity of Prim’s algorithm can be reduced to O(E log V) with the help of a binary heap. In this implementation, we are always considering the spanning tree to start from the root of the graph, and this is the basic difference between Kruskal’s Minimum Spanning Tree and Prim’s Minimum Spanning tree. Please see Prim’s MST for Adjacency List Representation for more details. Prim's Algorithm for MST(with Code Walkthrough) | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPrim's Algorithm for MST(with Code Walkthrough) | 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 / 8:11•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=eB61LXLZVqs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySGHRB9iQ-jxdhLUriW-V6wr Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m AnkurKarmakar udkumar249 GlitchFinder rathbhupendra POuryaKordi user_9781 arorakashish0911 dharanendralv23 simmytarika5 varun_b_g AliZaidi1 amartyaghoshgfg kumargaurav97520 geeky01adarsh Amazon Cisco Minimum Spanning Tree Prim's Algorithm.MST Samsung Graph Greedy Amazon Samsung Cisco Greedy Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Graph and its representations Find if there is a path between two vertices in a directed graph Topological Sorting Program for array rotation Write a program to print all permutations of a given string Coin Change | DP-7 Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Minimum Number of Platforms Required for a Railway/Bus Station
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 995, "s": 54, "text": "We have discussed Kruskal’s algorithm for Minimum Spanning Tree. Like Kruskal’s algorithm, Prim’s algorithm is also a Greedy algorithm. It starts with an empty spanning tree. The idea is to maintain two sets of vertices. The first set contains the vertices already included in the MST, the other set contains the vertices not yet included. At every step, it considers all the edges that connect the two sets and picks the minimum weight edge from these edges. After picking the edge, it moves the other endpoint of the edge to the set containing MST. A group of edges that connects two sets of vertices in a graph is called cut in graph theory. So, at every step of Prim’s algorithm, we find a cut (of two sets, one contains the vertices already included in MST and the other contains the rest of the vertices), pick the minimum weight edge from the cut, and include this vertex to MST Set (the set that contains already included vertices)." }, { "code": null, "e": 1318, "s": 995, "text": "How does Prim’s Algorithm Work? The idea behind Prim’s algorithm is simple, a spanning tree means all vertices must be connected. So the two disjoint subsets (discussed above) of vertices must be connected to make a Spanning Tree. And they must be connected with the minimum weight edge to make it a Minimum Spanning Tree." }, { "code": null, "e": 2265, "s": 1318, "text": "Algorithm 1) Create a set mstSet that keeps track of vertices already included in MST. 2) Assign a key value to all vertices in the input graph. Initialize all key values as INFINITE. Assign the key value as 0 for the first vertex so that it is picked first. 3) While mstSet doesn’t include all vertices ....a) Pick a vertex u which is not there in mstSet and has a minimum key value. ....b) Include u to mstSet. ....c) Update key value of all adjacent vertices of u. To update the key values, iterate through all adjacent vertices. For every adjacent vertex v, if the weight of edge u-v is less than the previous key value of v, update the key value as the weight of u-vThe idea of using key values is to pick the minimum weight edge from cut. The key values are used only for vertices that are not yet included in MST, the key value for these vertices indicates the minimum weight edges connecting them to the set of vertices included in MST. " }, { "code": null, "e": 2313, "s": 2265, "text": "Let us understand with the following example: " }, { "code": null, "e": 2883, "s": 2313, "text": "The set mstSet is initially empty and keys assigned to vertices are {0, INF, INF, INF, INF, INF, INF, INF} where INF indicates infinite. Now pick the vertex with the minimum key value. The vertex 0 is picked, include it in mstSet. So mstSet becomes {0}. After including to mstSet, update key values of adjacent vertices. Adjacent vertices of 0 are 1 and 7. The key values of 1 and 7 are updated as 4 and 8. Following subgraph shows vertices and their key values, only the vertices with finite key values are shown. The vertices included in MST are shown in green color." }, { "code": null, "e": 2892, "s": 2883, "text": "Chapters" }, { "code": null, "e": 2919, "s": 2892, "text": "descriptions off, selected" }, { "code": null, "e": 2969, "s": 2919, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 2992, "s": 2969, "text": "captions off, selected" }, { "code": null, "e": 3000, "s": 2992, "text": "English" }, { "code": null, "e": 3024, "s": 3000, "text": "This is a modal window." }, { "code": null, "e": 3093, "s": 3024, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 3115, "s": 3093, "text": "End of dialog window." }, { "code": null, "e": 3364, "s": 3115, "text": "Pick the vertex with minimum key value and not already included in MST (not in mstSET). The vertex 1 is picked and added to mstSet. So mstSet now becomes {0, 1}. Update the key values of adjacent vertices of 1. The key value of vertex 2 becomes 8. " }, { "code": null, "e": 3672, "s": 3364, "text": "Pick the vertex with minimum key value and not already included in MST (not in mstSET). We can either pick vertex 7 or vertex 2, let vertex 7 is picked. So mstSet now becomes {0, 1, 7}. Update the key values of adjacent vertices of 7. The key value of vertex 6 and 8 becomes finite (1 and 7 respectively). " }, { "code": null, "e": 3911, "s": 3672, "text": "Pick the vertex with minimum key value and not already included in MST (not in mstSET). Vertex 6 is picked. So mstSet now becomes {0, 1, 7, 6}. Update the key values of adjacent vertices of 6. The key value of vertex 5 and 8 are updated. " }, { "code": null, "e": 4026, "s": 3911, "text": "We repeat the above steps until mstSet includes all vertices of given graph. Finally, we get the following graph. " }, { "code": null, "e": 4429, "s": 4028, "text": "How to implement the above algorithm? We use a boolean array mstSet[] to represent the set of vertices included in MST. If a value mstSet[v] is true, then vertex v is included in MST, otherwise not. Array key[] is used to store key values of all vertices. Another array parent[] to store indexes of parent nodes in MST. The parent array is the output array which is used to show the constructed MST. " }, { "code": null, "e": 4433, "s": 4429, "text": "C++" }, { "code": null, "e": 4435, "s": 4433, "text": "C" }, { "code": null, "e": 4440, "s": 4435, "text": "Java" }, { "code": null, "e": 4448, "s": 4440, "text": "Python3" }, { "code": null, "e": 4451, "s": 4448, "text": "C#" }, { "code": null, "e": 4462, "s": 4451, "text": "Javascript" }, { "code": "// A C++ program for Prim's Minimum// Spanning Tree (MST) algorithm. The program is// for adjacency matrix representation of the graph#include <bits/stdc++.h>using namespace std; // Number of vertices in the graph#define V 5 // A utility function to find the vertex with// minimum key value, from the set of vertices// not yet included in MSTint minKey(int key[], bool mstSet[]){ // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (mstSet[v] == false && key[v] < min) min = key[v], min_index = v; return min_index;} // A utility function to print the// constructed MST stored in parent[]void printMST(int parent[], int graph[V][V]){ cout<<\"Edge \\tWeight\\n\"; for (int i = 1; i < V; i++) cout<<parent[i]<<\" - \"<<i<<\" \\t\"<<graph[i][parent[i]]<<\" \\n\";} // Function to construct and print MST for// a graph represented using adjacency// matrix representationvoid primMST(int graph[V][V]){ // Array to store constructed MST int parent[V]; // Key values used to pick minimum weight edge in cut int key[V]; // To represent set of vertices included in MST bool mstSet[V]; // Initialize all keys as INFINITE for (int i = 0; i < V; i++) key[i] = INT_MAX, mstSet[i] = false; // Always include first 1st vertex in MST. // Make key 0 so that this vertex is picked as first vertex. key[0] = 0; parent[0] = -1; // First node is always root of MST // The MST will have V vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum key vertex from the // set of vertices not yet included in MST int u = minKey(key, mstSet); // Add the picked vertex to the MST Set mstSet[u] = true; // Update key value and parent index of // the adjacent vertices of the picked vertex. // Consider only those vertices which are not // yet included in MST for (int v = 0; v < V; v++) // graph[u][v] is non zero only for adjacent vertices of m // mstSet[v] is false for vertices not yet included in MST // Update the key only if graph[u][v] is smaller than key[v] if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) parent[v] = u, key[v] = graph[u][v]; } // print the constructed MST printMST(parent, graph);} // Driver codeint main(){ /* Let us create the following graph 2 3 (0)--(1)--(2) | / \\ | 6| 8/ \\5 |7 | / \\ | (3)-------(4) 9 */ int graph[V][V] = { { 0, 2, 0, 6, 0 }, { 2, 0, 3, 8, 5 }, { 0, 3, 0, 0, 7 }, { 6, 8, 0, 0, 9 }, { 0, 5, 7, 9, 0 } }; // Print the solution primMST(graph); return 0;} // This code is contributed by rathbhupendra", "e": 7332, "s": 4462, "text": null }, { "code": "// A C program for Prim's Minimum// Spanning Tree (MST) algorithm. The program is// for adjacency matrix representation of the graph#include <limits.h>#include <stdbool.h>#include <stdio.h>// Number of vertices in the graph#define V 5 // A utility function to find the vertex with// minimum key value, from the set of vertices// not yet included in MSTint minKey(int key[], bool mstSet[]){ // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (mstSet[v] == false && key[v] < min) min = key[v], min_index = v; return min_index;} // A utility function to print the// constructed MST stored in parent[]int printMST(int parent[], int graph[V][V]){ printf(\"Edge \\tWeight\\n\"); for (int i = 1; i < V; i++) printf(\"%d - %d \\t%d \\n\", parent[i], i, graph[i][parent[i]]);} // Function to construct and print MST for// a graph represented using adjacency// matrix representationvoid primMST(int graph[V][V]){ // Array to store constructed MST int parent[V]; // Key values used to pick minimum weight edge in cut int key[V]; // To represent set of vertices included in MST bool mstSet[V]; // Initialize all keys as INFINITE for (int i = 0; i < V; i++) key[i] = INT_MAX, mstSet[i] = false; // Always include first 1st vertex in MST. // Make key 0 so that this vertex is picked as first vertex. key[0] = 0; parent[0] = -1; // First node is always root of MST // The MST will have V vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum key vertex from the // set of vertices not yet included in MST int u = minKey(key, mstSet); // Add the picked vertex to the MST Set mstSet[u] = true; // Update key value and parent index of // the adjacent vertices of the picked vertex. // Consider only those vertices which are not // yet included in MST for (int v = 0; v < V; v++) // graph[u][v] is non zero only for adjacent vertices of m // mstSet[v] is false for vertices not yet included in MST // Update the key only if graph[u][v] is smaller than key[v] if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) parent[v] = u, key[v] = graph[u][v]; } // print the constructed MST printMST(parent, graph);} // driver program to test above functionint main(){ /* Let us create the following graph 2 3 (0)--(1)--(2) | / \\ | 6| 8/ \\5 |7 | / \\ | (3)-------(4) 9 */ int graph[V][V] = { { 0, 2, 0, 6, 0 }, { 2, 0, 3, 8, 5 }, { 0, 3, 0, 0, 7 }, { 6, 8, 0, 0, 9 }, { 0, 5, 7, 9, 0 } }; // Print the solution primMST(graph); return 0;}", "e": 10189, "s": 7332, "text": null }, { "code": "// A Java program for Prim's Minimum Spanning Tree (MST) algorithm.// The program is for adjacency matrix representation of the graph import java.util.*;import java.lang.*;import java.io.*; class MST { // Number of vertices in the graph private static final int V = 5; // A utility function to find the vertex with minimum key // value, from the set of vertices not yet included in MST int minKey(int key[], Boolean mstSet[]) { // Initialize min value int min = Integer.MAX_VALUE, min_index = -1; for (int v = 0; v < V; v++) if (mstSet[v] == false && key[v] < min) { min = key[v]; min_index = v; } return min_index; } // A utility function to print the constructed MST stored in // parent[] void printMST(int parent[], int graph[][]) { System.out.println(\"Edge \\tWeight\"); for (int i = 1; i < V; i++) System.out.println(parent[i] + \" - \" + i + \"\\t\" + graph[i][parent[i]]); } // Function to construct and print MST for a graph represented // using adjacency matrix representation void primMST(int graph[][]) { // Array to store constructed MST int parent[] = new int[V]; // Key values used to pick minimum weight edge in cut int key[] = new int[V]; // To represent set of vertices included in MST Boolean mstSet[] = new Boolean[V]; // Initialize all keys as INFINITE for (int i = 0; i < V; i++) { key[i] = Integer.MAX_VALUE; mstSet[i] = false; } // Always include first 1st vertex in MST. key[0] = 0; // Make key 0 so that this vertex is // picked as first vertex parent[0] = -1; // First node is always root of MST // The MST will have V vertices for (int count = 0; count < V - 1; count++) { // Pick thd minimum key vertex from the set of vertices // not yet included in MST int u = minKey(key, mstSet); // Add the picked vertex to the MST Set mstSet[u] = true; // Update key value and parent index of the adjacent // vertices of the picked vertex. Consider only those // vertices which are not yet included in MST for (int v = 0; v < V; v++) // graph[u][v] is non zero only for adjacent vertices of m // mstSet[v] is false for vertices not yet included in MST // Update the key only if graph[u][v] is smaller than key[v] if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) { parent[v] = u; key[v] = graph[u][v]; } } // print the constructed MST printMST(parent, graph); } public static void main(String[] args) { /* Let us create the following graph 2 3 (0)--(1)--(2) | / \\ | 6| 8/ \\5 |7 | / \\ | (3)-------(4) 9 */ MST t = new MST(); int graph[][] = new int[][] { { 0, 2, 0, 6, 0 }, { 2, 0, 3, 8, 5 }, { 0, 3, 0, 0, 7 }, { 6, 8, 0, 0, 9 }, { 0, 5, 7, 9, 0 } }; // Print the solution t.primMST(graph); }}// This code is contributed by Aakash Hasija", "e": 13644, "s": 10189, "text": null }, { "code": "# A Python program for Prim's Minimum Spanning Tree (MST) algorithm.# The program is for adjacency matrix representation of the graph import sys # Library for INT_MAX class Graph(): def __init__(self, vertices): self.V = vertices self.graph = [[0 for column in range(vertices)] for row in range(vertices)] # A utility function to print the constructed MST stored in parent[] def printMST(self, parent): print (\"Edge \\tWeight\") for i in range(1, self.V): print (parent[i], \"-\", i, \"\\t\", self.graph[i][parent[i]]) # A utility function to find the vertex with # minimum distance value, from the set of vertices # not yet included in shortest path tree def minKey(self, key, mstSet): # Initialize min value min = sys.maxsize for v in range(self.V): if key[v] < min and mstSet[v] == False: min = key[v] min_index = v return min_index # Function to construct and print MST for a graph # represented using adjacency matrix representation def primMST(self): # Key values used to pick minimum weight edge in cut key = [sys.maxsize] * self.V parent = [None] * self.V # Array to store constructed MST # Make key 0 so that this vertex is picked as first vertex key[0] = 0 mstSet = [False] * self.V parent[0] = -1 # First node is always the root of for cout in range(self.V): # Pick the minimum distance vertex from # the set of vertices not yet processed. # u is always equal to src in first iteration u = self.minKey(key, mstSet) # Put the minimum distance vertex in # the shortest path tree mstSet[u] = True # Update dist value of the adjacent vertices # of the picked vertex only if the current # distance is greater than new distance and # the vertex in not in the shortest path tree for v in range(self.V): # graph[u][v] is non zero only for adjacent vertices of m # mstSet[v] is false for vertices not yet included in MST # Update the key only if graph[u][v] is smaller than key[v] if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]: key[v] = self.graph[u][v] parent[v] = u self.printMST(parent) g = Graph(5)g.graph = [ [0, 2, 0, 6, 0], [2, 0, 3, 8, 5], [0, 3, 0, 0, 7], [6, 8, 0, 0, 9], [0, 5, 7, 9, 0]] g.primMST(); # Contributed by Divyanshu Mehta", "e": 16332, "s": 13644, "text": null }, { "code": "// A C# program for Prim's Minimum// Spanning Tree (MST) algorithm.// The program is for adjacency// matrix representation of the graphusing System;class MST { // Number of vertices in the graph static int V = 5; // A utility function to find // the vertex with minimum key // value, from the set of vertices // not yet included in MST static int minKey(int[] key, bool[] mstSet) { // Initialize min value int min = int.MaxValue, min_index = -1; for (int v = 0; v < V; v++) if (mstSet[v] == false && key[v] < min) { min = key[v]; min_index = v; } return min_index; } // A utility function to print // the constructed MST stored in // parent[] static void printMST(int[] parent, int[, ] graph) { Console.WriteLine(\"Edge \\tWeight\"); for (int i = 1; i < V; i++) Console.WriteLine(parent[i] + \" - \" + i + \"\\t\" + graph[i, parent[i]]); } // Function to construct and // print MST for a graph represented // using adjacency matrix representation static void primMST(int[, ] graph) { // Array to store constructed MST int[] parent = new int[V]; // Key values used to pick // minimum weight edge in cut int[] key = new int[V]; // To represent set of vertices // included in MST bool[] mstSet = new bool[V]; // Initialize all keys // as INFINITE for (int i = 0; i < V; i++) { key[i] = int.MaxValue; mstSet[i] = false; } // Always include first 1st vertex in MST. // Make key 0 so that this vertex is // picked as first vertex // First node is always root of MST key[0] = 0; parent[0] = -1; // The MST will have V vertices for (int count = 0; count < V - 1; count++) { // Pick thd minimum key vertex // from the set of vertices // not yet included in MST int u = minKey(key, mstSet); // Add the picked vertex // to the MST Set mstSet[u] = true; // Update key value and parent // index of the adjacent vertices // of the picked vertex. Consider // only those vertices which are // not yet included in MST for (int v = 0; v < V; v++) // graph[u][v] is non zero only // for adjacent vertices of m // mstSet[v] is false for vertices // not yet included in MST Update // the key only if graph[u][v] is // smaller than key[v] if (graph[u, v] != 0 && mstSet[v] == false && graph[u, v] < key[v]) { parent[v] = u; key[v] = graph[u, v]; } } // print the constructed MST printMST(parent, graph); } // Driver Code public static void Main() { /* Let us create the following graph 2 3 (0)--(1)--(2) | / \\ | 6| 8/ \\5 |7 | / \\ | (3)-------(4) 9 */ int[, ] graph = new int[, ] { { 0, 2, 0, 6, 0 }, { 2, 0, 3, 8, 5 }, { 0, 3, 0, 0, 7 }, { 6, 8, 0, 0, 9 }, { 0, 5, 7, 9, 0 } }; // Print the solution primMST(graph); }} // This code is contributed by anuj_67.", "e": 19895, "s": 16332, "text": null }, { "code": "<script> // Number of vertices in the graphlet V = 5; // A utility function to find the vertex with// minimum key value, from the set of vertices// not yet included in MSTfunction minKey(key, mstSet){ // Initialize min value let min = Number.MAX_VALUE, min_index; for (let v = 0; v < V; v++) if (mstSet[v] == false && key[v] < min) min = key[v], min_index = v; return min_index;} // A utility function to print the// constructed MST stored in parent[]function printMST(parent, graph){ document.write(\"Edge Weight\" + \"<br>\"); for (let i = 1; i < V; i++) document.write(parent[i] + \" - \" + i + \" \" + graph[i][parent[i]] + \"<br>\");} // Function to construct and print MST for// a graph represented using adjacency// matrix representationfunction primMST(graph){ // Array to store constructed MST let parent = []; // Key values used to pick minimum weight edge in cut let key = []; // To represent set of vertices included in MST let mstSet = []; // Initialize all keys as INFINITE for (let i = 0; i < V; i++) key[i] = Number.MAX_VALUE, mstSet[i] = false; // Always include first 1st vertex in MST. // Make key 0 so that this vertex is picked as first vertex. key[0] = 0; parent[0] = -1; // First node is always root of MST // The MST will have V vertices for (let count = 0; count < V - 1; count++) { // Pick the minimum key vertex from the // set of vertices not yet included in MST let u = minKey(key, mstSet); // Add the picked vertex to the MST Set mstSet[u] = true; // Update key value and parent index of // the adjacent vertices of the picked vertex. // Consider only those vertices which are not // yet included in MST for (let v = 0; v < V; v++) // graph[u][v] is non zero only for adjacent vertices of m // mstSet[v] is false for vertices not yet included in MST // Update the key only if graph[u][v] is smaller than key[v] if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) parent[v] = u, key[v] = graph[u][v]; } // print the constructed MST printMST(parent, graph);} // Driver code /* Let us create the following graph 2 3 (0)--(1)--(2) | / \\ | 6| 8/ \\5 |7 | / \\ | (3)-------(4) 9 */ let graph = [ [ 0, 2, 0, 6, 0 ],[ 2, 0, 3, 8, 5 ],[ 0, 3, 0, 0, 7 ],[ 6, 8, 0, 0, 9 ],[ 0, 5, 7, 9, 0 ] ]; // Print the solutionprimMST(graph); // This code is contributed by Dharanendra L V.</script>", "e": 22495, "s": 19895, "text": null }, { "code": null, "e": 22504, "s": 22495, "text": "Output: " }, { "code": null, "e": 22562, "s": 22504, "text": "Edge Weight\n0 - 1 2\n1 - 2 3\n0 - 3 6\n1 - 4 5" }, { "code": null, "e": 22989, "s": 22562, "text": "The Time Complexity of the above program is O(V^2). If the input graph is represented using adjacency list, then the time complexity of Prim’s algorithm can be reduced to O(E log V) with the help of a binary heap. In this implementation, we are always considering the spanning tree to start from the root of the graph, and this is the basic difference between Kruskal’s Minimum Spanning Tree and Prim’s Minimum Spanning tree." }, { "code": null, "e": 23066, "s": 22989, "text": " Please see Prim’s MST for Adjacency List Representation for more details. " }, { "code": null, "e": 23978, "s": 23066, "text": "Prim's Algorithm for MST(with Code Walkthrough) | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPrim's Algorithm for MST(with Code Walkthrough) | 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 / 8:11•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=eB61LXLZVqs\" 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": 24019, "s": 23978, "text": "?list=PLqM7alHXFySGHRB9iQ-jxdhLUriW-V6wr" }, { "code": null, "e": 24145, "s": 24019, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 24152, "s": 24147, "text": "vt_m" }, { "code": null, "e": 24166, "s": 24152, "text": "AnkurKarmakar" }, { "code": null, "e": 24177, "s": 24166, "text": "udkumar249" }, { "code": null, "e": 24190, "s": 24177, "text": "GlitchFinder" }, { "code": null, "e": 24204, "s": 24190, "text": "rathbhupendra" }, { "code": null, "e": 24216, "s": 24204, "text": "POuryaKordi" }, { "code": null, "e": 24226, "s": 24216, "text": "user_9781" }, { "code": null, "e": 24243, "s": 24226, "text": "arorakashish0911" }, { "code": null, "e": 24259, "s": 24243, "text": "dharanendralv23" }, { "code": null, "e": 24272, "s": 24259, "text": "simmytarika5" }, { "code": null, "e": 24282, "s": 24272, "text": "varun_b_g" }, { "code": null, "e": 24292, "s": 24282, "text": "AliZaidi1" }, { "code": null, "e": 24308, "s": 24292, "text": "amartyaghoshgfg" }, { "code": null, "e": 24325, "s": 24308, "text": "kumargaurav97520" }, { "code": null, "e": 24339, "s": 24325, "text": "geeky01adarsh" }, { "code": null, "e": 24346, "s": 24339, "text": "Amazon" }, { "code": null, "e": 24352, "s": 24346, "text": "Cisco" }, { "code": null, "e": 24374, "s": 24352, "text": "Minimum Spanning Tree" }, { "code": null, "e": 24395, "s": 24374, "text": "Prim's Algorithm.MST" }, { "code": null, "e": 24403, "s": 24395, "text": "Samsung" }, { "code": null, "e": 24409, "s": 24403, "text": "Graph" }, { "code": null, "e": 24416, "s": 24409, "text": "Greedy" }, { "code": null, "e": 24423, "s": 24416, "text": "Amazon" }, { "code": null, "e": 24431, "s": 24423, "text": "Samsung" }, { "code": null, "e": 24437, "s": 24431, "text": "Cisco" }, { "code": null, "e": 24444, "s": 24437, "text": "Greedy" }, { "code": null, "e": 24450, "s": 24444, "text": "Graph" }, { "code": null, "e": 24548, "s": 24450, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24588, "s": 24548, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 24626, "s": 24588, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 24656, "s": 24626, "text": "Graph and its representations" }, { "code": null, "e": 24721, "s": 24656, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 24741, "s": 24721, "text": "Topological Sorting" }, { "code": null, "e": 24768, "s": 24741, "text": "Program for array rotation" }, { "code": null, "e": 24828, "s": 24768, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 24847, "s": 24828, "text": "Coin Change | DP-7" }, { "code": null, "e": 24928, "s": 24847, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" } ]
numpy.random.chisquare() in Python
15 Jul, 2020 With the help of chisquare() method, we can get chi-square distribution by using this method. Mainly we can use this distribution in hypothesis testing. chi-square distribution Syntax : numpy.random.chisquare(df, size=None) Parameters : 1) df – number of degree of freedom and must be >0. 2) size – Output shape of scalar array. Return : Return the scalar numpy array. Example #1 : In this example we can see that by using chisquare() method, we are able to get the chi-square distribution and return the scalar numpy array by using this method. Python3 # import chisquareimport numpy as npimport matplotlib.pyplot as plt # Using chisquare() methodgfg = np.random.chisquare(3, 1000) count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show() Output : Example #2 : Python3 # import chisquareimport numpy as npimport matplotlib.pyplot as plt # Using chisquare() methodgfg = np.random.chisquare(5, 10000)gfg1 = np.random.chisquare(gfg, 10000) count, bins, ignored = plt.hist(gfg1, 30, density = True)plt.show() Output : Python numpy-Random Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jul, 2020" }, { "code": null, "e": 181, "s": 28, "text": "With the help of chisquare() method, we can get chi-square distribution by using this method. Mainly we can use this distribution in hypothesis testing." }, { "code": null, "e": 205, "s": 181, "text": "chi-square distribution" }, { "code": null, "e": 252, "s": 205, "text": "Syntax : numpy.random.chisquare(df, size=None)" }, { "code": null, "e": 266, "s": 252, "text": "Parameters : " }, { "code": null, "e": 318, "s": 266, "text": "1) df – number of degree of freedom and must be >0." }, { "code": null, "e": 358, "s": 318, "text": "2) size – Output shape of scalar array." }, { "code": null, "e": 398, "s": 358, "text": "Return : Return the scalar numpy array." }, { "code": null, "e": 411, "s": 398, "text": "Example #1 :" }, { "code": null, "e": 575, "s": 411, "text": "In this example we can see that by using chisquare() method, we are able to get the chi-square distribution and return the scalar numpy array by using this method." }, { "code": null, "e": 583, "s": 575, "text": "Python3" }, { "code": "# import chisquareimport numpy as npimport matplotlib.pyplot as plt # Using chisquare() methodgfg = np.random.chisquare(3, 1000) count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()", "e": 781, "s": 583, "text": null }, { "code": null, "e": 790, "s": 781, "text": "Output :" }, { "code": null, "e": 803, "s": 790, "text": "Example #2 :" }, { "code": null, "e": 811, "s": 803, "text": "Python3" }, { "code": "# import chisquareimport numpy as npimport matplotlib.pyplot as plt # Using chisquare() methodgfg = np.random.chisquare(5, 10000)gfg1 = np.random.chisquare(gfg, 10000) count, bins, ignored = plt.hist(gfg1, 30, density = True)plt.show()", "e": 1049, "s": 811, "text": null }, { "code": null, "e": 1058, "s": 1049, "text": "Output :" }, { "code": null, "e": 1078, "s": 1058, "text": "Python numpy-Random" }, { "code": null, "e": 1091, "s": 1078, "text": "Python-numpy" }, { "code": null, "e": 1098, "s": 1091, "text": "Python" }, { "code": null, "e": 1196, "s": 1098, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1228, "s": 1196, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1255, "s": 1228, "text": "Python Classes and Objects" }, { "code": null, "e": 1276, "s": 1255, "text": "Python OOPs Concepts" }, { "code": null, "e": 1299, "s": 1276, "text": "Introduction To PYTHON" }, { "code": null, "e": 1330, "s": 1299, "text": "Python | os.path.join() method" }, { "code": null, "e": 1386, "s": 1330, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1428, "s": 1386, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1470, "s": 1428, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1509, "s": 1470, "text": "Python | Get unique values from a list" } ]
C++ Program for Third largest element in an array of distinct elements
03 Jan, 2022 Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example : Input: arr[] = {1, 14, 2, 16, 10, 20} Output: The third Largest element is 14 Explanation: Largest element is 20, second largest element is 16 and third largest element is 14 Input: arr[] = {19, -10, 20, 14, 2, 16, 10} Output: The third Largest element is 16 Explanation: Largest element is 20, second largest element is 19 and third largest element is 16 Naive Approach: The task is to first find the largest element, followed by the second-largest element and then excluding them both find the third-largest element. The basic idea is to iterate the array twice and mark the maximum and second maximum element and then excluding them both find the third maximum element, i.e the maximum element excluding the maximum and second maximum. Algorithm: First, iterate through the array and find maximum.Store this as first maximum along with its index.Now traverse the whole array finding the second max, excluding the maximum element.Finally traverse the array the third time and find the third largest element i.e., excluding the maximum and second maximum. First, iterate through the array and find maximum.Store this as first maximum along with its index.Now traverse the whole array finding the second max, excluding the maximum element.Finally traverse the array the third time and find the third largest element i.e., excluding the maximum and second maximum. First, iterate through the array and find maximum. Store this as first maximum along with its index. Now traverse the whole array finding the second max, excluding the maximum element. Finally traverse the array the third time and find the third largest element i.e., excluding the maximum and second maximum. C++ // C++ program to find third Largest// element in an array of distinct elements#include <bits/stdc++.h> void thirdLargest(int arr[], int arr_size){ /* There should be atleast three elements */ if (arr_size < 3) { printf(" Invalid Input "); return; } // Find first largest element int first = arr[0]; for (int i = 1; i < arr_size ; i++) if (arr[i] > first) first = arr[i]; // Find second largest element int second = INT_MIN; for (int i = 0; i < arr_size ; i++) if (arr[i] > second && arr[i] < first) second = arr[i]; // Find third largest element int third = INT_MIN; for (int i = 0; i < arr_size ; i++) if (arr[i] > third && arr[i] < second) third = arr[i]; printf("The third Largest element is %d", third);} /* Driver program to test above function */int main(){ int arr[] = {12, 13, 1, 10, 34, 16}; int n = sizeof(arr)/sizeof(arr[0]); thirdLargest(arr, n); return 0;} Output: The third Largest element is 13 Complexity Analysis: Time Complexity: O(n). As the array is iterated thrice and is done in a constant timeSpace complexity: O(1). No extra space is needed as the indices can be stored in constant space. Time Complexity: O(n). As the array is iterated thrice and is done in a constant time Space complexity: O(1). No extra space is needed as the indices can be stored in constant space. Efficient Approach: The problem deals with finding the third largest element in the array in a single traversal. The problem can be cracked by taking help of a similar problem- finding the second maximum element. So the idea is to traverse the array from start to end and to keep track of the three largest elements up to that index (stored in variables). So after traversing the whole array, the variables would have stored the indices (or value) of the three largest elements of the array. Algorithm: Create three variables, first, second, third, to store indices of three largest elements of the array. (Initially all of them are initialized to a minimum value).Move along the input array from start to the end.For every index check if the element is larger than first or not. Update the value of first, if the element is larger, and assign the value of first to second and second to third. So the largest element gets updated and the elements previously stored as largest becomes second largest, and the second largest element becomes third largest.Else if the element is larger than the second, then update the value of second,and the second largest element becomes third largest.If the previous two conditions fail, but the element is larger than the third, then update the third.Print the value of third after traversing the array from start to end Create three variables, first, second, third, to store indices of three largest elements of the array. (Initially all of them are initialized to a minimum value).Move along the input array from start to the end.For every index check if the element is larger than first or not. Update the value of first, if the element is larger, and assign the value of first to second and second to third. So the largest element gets updated and the elements previously stored as largest becomes second largest, and the second largest element becomes third largest.Else if the element is larger than the second, then update the value of second,and the second largest element becomes third largest.If the previous two conditions fail, but the element is larger than the third, then update the third.Print the value of third after traversing the array from start to end Create three variables, first, second, third, to store indices of three largest elements of the array. (Initially all of them are initialized to a minimum value). Move along the input array from start to the end. For every index check if the element is larger than first or not. Update the value of first, if the element is larger, and assign the value of first to second and second to third. So the largest element gets updated and the elements previously stored as largest becomes second largest, and the second largest element becomes third largest. Else if the element is larger than the second, then update the value of second,and the second largest element becomes third largest. If the previous two conditions fail, but the element is larger than the third, then update the third. Print the value of third after traversing the array from start to end C++ // C++ program to find third // Largest element in an array#include <bits/stdc++.h> void thirdLargest(int arr[], int arr_size){ /* There should be atleast three elements */ if (arr_size < 3) { printf(" Invalid Input "); return; } // Initialize first, second and third Largest element int first = arr[0], second = INT_MIN, third = INT_MIN; // Traverse array elements to find the third Largest for (int i = 1; i < arr_size ; i ++) { /* If current element is greater than first, then update first, second and third */ if (arr[i] > first) { third = second; second = first; first = arr[i]; } /* If arr[i] is in between first and second */ else if (arr[i] > second) { third = second; second = arr[i]; } /* If arr[i] is in between second and third */ else if (arr[i] > third) third = arr[i]; } printf("The third Largest element is %d", third);} /* Driver program to test above function */int main(){ int arr[] = {12, 13, 1, 10, 34, 16}; int n = sizeof(arr)/sizeof(arr[0]); thirdLargest(arr, n); return 0;} Output: The third Largest element is 13 Complexity Analysis:Time Complexity: O(n). As the array is iterated once and is done in a constant timeSpace complexity: O(1). No extra space is needed as the indices can be stored in constant space. Time Complexity: O(n). As the array is iterated once and is done in a constant time Space complexity: O(1). No extra space is needed as the indices can be stored in constant space. Please refer complete article on Third largest element in an array of distinct elements for more details! Amazon Arrays C++ C++ Programs Searching Amazon Arrays Searching CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) std::sort() in C++ STL Bitwise Operators in C/C++
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jan, 2022" }, { "code": null, "e": 155, "s": 28, "text": "Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example : " }, { "code": null, "e": 516, "s": 155, "text": "Input: arr[] = {1, 14, 2, 16, 10, 20}\nOutput: The third Largest element is 14\n\nExplanation: Largest element is 20, second largest element is 16 \nand third largest element is 14\n\nInput: arr[] = {19, -10, 20, 14, 2, 16, 10}\nOutput: The third Largest element is 16\n\nExplanation: Largest element is 20, second largest element is 19 \nand third largest element is 16" }, { "code": null, "e": 902, "s": 518, "text": "Naive Approach: The task is to first find the largest element, followed by the second-largest element and then excluding them both find the third-largest element. The basic idea is to iterate the array twice and mark the maximum and second maximum element and then excluding them both find the third maximum element, i.e the maximum element excluding the maximum and second maximum. " }, { "code": null, "e": 1221, "s": 902, "text": "Algorithm: First, iterate through the array and find maximum.Store this as first maximum along with its index.Now traverse the whole array finding the second max, excluding the maximum element.Finally traverse the array the third time and find the third largest element i.e., excluding the maximum and second maximum. " }, { "code": null, "e": 1529, "s": 1221, "text": "First, iterate through the array and find maximum.Store this as first maximum along with its index.Now traverse the whole array finding the second max, excluding the maximum element.Finally traverse the array the third time and find the third largest element i.e., excluding the maximum and second maximum. " }, { "code": null, "e": 1580, "s": 1529, "text": "First, iterate through the array and find maximum." }, { "code": null, "e": 1630, "s": 1580, "text": "Store this as first maximum along with its index." }, { "code": null, "e": 1714, "s": 1630, "text": "Now traverse the whole array finding the second max, excluding the maximum element." }, { "code": null, "e": 1840, "s": 1714, "text": "Finally traverse the array the third time and find the third largest element i.e., excluding the maximum and second maximum. " }, { "code": null, "e": 1844, "s": 1840, "text": "C++" }, { "code": "// C++ program to find third Largest// element in an array of distinct elements#include <bits/stdc++.h> void thirdLargest(int arr[], int arr_size){ /* There should be atleast three elements */ if (arr_size < 3) { printf(\" Invalid Input \"); return; } // Find first largest element int first = arr[0]; for (int i = 1; i < arr_size ; i++) if (arr[i] > first) first = arr[i]; // Find second largest element int second = INT_MIN; for (int i = 0; i < arr_size ; i++) if (arr[i] > second && arr[i] < first) second = arr[i]; // Find third largest element int third = INT_MIN; for (int i = 0; i < arr_size ; i++) if (arr[i] > third && arr[i] < second) third = arr[i]; printf(\"The third Largest element is %d\", third);} /* Driver program to test above function */int main(){ int arr[] = {12, 13, 1, 10, 34, 16}; int n = sizeof(arr)/sizeof(arr[0]); thirdLargest(arr, n); return 0;}", "e": 2847, "s": 1844, "text": null }, { "code": null, "e": 2857, "s": 2847, "text": "Output: " }, { "code": null, "e": 2889, "s": 2857, "text": "The third Largest element is 13" }, { "code": null, "e": 3092, "s": 2889, "text": "Complexity Analysis: Time Complexity: O(n). As the array is iterated thrice and is done in a constant timeSpace complexity: O(1). No extra space is needed as the indices can be stored in constant space." }, { "code": null, "e": 3178, "s": 3092, "text": "Time Complexity: O(n). As the array is iterated thrice and is done in a constant time" }, { "code": null, "e": 3275, "s": 3178, "text": "Space complexity: O(1). No extra space is needed as the indices can be stored in constant space." }, { "code": null, "e": 3768, "s": 3275, "text": "Efficient Approach: The problem deals with finding the third largest element in the array in a single traversal. The problem can be cracked by taking help of a similar problem- finding the second maximum element. So the idea is to traverse the array from start to end and to keep track of the three largest elements up to that index (stored in variables). So after traversing the whole array, the variables would have stored the indices (or value) of the three largest elements of the array. " }, { "code": null, "e": 4633, "s": 3768, "text": "Algorithm: Create three variables, first, second, third, to store indices of three largest elements of the array. (Initially all of them are initialized to a minimum value).Move along the input array from start to the end.For every index check if the element is larger than first or not. Update the value of first, if the element is larger, and assign the value of first to second and second to third. So the largest element gets updated and the elements previously stored as largest becomes second largest, and the second largest element becomes third largest.Else if the element is larger than the second, then update the value of second,and the second largest element becomes third largest.If the previous two conditions fail, but the element is larger than the third, then update the third.Print the value of third after traversing the array from start to end " }, { "code": null, "e": 5487, "s": 4633, "text": "Create three variables, first, second, third, to store indices of three largest elements of the array. (Initially all of them are initialized to a minimum value).Move along the input array from start to the end.For every index check if the element is larger than first or not. Update the value of first, if the element is larger, and assign the value of first to second and second to third. So the largest element gets updated and the elements previously stored as largest becomes second largest, and the second largest element becomes third largest.Else if the element is larger than the second, then update the value of second,and the second largest element becomes third largest.If the previous two conditions fail, but the element is larger than the third, then update the third.Print the value of third after traversing the array from start to end " }, { "code": null, "e": 5650, "s": 5487, "text": "Create three variables, first, second, third, to store indices of three largest elements of the array. (Initially all of them are initialized to a minimum value)." }, { "code": null, "e": 5700, "s": 5650, "text": "Move along the input array from start to the end." }, { "code": null, "e": 6040, "s": 5700, "text": "For every index check if the element is larger than first or not. Update the value of first, if the element is larger, and assign the value of first to second and second to third. So the largest element gets updated and the elements previously stored as largest becomes second largest, and the second largest element becomes third largest." }, { "code": null, "e": 6173, "s": 6040, "text": "Else if the element is larger than the second, then update the value of second,and the second largest element becomes third largest." }, { "code": null, "e": 6275, "s": 6173, "text": "If the previous two conditions fail, but the element is larger than the third, then update the third." }, { "code": null, "e": 6346, "s": 6275, "text": "Print the value of third after traversing the array from start to end " }, { "code": null, "e": 6350, "s": 6346, "text": "C++" }, { "code": "// C++ program to find third // Largest element in an array#include <bits/stdc++.h> void thirdLargest(int arr[], int arr_size){ /* There should be atleast three elements */ if (arr_size < 3) { printf(\" Invalid Input \"); return; } // Initialize first, second and third Largest element int first = arr[0], second = INT_MIN, third = INT_MIN; // Traverse array elements to find the third Largest for (int i = 1; i < arr_size ; i ++) { /* If current element is greater than first, then update first, second and third */ if (arr[i] > first) { third = second; second = first; first = arr[i]; } /* If arr[i] is in between first and second */ else if (arr[i] > second) { third = second; second = arr[i]; } /* If arr[i] is in between second and third */ else if (arr[i] > third) third = arr[i]; } printf(\"The third Largest element is %d\", third);} /* Driver program to test above function */int main(){ int arr[] = {12, 13, 1, 10, 34, 16}; int n = sizeof(arr)/sizeof(arr[0]); thirdLargest(arr, n); return 0;}", "e": 7568, "s": 6350, "text": null }, { "code": null, "e": 7578, "s": 7568, "text": "Output: " }, { "code": null, "e": 7610, "s": 7578, "text": "The third Largest element is 13" }, { "code": null, "e": 7810, "s": 7610, "text": "Complexity Analysis:Time Complexity: O(n). As the array is iterated once and is done in a constant timeSpace complexity: O(1). No extra space is needed as the indices can be stored in constant space." }, { "code": null, "e": 7894, "s": 7810, "text": "Time Complexity: O(n). As the array is iterated once and is done in a constant time" }, { "code": null, "e": 7991, "s": 7894, "text": "Space complexity: O(1). No extra space is needed as the indices can be stored in constant space." }, { "code": null, "e": 8097, "s": 7991, "text": "Please refer complete article on Third largest element in an array of distinct elements for more details!" }, { "code": null, "e": 8104, "s": 8097, "text": "Amazon" }, { "code": null, "e": 8111, "s": 8104, "text": "Arrays" }, { "code": null, "e": 8115, "s": 8111, "text": "C++" }, { "code": null, "e": 8128, "s": 8115, "text": "C++ Programs" }, { "code": null, "e": 8138, "s": 8128, "text": "Searching" }, { "code": null, "e": 8145, "s": 8138, "text": "Amazon" }, { "code": null, "e": 8152, "s": 8145, "text": "Arrays" }, { "code": null, "e": 8162, "s": 8152, "text": "Searching" }, { "code": null, "e": 8166, "s": 8162, "text": "CPP" }, { "code": null, "e": 8264, "s": 8166, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8296, "s": 8264, "text": "Introduction to Data Structures" }, { "code": null, "e": 8321, "s": 8296, "text": "Window Sliding Technique" }, { "code": null, "e": 8368, "s": 8321, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 8432, "s": 8368, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 8463, "s": 8432, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 8481, "s": 8463, "text": "Vector in C++ STL" }, { "code": null, "e": 8524, "s": 8481, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 8570, "s": 8524, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 8593, "s": 8570, "text": "std::sort() in C++ STL" } ]
K-Fold Cross Validation Example Using Sklearn Python | by Cory Maklin | Towards Data Science
At the end of the day, machine learning models are used to make predictions on data for which we don’t already have the answer. For example, this could take the form of a recommender system that tries to predict whether the user will like the song or product. When developing a model, we have to be very cautious not to overfit to our training data. In other words, we have to ensure that the model is capturing the underlying pattern as opposed to simply memorizing the data. Ergo, before using a model in production, it’s imperative that we check how it handles unforeseen data. This is typically done by splitting the data into two subsets, one for training and the other to test the accuracy of the model. Certain machine learning algorithms rely on hyperparameters. In essence, a hyperparameter is a variable set by the user that dictates how the algorithm behaves. Some examples of hyperparameters are step size in gradient descent and alpha in ridge regression. There is no one size fits all when it comes to hyperparameters. A data scientist must try to determine the optimal hyperparameter values through trial and error. We call this process hyperparameter tuning. Unfortunately, if we constantly use the test set to measure the performance of our model for different hyperparameter values, our model will develop an affinity for the data inside of the test set. In other words, knowledge about the test set can leak into the model and evaluation metrics no longer reflect generalized performance. To solve this problem, we can break up the data further (i.e. validation, training and test sets). The training proceeds on the training set, after which evaluation is done on the validation set, and when we are satisfied with the results, the final evaluation can be performed on the test set. However, by partitioning the available data into three sets, we drastically reduce the number of samples which can be used for training the model. In addition, the results can depend on a particular random choice of samples. For instance, say we built a model that tried to classify hand written digits, we could end up with a scenario in which our training set contained very little samples for the number 7. A solution to these issues is a procedure called cross-validation. In cross validation, a test set is still put off to the side for final evaluation, but the validation set is no longer needed. There are multiple kinds of cross validation, the most commonly of which is called k-fold cross validation. In k-fold cross validation, the training set is split into k smaller sets (or folds). The model is then trained using k-1 of the folds and the last one is used as the validation set to compute a performance measure such as accuracy. Let’s take a look at an example. For the proceeding example, we’ll be using the Boston house prices dataset. To start, import all the necessary libraries. from sklearn.datasets import load_bostonfrom sklearn.linear_model import RidgeCVfrom sklearn.model_selection import train_test_splitimport numpy as npimport pandas as pdfrom matplotlib import pyplot as plt Next, we’ll use sklearn to import the features and labels for our data. boston = load_boston()boston_features = pd.DataFrame(boston.data, columns=boston.feature_names)X = boston_features['RM'].values.reshape(-1,1)y = boston.target We’ll use matplotlib to plot the relationship between the house prices and the average number of rooms per dwelling. plt.scatter(X, y);plt.title('boston house prices')plt.xlabel('average number of rooms per dwelling')plt.ylabel('house prices')plt.show() As mentioned previously, we’ll want to put a portion of the data aside for the final evaluation. train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.2, random_state=0) We’ll use cross validation to determine the optimal alpha value. By default, the ridge regression cross validation class uses the Leave One Out strategy (k-fold). We can compare the performance of our model with different alpha values by taking a look at the mean square error. regressor = RidgeCV(alphas=[1, 1e3, 1e6], store_cv_values=True)regressor.fit(train_X, train_y)cv_mse = np.mean(regressor.cv_values_, axis=0)print(alphas)print(cv_mse) The RidgeCV class will automatically select the best alpha value. We can view it by accessing the following property. # Best alphaprint(regressor.alpha_) We can use the model to predict that house prices for the test set. predict_y = regressor.predict(test_X) Finally, we plot the data in the test set and the line determined during the training phase. plt.scatter(test_X, test_y);plt.plot(test_X, predict_y, color='red')plt.title('boston house prices')plt.xlabel('average number of rooms per dwelling')plt.ylabel('house prices')plt.show()
[ { "code": null, "e": 431, "s": 171, "text": "At the end of the day, machine learning models are used to make predictions on data for which we don’t already have the answer. For example, this could take the form of a recommender system that tries to predict whether the user will like the song or product." }, { "code": null, "e": 881, "s": 431, "text": "When developing a model, we have to be very cautious not to overfit to our training data. In other words, we have to ensure that the model is capturing the underlying pattern as opposed to simply memorizing the data. Ergo, before using a model in production, it’s imperative that we check how it handles unforeseen data. This is typically done by splitting the data into two subsets, one for training and the other to test the accuracy of the model." }, { "code": null, "e": 1346, "s": 881, "text": "Certain machine learning algorithms rely on hyperparameters. In essence, a hyperparameter is a variable set by the user that dictates how the algorithm behaves. Some examples of hyperparameters are step size in gradient descent and alpha in ridge regression. There is no one size fits all when it comes to hyperparameters. A data scientist must try to determine the optimal hyperparameter values through trial and error. We call this process hyperparameter tuning." }, { "code": null, "e": 1679, "s": 1346, "text": "Unfortunately, if we constantly use the test set to measure the performance of our model for different hyperparameter values, our model will develop an affinity for the data inside of the test set. In other words, knowledge about the test set can leak into the model and evaluation metrics no longer reflect generalized performance." }, { "code": null, "e": 1974, "s": 1679, "text": "To solve this problem, we can break up the data further (i.e. validation, training and test sets). The training proceeds on the training set, after which evaluation is done on the validation set, and when we are satisfied with the results, the final evaluation can be performed on the test set." }, { "code": null, "e": 2384, "s": 1974, "text": "However, by partitioning the available data into three sets, we drastically reduce the number of samples which can be used for training the model. In addition, the results can depend on a particular random choice of samples. For instance, say we built a model that tried to classify hand written digits, we could end up with a scenario in which our training set contained very little samples for the number 7." }, { "code": null, "e": 2919, "s": 2384, "text": "A solution to these issues is a procedure called cross-validation. In cross validation, a test set is still put off to the side for final evaluation, but the validation set is no longer needed. There are multiple kinds of cross validation, the most commonly of which is called k-fold cross validation. In k-fold cross validation, the training set is split into k smaller sets (or folds). The model is then trained using k-1 of the folds and the last one is used as the validation set to compute a performance measure such as accuracy." }, { "code": null, "e": 3028, "s": 2919, "text": "Let’s take a look at an example. For the proceeding example, we’ll be using the Boston house prices dataset." }, { "code": null, "e": 3074, "s": 3028, "text": "To start, import all the necessary libraries." }, { "code": null, "e": 3280, "s": 3074, "text": "from sklearn.datasets import load_bostonfrom sklearn.linear_model import RidgeCVfrom sklearn.model_selection import train_test_splitimport numpy as npimport pandas as pdfrom matplotlib import pyplot as plt" }, { "code": null, "e": 3352, "s": 3280, "text": "Next, we’ll use sklearn to import the features and labels for our data." }, { "code": null, "e": 3511, "s": 3352, "text": "boston = load_boston()boston_features = pd.DataFrame(boston.data, columns=boston.feature_names)X = boston_features['RM'].values.reshape(-1,1)y = boston.target" }, { "code": null, "e": 3628, "s": 3511, "text": "We’ll use matplotlib to plot the relationship between the house prices and the average number of rooms per dwelling." }, { "code": null, "e": 3765, "s": 3628, "text": "plt.scatter(X, y);plt.title('boston house prices')plt.xlabel('average number of rooms per dwelling')plt.ylabel('house prices')plt.show()" }, { "code": null, "e": 3862, "s": 3765, "text": "As mentioned previously, we’ll want to put a portion of the data aside for the final evaluation." }, { "code": null, "e": 3951, "s": 3862, "text": "train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.2, random_state=0)" }, { "code": null, "e": 4229, "s": 3951, "text": "We’ll use cross validation to determine the optimal alpha value. By default, the ridge regression cross validation class uses the Leave One Out strategy (k-fold). We can compare the performance of our model with different alpha values by taking a look at the mean square error." }, { "code": null, "e": 4396, "s": 4229, "text": "regressor = RidgeCV(alphas=[1, 1e3, 1e6], store_cv_values=True)regressor.fit(train_X, train_y)cv_mse = np.mean(regressor.cv_values_, axis=0)print(alphas)print(cv_mse)" }, { "code": null, "e": 4514, "s": 4396, "text": "The RidgeCV class will automatically select the best alpha value. We can view it by accessing the following property." }, { "code": null, "e": 4550, "s": 4514, "text": "# Best alphaprint(regressor.alpha_)" }, { "code": null, "e": 4618, "s": 4550, "text": "We can use the model to predict that house prices for the test set." }, { "code": null, "e": 4656, "s": 4618, "text": "predict_y = regressor.predict(test_X)" }, { "code": null, "e": 4749, "s": 4656, "text": "Finally, we plot the data in the test set and the line determined during the training phase." } ]
C# | StringComparer.Compare Method - GeeksforGeeks
30 Jun, 2019 StringComparer.Compare Method is used to compare two objects or strings and returns an indication of their relative sort order. There are 2 methods in the overload list of this method: Compare(Object, Object) Compare(String, String) This method compares two objects and returns an indication of their relative sort order when overridden in a derived class. Syntax: public int Compare (object a, object b); Here, a is the 1st object and b is the 2nd object to be compared with each other. Returns: This method returns a signed integer that indicates the relative values of the object a and b. The values are returned according to the following table: Exception: This method will give ArgumentException if neither a nor b is a String object, and neither a nor b implements the IComparable interface. Example: // C# program to demonstrate the use of// StringComparer.Compare(Object, Object)// Methodusing System;using System.Collections; class gfg { public class cmp : IComparer { // CaseInsensitiveComparer int IComparer.Compare(Object x, Object y) { return ((new CaseInsensitiveComparer()).Compare(x, y)); } } // Main Method public static void Main() { // Initialize a string array. string[] arr = {"A", "E", "D", "C", "B"}; // Display original array Console.WriteLine("Original array:"); print(arr); // Sort the array using the default comparer. Array.Sort(arr); Console.WriteLine("Sort using sort function:"); print(arr); // Sort the array using the comparer. Array.Sort(arr, new cmp()); Console.WriteLine("Sorting using compare method :"); print(arr); } // print function public static void print(IEnumerable list) { foreach(var v in list) Console.WriteLine(v); Console.WriteLine(); }} Original array: A E D C B Sort using sort function: A B C D E Sorting using compare method : A B C D E This method compares two strings and returns an indication of their relative sort order when overridden in a derived class. Syntax: public abstract int Compare (string a, string b); Here, a is the 1st string and b is the 2nd string to be compared with each other. Returns: This method returns a signed integer that indicates the relative values of the object a and b. The values are returned according to the following table: Exception: This method will give ArgumentException if neither a nor b is a String object, and neither a nor b implements the IComparable interface. Example: // C# program to demonstrate the use of // StringComparer.Compare(String, String)// Methodusing System;using System.Collections.Generic; class GFG { // Main Method static void Main(string[] args) { string s1 = "geek"; string s2 = "Geek"; int st = 0; // Compare(string, string) method st = string.Compare(s1, s2); Console.WriteLine(st.ToString()); }} -1 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.stringcomparer.compare?view=netframework-4.8 C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples Partial Classes in C# C# | Inheritance C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Lambda Expressions in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n30 Jun, 2019" }, { "code": null, "e": 25732, "s": 25547, "text": "StringComparer.Compare Method is used to compare two objects or strings and returns an indication of their relative sort order. There are 2 methods in the overload list of this method:" }, { "code": null, "e": 25756, "s": 25732, "text": "Compare(Object, Object)" }, { "code": null, "e": 25780, "s": 25756, "text": "Compare(String, String)" }, { "code": null, "e": 25904, "s": 25780, "text": "This method compares two objects and returns an indication of their relative sort order when overridden in a derived class." }, { "code": null, "e": 25912, "s": 25904, "text": "Syntax:" }, { "code": null, "e": 25953, "s": 25912, "text": "public int Compare (object a, object b);" }, { "code": null, "e": 26035, "s": 25953, "text": "Here, a is the 1st object and b is the 2nd object to be compared with each other." }, { "code": null, "e": 26197, "s": 26035, "text": "Returns: This method returns a signed integer that indicates the relative values of the object a and b. The values are returned according to the following table:" }, { "code": null, "e": 26345, "s": 26197, "text": "Exception: This method will give ArgumentException if neither a nor b is a String object, and neither a nor b implements the IComparable interface." }, { "code": null, "e": 26354, "s": 26345, "text": "Example:" }, { "code": "// C# program to demonstrate the use of// StringComparer.Compare(Object, Object)// Methodusing System;using System.Collections; class gfg { public class cmp : IComparer { // CaseInsensitiveComparer int IComparer.Compare(Object x, Object y) { return ((new CaseInsensitiveComparer()).Compare(x, y)); } } // Main Method public static void Main() { // Initialize a string array. string[] arr = {\"A\", \"E\", \"D\", \"C\", \"B\"}; // Display original array Console.WriteLine(\"Original array:\"); print(arr); // Sort the array using the default comparer. Array.Sort(arr); Console.WriteLine(\"Sort using sort function:\"); print(arr); // Sort the array using the comparer. Array.Sort(arr, new cmp()); Console.WriteLine(\"Sorting using compare method :\"); print(arr); } // print function public static void print(IEnumerable list) { foreach(var v in list) Console.WriteLine(v); Console.WriteLine(); }}", "e": 27437, "s": 26354, "text": null }, { "code": null, "e": 27543, "s": 27437, "text": "Original array:\nA\nE\nD\nC\nB\n\nSort using sort function:\nA\nB\nC\nD\nE\n\nSorting using compare method :\nA\nB\nC\nD\nE\n" }, { "code": null, "e": 27667, "s": 27543, "text": "This method compares two strings and returns an indication of their relative sort order when overridden in a derived class." }, { "code": null, "e": 27675, "s": 27667, "text": "Syntax:" }, { "code": null, "e": 27725, "s": 27675, "text": "public abstract int Compare (string a, string b);" }, { "code": null, "e": 27807, "s": 27725, "text": "Here, a is the 1st string and b is the 2nd string to be compared with each other." }, { "code": null, "e": 27969, "s": 27807, "text": "Returns: This method returns a signed integer that indicates the relative values of the object a and b. The values are returned according to the following table:" }, { "code": null, "e": 28117, "s": 27969, "text": "Exception: This method will give ArgumentException if neither a nor b is a String object, and neither a nor b implements the IComparable interface." }, { "code": null, "e": 28126, "s": 28117, "text": "Example:" }, { "code": "// C# program to demonstrate the use of // StringComparer.Compare(String, String)// Methodusing System;using System.Collections.Generic; class GFG { // Main Method static void Main(string[] args) { string s1 = \"geek\"; string s2 = \"Geek\"; int st = 0; // Compare(string, string) method st = string.Compare(s1, s2); Console.WriteLine(st.ToString()); }}", "e": 28539, "s": 28126, "text": null }, { "code": null, "e": 28543, "s": 28539, "text": "-1\n" }, { "code": null, "e": 28554, "s": 28543, "text": "Reference:" }, { "code": null, "e": 28650, "s": 28554, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.stringcomparer.compare?view=netframework-4.8" }, { "code": null, "e": 28653, "s": 28650, "text": "C#" }, { "code": null, "e": 28751, "s": 28653, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28774, "s": 28751, "text": "Extension Method in C#" }, { "code": null, "e": 28802, "s": 28774, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28824, "s": 28802, "text": "Partial Classes in C#" }, { "code": null, "e": 28841, "s": 28824, "text": "C# | Inheritance" }, { "code": null, "e": 28870, "s": 28841, "text": "C# | Generics - Introduction" }, { "code": null, "e": 28910, "s": 28870, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28933, "s": 28910, "text": "Switch Statement in C#" }, { "code": null, "e": 28973, "s": 28933, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 29016, "s": 28973, "text": "C# | How to insert an element in an Array?" } ]
Using Fastai for Image Classification | by Pascal Schröder | Towards Data Science
I recently took a peek into Jeremy Howard’s 2019 course on deep learning. I never used the Fastai library before so I was pretty amazed by its level of abstraction that allows you to create stage-of-the-art neural networks in minutes, with a ridiculously tiny amount of code. In the following I will offer a short tutorial on building a CNN image classifier with Fastai that is supposed to act simultaneously as a helpful summary of the key concepts for myself and a clear overview for newcomers. I chose the plant seedling dataset from Kaggle as an examplary dataset. If you haven’t heard of Fastai yet I recommend taking a look at their homepage. In their mission statement it is stated that not only do they want to accelerate and help deep learning research, they also want to decrease the entry barriers for everyone. This line is from their introduction of PyTorch for Fastai back in September 2017 (Source): Everybody should be able to use deep learning to solve their problems with no more education than it takes to use a smart phone. Therefore, each year our main research goal is to be able to teach a wider range of deep learning applications, that run faster, and are more accurate, to people with less prerequisites. You can feel this ambition even if you watch Fastai's 2019 course, and it's something that gives me a good feeling about the direction the field is headed. As it often happens in research, knowledge and tools are only accessible to a certain minority. This is even more pronounced in deep learning research, where you need huge amounts of RAM in powerful GPUs to solve a lot of problems (check this unrelated video on GPU vs CPU). In addition, support for Fastai is now offered on a lot of cloud computing platforms, like Paperspace, Cradle and AWS, just to name a few. But since these services all cost money, I will stick to Google's just recently announced Colaboratory, that let's you use Google's GPUs for free. Yes, zero cost! Ain't that incredible times to be alive? To avoid redundancy online, please check this Medium post by Manikanta Yadunanda for a quick introduction on how to use the Google Colaboratory (Colab) with Fastai. Since this introduction was written, Google has included official Fastai and PyTorch support in Colab, so you probably don't even need to install it after connecting to a runtime. You can check with the following line of code if all of the important pip packages are installed. If not, uncomment the last line and use it to install Fastai and PyTorch for Python 3.6.x and CUDA 9.x. To access this notebook and run the computations yourself, you can simply import it directly from my GitHub repository. Just go to File... Open Notebook..., select the GitHub tab and enter ‘verrannt/Tutorials’ in the search bar. Select the ‘fastai-plant-seedlings-classification.ipynb’ and you’re done. Simple as that. After you checked that Colab is configured for Fastai support, you can continue with the data preperation part. Since we are using Kaggle as our dataset supply, you need a Kaggle account to download the dataset. If you got one, head over to your account settings and get a new API key which you can use for the Kaggle CLI. The following code installs the CLI and registers a new API key. We then download the plant seedling dataset and unzip it. Make sure that you are in the /content folder of the fastai directory. Let’s inspect the data. The folder we downloaded and extracted from Kaggle has 12 subfolders, each of which corresponds to one type of seedling with its respective images inside. These will be our labels for the classification task. If we print the lengths of the contents of these folders we can see that every folder contains a different amount of images. The differences are great, see e.g. that the ‘Loose Silky-bent’ has the most images (762) while the ‘Common Wheat’ the fewest (253). We will see later if this amounts to differences in the prediction accuracy. This outputs the following: No. of labels: 12-----------------Small-flowered Cranesbill, 576 filesCommon wheat, 253 filesCharlock, 452 filesSugar beet, 463 filesMaize, 257 filesBlack-grass, 309 filesLoose Silky-bent, 762 filesFat Hen, 538 filesCleavers, 335 filesShepherd’s Purse, 274 filesScentless Mayweed, 607 filesCommon Chickweed, 713 files Let’s have a look at those images. For each of the 12 labels, we will print one random seedling. Alright, they look good and quite distinguishable, except for ‘Loose Silky-bent’ and ‘Black-grass’. These might be harder for the network to recognize, but we will see. Let’s get to it! We can now create the CNN model using the Fastai library. Since its major update to v1, it got a lot clearer and consistent, so we only need to import the vision module and accuracy for our metric. from fastai.vision import *from fastai.metrics import accuracy Fastai has a really nice class for handling everything related to the input images for vision tasks. It is called ImageDataBunch and has different functions, respective of the different ways data can be presented to the network. Since our images are placed in folders whose names correspond to the image labels, we will use the ImageDataBunch.from_folder() function to create an object that contains our image data. This is super useful and makes it incredibly easy to read the data into our model, as you will see in a bit. What’s even more handy is that Fastai can automatically split our data into train and validation sets, so we don't even need to create these on our own. The only hyperparameters we need now are the path-variable pointing to our data set, the size of the inputs and the batch size for each gradient descent iteration. To make matters simple, the ImageDataBunch object will scale all images to a size*size squared image unless otherwise instructed. A quick note on image size: the bigger an image, the more details the CNN will be able to pick out of it. At the same time, a bigger image means longer computation times. On the same note it might be that your GPU runs out of memory for a too large batch size. You can half the batch size if this is the case. path = “./plant_seedlings-data/”size = 224bs = 64 We will create a variable called data in which we place the ImageDataBunch object. We create this object with the from_folder() function that we discussed above. Among the path to our data, the image and batch size, it also takes: a function argument called get_transforms() which returns a list of available image transformations upon call. a parameter valid_pct which controls the percentage of images that will be randomly chosen to be in the validation set a parameter flip_vert which controls vertical flips and 90° turns in addition to just horizontal flips. (Since our plant images are taken from above, we can perform those without a problem, which would not be feasible on e.g. face data.) To normalize the data in our object, we simply call normalize() on the object. It is possible to use ImageNet, CIFAR or MNIST stats as templates here, and if left empty this function will simply grab a batch of data from our object and compute the stats on it (mean and standard-deviation) and normalize the data accordingly. Since we will be using a ResNet architecture for our model which was trained on ImageNet, we will be using the ImageNet stats. data.normalize(imagenet_stats) This outputs a summary: ImageDataBunch;Train: LabelListy: CategoryList (4432 items)[Category Small-flowered Cranesbill, Category Small-flowered Cranesbill, Category Small-flowered Cranesbill, Category Small-flowered Cranesbill, Category Small-flowered Cranesbill]...Path: plant-seedlings-datax: ImageItemList (4432 items)[Image (3, 237, 237), Image (3, 497, 497), Image (3, 94, 94), Image (3, 551, 551), Image (3, 246, 246)]...Path: plant-seedlings-data;Valid: LabelListy: CategoryList (1107 items)[Category Maize, Category Black-grass, Category Common Chickweed, Category Cleavers, Category Charlock]...Path: plant-seedlings-datax: ImageItemList (1107 items)[Image (3, 529, 529), Image (3, 945, 945), Image (3, 171, 171), Image (3, 125, 125), Image (3, 163, 163)]...Path: plant-seedlings-data;Test: None That’s it, two lines of code for optimizing our dataset for training, adding different kinds of transformations and normalization! I would kindly ask you to stop here for a moment and just take a second to appreciate the beauty of this. The beauty of high-level libraries; just two lines of code and we have increased the diversity of our dataset tremendously. I can already hear my ugly batchnorm code crying in the trashbin. All that is left now is to create the actual network and train it, which could not be more simple. Fastai supplies us with a function called create_cnn() from its vision module. This function creates what is called a learner object, which we'll put into a properly named variable. See here that we specify the ResNet architecture as our base model for transfer learning. Upon call, the trained architecture will be downloaded via the Fastai API and stored locally. We will use accuracy for our metric. If you check the docs you can see a list of other metrics which are availabe. Defining the callback function ShowGraph simply tells the learner that it should return a graph for whatever it does, which seems very useful to me for seeing whether the model is still improving. learner = create_cnn(data, models.resnet18, metrics=[accuracy], callback_fns=ShowGraph) The learner object we create comes with a build-in function to find the optimal learning rate, or range of learning rates, for training. It achieves this by fitting the model for a few epochs and saving for which learning rates the loss decreases the most. We want to choose a learning rate, for which the loss is still decreasing, i.e. we do not want the learning rate with the minimum loss, but with the steepest slope. In the following plot, which is stored in the recorder object of our learner, we can see that this is the case for learning rates between 0.001 and 0.01. learner.lr_find()learner.recorder.plot() Now let’s fit our model for 8 epochs, with a learning rate between 0.001 and 0.01 learner.fit_one_cycle(8, max_lr=slice(1e-3, 1e-2)) That already looks good! The loss is decreasing a lot in the first few 1/5th of iterations, and less but continously afterwards. Let’s see where the algorithm is making the most mistakes: interpreter = ClassificationInterpretation.from_learner(learner)interpreter.most_confused(min_val=2)## OUTPUTS:[(‘Black-grass’, ‘Loose Silky-bent’, 28), (‘Loose Silky-bent’, ‘Black-grass’, 7), (‘Shepherd’s Purse’, ‘Scentless Mayweed’, 4)] This shows us that the algorithm confuses the classes ‘black-grass’ and ‘loose silky-bent’ most often. We already saw on the sample images we displayed earlier that these look the most alike, so this makes sense. Before we unfreeze the layers and learn again, we save the weights so that we can go back in case we mess up. learner.save(‘stage-1’)#learner.load(‘stage-1’)learner.unfreeze()learner.fit_one_cycle(12, max_lr=slice(1e-5, 1e-4)) We will stick to this, because the validation error is getting worse than the testing error, and it looks like this tendency will only increase. The model would start to overfit the training data if we continue training from this point onwards! Good job, we successfully trained a state-of-the-art image classifier for a custom dataset, achieving 96.5% accuracy in just a handful of lines of code! Sources[1] Fastai MOOC[2] Fastai library[3] Plant Seedling Dataset
[ { "code": null, "e": 544, "s": 47, "text": "I recently took a peek into Jeremy Howard’s 2019 course on deep learning. I never used the Fastai library before so I was pretty amazed by its level of abstraction that allows you to create stage-of-the-art neural networks in minutes, with a ridiculously tiny amount of code. In the following I will offer a short tutorial on building a CNN image classifier with Fastai that is supposed to act simultaneously as a helpful summary of the key concepts for myself and a clear overview for newcomers." }, { "code": null, "e": 616, "s": 544, "text": "I chose the plant seedling dataset from Kaggle as an examplary dataset." }, { "code": null, "e": 962, "s": 616, "text": "If you haven’t heard of Fastai yet I recommend taking a look at their homepage. In their mission statement it is stated that not only do they want to accelerate and help deep learning research, they also want to decrease the entry barriers for everyone. This line is from their introduction of PyTorch for Fastai back in September 2017 (Source):" }, { "code": null, "e": 1278, "s": 962, "text": "Everybody should be able to use deep learning to solve their problems with no more education than it takes to use a smart phone. Therefore, each year our main research goal is to be able to teach a wider range of deep learning applications, that run faster, and are more accurate, to people with less prerequisites." }, { "code": null, "e": 1709, "s": 1278, "text": "You can feel this ambition even if you watch Fastai's 2019 course, and it's something that gives me a good feeling about the direction the field is headed. As it often happens in research, knowledge and tools are only accessible to a certain minority. This is even more pronounced in deep learning research, where you need huge amounts of RAM in powerful GPUs to solve a lot of problems (check this unrelated video on GPU vs CPU)." }, { "code": null, "e": 2052, "s": 1709, "text": "In addition, support for Fastai is now offered on a lot of cloud computing platforms, like Paperspace, Cradle and AWS, just to name a few. But since these services all cost money, I will stick to Google's just recently announced Colaboratory, that let's you use Google's GPUs for free. Yes, zero cost! Ain't that incredible times to be alive?" }, { "code": null, "e": 2599, "s": 2052, "text": "To avoid redundancy online, please check this Medium post by Manikanta Yadunanda for a quick introduction on how to use the Google Colaboratory (Colab) with Fastai. Since this introduction was written, Google has included official Fastai and PyTorch support in Colab, so you probably don't even need to install it after connecting to a runtime. You can check with the following line of code if all of the important pip packages are installed. If not, uncomment the last line and use it to install Fastai and PyTorch for Python 3.6.x and CUDA 9.x." }, { "code": null, "e": 3030, "s": 2599, "text": "To access this notebook and run the computations yourself, you can simply import it directly from my GitHub repository. Just go to File... Open Notebook..., select the GitHub tab and enter ‘verrannt/Tutorials’ in the search bar. Select the ‘fastai-plant-seedlings-classification.ipynb’ and you’re done. Simple as that. After you checked that Colab is configured for Fastai support, you can continue with the data preperation part." }, { "code": null, "e": 3241, "s": 3030, "text": "Since we are using Kaggle as our dataset supply, you need a Kaggle account to download the dataset. If you got one, head over to your account settings and get a new API key which you can use for the Kaggle CLI." }, { "code": null, "e": 3435, "s": 3241, "text": "The following code installs the CLI and registers a new API key. We then download the plant seedling dataset and unzip it. Make sure that you are in the /content folder of the fastai directory." }, { "code": null, "e": 3668, "s": 3435, "text": "Let’s inspect the data. The folder we downloaded and extracted from Kaggle has 12 subfolders, each of which corresponds to one type of seedling with its respective images inside. These will be our labels for the classification task." }, { "code": null, "e": 4003, "s": 3668, "text": "If we print the lengths of the contents of these folders we can see that every folder contains a different amount of images. The differences are great, see e.g. that the ‘Loose Silky-bent’ has the most images (762) while the ‘Common Wheat’ the fewest (253). We will see later if this amounts to differences in the prediction accuracy." }, { "code": null, "e": 4031, "s": 4003, "text": "This outputs the following:" }, { "code": null, "e": 4349, "s": 4031, "text": "No. of labels: 12-----------------Small-flowered Cranesbill, 576 filesCommon wheat, 253 filesCharlock, 452 filesSugar beet, 463 filesMaize, 257 filesBlack-grass, 309 filesLoose Silky-bent, 762 filesFat Hen, 538 filesCleavers, 335 filesShepherd’s Purse, 274 filesScentless Mayweed, 607 filesCommon Chickweed, 713 files" }, { "code": null, "e": 4446, "s": 4349, "text": "Let’s have a look at those images. For each of the 12 labels, we will print one random seedling." }, { "code": null, "e": 4632, "s": 4446, "text": "Alright, they look good and quite distinguishable, except for ‘Loose Silky-bent’ and ‘Black-grass’. These might be harder for the network to recognize, but we will see. Let’s get to it!" }, { "code": null, "e": 4830, "s": 4632, "text": "We can now create the CNN model using the Fastai library. Since its major update to v1, it got a lot clearer and consistent, so we only need to import the vision module and accuracy for our metric." }, { "code": null, "e": 4893, "s": 4830, "text": "from fastai.vision import *from fastai.metrics import accuracy" }, { "code": null, "e": 5418, "s": 4893, "text": "Fastai has a really nice class for handling everything related to the input images for vision tasks. It is called ImageDataBunch and has different functions, respective of the different ways data can be presented to the network. Since our images are placed in folders whose names correspond to the image labels, we will use the ImageDataBunch.from_folder() function to create an object that contains our image data. This is super useful and makes it incredibly easy to read the data into our model, as you will see in a bit." }, { "code": null, "e": 5571, "s": 5418, "text": "What’s even more handy is that Fastai can automatically split our data into train and validation sets, so we don't even need to create these on our own." }, { "code": null, "e": 5865, "s": 5571, "text": "The only hyperparameters we need now are the path-variable pointing to our data set, the size of the inputs and the batch size for each gradient descent iteration. To make matters simple, the ImageDataBunch object will scale all images to a size*size squared image unless otherwise instructed." }, { "code": null, "e": 6175, "s": 5865, "text": "A quick note on image size: the bigger an image, the more details the CNN will be able to pick out of it. At the same time, a bigger image means longer computation times. On the same note it might be that your GPU runs out of memory for a too large batch size. You can half the batch size if this is the case." }, { "code": null, "e": 6225, "s": 6175, "text": "path = “./plant_seedlings-data/”size = 224bs = 64" }, { "code": null, "e": 6456, "s": 6225, "text": "We will create a variable called data in which we place the ImageDataBunch object. We create this object with the from_folder() function that we discussed above. Among the path to our data, the image and batch size, it also takes:" }, { "code": null, "e": 6567, "s": 6456, "text": "a function argument called get_transforms() which returns a list of available image transformations upon call." }, { "code": null, "e": 6686, "s": 6567, "text": "a parameter valid_pct which controls the percentage of images that will be randomly chosen to be in the validation set" }, { "code": null, "e": 6924, "s": 6686, "text": "a parameter flip_vert which controls vertical flips and 90° turns in addition to just horizontal flips. (Since our plant images are taken from above, we can perform those without a problem, which would not be feasible on e.g. face data.)" }, { "code": null, "e": 7377, "s": 6924, "text": "To normalize the data in our object, we simply call normalize() on the object. It is possible to use ImageNet, CIFAR or MNIST stats as templates here, and if left empty this function will simply grab a batch of data from our object and compute the stats on it (mean and standard-deviation) and normalize the data accordingly. Since we will be using a ResNet architecture for our model which was trained on ImageNet, we will be using the ImageNet stats." }, { "code": null, "e": 7408, "s": 7377, "text": "data.normalize(imagenet_stats)" }, { "code": null, "e": 7432, "s": 7408, "text": "This outputs a summary:" }, { "code": null, "e": 8213, "s": 7432, "text": "ImageDataBunch;Train: LabelListy: CategoryList (4432 items)[Category Small-flowered Cranesbill, Category Small-flowered Cranesbill, Category Small-flowered Cranesbill, Category Small-flowered Cranesbill, Category Small-flowered Cranesbill]...Path: plant-seedlings-datax: ImageItemList (4432 items)[Image (3, 237, 237), Image (3, 497, 497), Image (3, 94, 94), Image (3, 551, 551), Image (3, 246, 246)]...Path: plant-seedlings-data;Valid: LabelListy: CategoryList (1107 items)[Category Maize, Category Black-grass, Category Common Chickweed, Category Cleavers, Category Charlock]...Path: plant-seedlings-datax: ImageItemList (1107 items)[Image (3, 529, 529), Image (3, 945, 945), Image (3, 171, 171), Image (3, 125, 125), Image (3, 163, 163)]...Path: plant-seedlings-data;Test: None" }, { "code": null, "e": 8640, "s": 8213, "text": "That’s it, two lines of code for optimizing our dataset for training, adding different kinds of transformations and normalization! I would kindly ask you to stop here for a moment and just take a second to appreciate the beauty of this. The beauty of high-level libraries; just two lines of code and we have increased the diversity of our dataset tremendously. I can already hear my ugly batchnorm code crying in the trashbin." }, { "code": null, "e": 8739, "s": 8640, "text": "All that is left now is to create the actual network and train it, which could not be more simple." }, { "code": null, "e": 9105, "s": 8739, "text": "Fastai supplies us with a function called create_cnn() from its vision module. This function creates what is called a learner object, which we'll put into a properly named variable. See here that we specify the ResNet architecture as our base model for transfer learning. Upon call, the trained architecture will be downloaded via the Fastai API and stored locally." }, { "code": null, "e": 9417, "s": 9105, "text": "We will use accuracy for our metric. If you check the docs you can see a list of other metrics which are availabe. Defining the callback function ShowGraph simply tells the learner that it should return a graph for whatever it does, which seems very useful to me for seeing whether the model is still improving." }, { "code": null, "e": 9505, "s": 9417, "text": "learner = create_cnn(data, models.resnet18, metrics=[accuracy], callback_fns=ShowGraph)" }, { "code": null, "e": 9762, "s": 9505, "text": "The learner object we create comes with a build-in function to find the optimal learning rate, or range of learning rates, for training. It achieves this by fitting the model for a few epochs and saving for which learning rates the loss decreases the most." }, { "code": null, "e": 9927, "s": 9762, "text": "We want to choose a learning rate, for which the loss is still decreasing, i.e. we do not want the learning rate with the minimum loss, but with the steepest slope." }, { "code": null, "e": 10081, "s": 9927, "text": "In the following plot, which is stored in the recorder object of our learner, we can see that this is the case for learning rates between 0.001 and 0.01." }, { "code": null, "e": 10122, "s": 10081, "text": "learner.lr_find()learner.recorder.plot()" }, { "code": null, "e": 10204, "s": 10122, "text": "Now let’s fit our model for 8 epochs, with a learning rate between 0.001 and 0.01" }, { "code": null, "e": 10255, "s": 10204, "text": "learner.fit_one_cycle(8, max_lr=slice(1e-3, 1e-2))" }, { "code": null, "e": 10384, "s": 10255, "text": "That already looks good! The loss is decreasing a lot in the first few 1/5th of iterations, and less but continously afterwards." }, { "code": null, "e": 10443, "s": 10384, "text": "Let’s see where the algorithm is making the most mistakes:" }, { "code": null, "e": 10682, "s": 10443, "text": "interpreter = ClassificationInterpretation.from_learner(learner)interpreter.most_confused(min_val=2)## OUTPUTS:[(‘Black-grass’, ‘Loose Silky-bent’, 28), (‘Loose Silky-bent’, ‘Black-grass’, 7), (‘Shepherd’s Purse’, ‘Scentless Mayweed’, 4)]" }, { "code": null, "e": 10895, "s": 10682, "text": "This shows us that the algorithm confuses the classes ‘black-grass’ and ‘loose silky-bent’ most often. We already saw on the sample images we displayed earlier that these look the most alike, so this makes sense." }, { "code": null, "e": 11005, "s": 10895, "text": "Before we unfreeze the layers and learn again, we save the weights so that we can go back in case we mess up." }, { "code": null, "e": 11122, "s": 11005, "text": "learner.save(‘stage-1’)#learner.load(‘stage-1’)learner.unfreeze()learner.fit_one_cycle(12, max_lr=slice(1e-5, 1e-4))" }, { "code": null, "e": 11367, "s": 11122, "text": "We will stick to this, because the validation error is getting worse than the testing error, and it looks like this tendency will only increase. The model would start to overfit the training data if we continue training from this point onwards!" }, { "code": null, "e": 11520, "s": 11367, "text": "Good job, we successfully trained a state-of-the-art image classifier for a custom dataset, achieving 96.5% accuracy in just a handful of lines of code!" } ]
Fortran - select case construct
A select case statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being selected on is checked for each select case. The syntax for the select case construct is as follows − [name:] select case (expression) case (selector1) ! some statements ... case (selector2) ! other statements ... case default ! more statements ... end select [name] The following rules apply to a select statement − The logical expression used in a select statement could be logical, character, or integer (but not real) expression. The logical expression used in a select statement could be logical, character, or integer (but not real) expression. You can have any number of case statements within a select. Each case is followed by the value to be compared to and could be logical, character, or integer (but not real) expression and determines which statements are executed. You can have any number of case statements within a select. Each case is followed by the value to be compared to and could be logical, character, or integer (but not real) expression and determines which statements are executed. The constant-expression for a case, must be the same data type as the variable in the select, and it must be a constant or a literal. The constant-expression for a case, must be the same data type as the variable in the select, and it must be a constant or a literal. When the variable being selected on, is equal to a case, the statements following that case will execute until the next case statement is reached. When the variable being selected on, is equal to a case, the statements following that case will execute until the next case statement is reached. The case default block is executed if the expression in select case (expression) does not match any of the selectors. The case default block is executed if the expression in select case (expression) does not match any of the selectors. program selectCaseProg implicit none ! local variable declaration character :: grade = 'B' select case (grade) case ('A') print*, "Excellent!" case ('B') case ('C') print*, "Well done" case ('D') print*, "You passed" case ('F') print*, "Better try again" case default print*, "Invalid grade" end select print*, "Your grade is ", grade end program selectCaseProg When the above code is compiled and executed, it produces the following result − Your grade is B You can specify a range for the selector, by specifying a lower and upper limit separated by a colon − case (low:high) The following example demonstrates this − program selectCaseProg implicit none ! local variable declaration integer :: marks = 78 select case (marks) case (91:100) print*, "Excellent!" case (81:90) print*, "Very good!" case (71:80) print*, "Well done!" case (61:70) print*, "Not bad!" case (41:60) print*, "You passed!" case (:40) print*, "Better try again!" case default print*, "Invalid marks" end select print*, "Your marks is ", marks end program selectCaseProg When the above code is compiled and executed, it produces the following result − Well done! Your marks is 78 Print Add Notes Bookmark this page
[ { "code": null, "e": 2337, "s": 2146, "text": "A select case statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being selected on is checked for each select case." }, { "code": null, "e": 2394, "s": 2337, "text": "The syntax for the select case construct is as follows −" }, { "code": null, "e": 2657, "s": 2394, "text": "[name:] select case (expression) \n case (selector1) \n ! some statements \n ... case (selector2) \n ! other statements \n ... \n case default \n ! more statements \n ... \nend select [name]\n" }, { "code": null, "e": 2707, "s": 2657, "text": "The following rules apply to a select statement −" }, { "code": null, "e": 2824, "s": 2707, "text": "The logical expression used in a select statement could be logical, character, or integer (but not real) expression." }, { "code": null, "e": 2941, "s": 2824, "text": "The logical expression used in a select statement could be logical, character, or integer (but not real) expression." }, { "code": null, "e": 3170, "s": 2941, "text": "You can have any number of case statements within a select. Each case is followed by the value to be compared to and could be logical, character, or integer (but not real) expression and determines which statements are executed." }, { "code": null, "e": 3399, "s": 3170, "text": "You can have any number of case statements within a select. Each case is followed by the value to be compared to and could be logical, character, or integer (but not real) expression and determines which statements are executed." }, { "code": null, "e": 3533, "s": 3399, "text": "The constant-expression for a case, must be the same data type as the variable in the select, and it must be a constant or a literal." }, { "code": null, "e": 3667, "s": 3533, "text": "The constant-expression for a case, must be the same data type as the variable in the select, and it must be a constant or a literal." }, { "code": null, "e": 3814, "s": 3667, "text": "When the variable being selected on, is equal to a case, the statements following that case will execute until the next case statement is reached." }, { "code": null, "e": 3961, "s": 3814, "text": "When the variable being selected on, is equal to a case, the statements following that case will execute until the next case statement is reached." }, { "code": null, "e": 4079, "s": 3961, "text": "The case default block is executed if the expression in select case (expression) does not match any of the selectors." }, { "code": null, "e": 4197, "s": 4079, "text": "The case default block is executed if the expression in select case (expression) does not match any of the selectors." }, { "code": null, "e": 4690, "s": 4197, "text": "program selectCaseProg\nimplicit none\n\n ! local variable declaration\n character :: grade = 'B'\n\n select case (grade)\n \n case ('A') \n print*, \"Excellent!\" \n\n case ('B')\n \n case ('C') \n print*, \"Well done\" \n\n case ('D')\n print*, \"You passed\" \n\n case ('F')\n print*, \"Better try again\" \n\n case default\n print*, \"Invalid grade\" \n \n end select\n \n print*, \"Your grade is \", grade \n \nend program selectCaseProg" }, { "code": null, "e": 4771, "s": 4690, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4788, "s": 4771, "text": "Your grade is B\n" }, { "code": null, "e": 4891, "s": 4788, "text": "You can specify a range for the selector, by specifying a lower and upper limit separated by a colon −" }, { "code": null, "e": 4908, "s": 4891, "text": "case (low:high) " }, { "code": null, "e": 4950, "s": 4908, "text": "The following example demonstrates this −" }, { "code": null, "e": 5528, "s": 4950, "text": "program selectCaseProg\nimplicit none\n\n ! local variable declaration\n integer :: marks = 78\n\n select case (marks)\n \n case (91:100) \n print*, \"Excellent!\" \n\n case (81:90)\n print*, \"Very good!\"\n\n case (71:80) \n print*, \"Well done!\" \n\n case (61:70)\n print*, \"Not bad!\" \n\n case (41:60)\n print*, \"You passed!\" \n\n case (:40)\n print*, \"Better try again!\" \n\n case default\n print*, \"Invalid marks\" \n \n end select\n print*, \"Your marks is \", marks\n \nend program selectCaseProg" }, { "code": null, "e": 5609, "s": 5528, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5638, "s": 5609, "text": "Well done!\nYour marks is 78\n" }, { "code": null, "e": 5645, "s": 5638, "text": " Print" }, { "code": null, "e": 5656, "s": 5645, "text": " Add Notes" } ]
The Fastest Way to Visualize Correlation in Python | by Roman Orac | Towards Data Science
As a Data Scientist, I use correlation frequently to calculate and visualize relationships between features. I used to start by importing matplotlib and seaborn packages, which render a good-looking plot. But it’s cumbersome to import both packages just to visualize the correlation when starting with an empty Jupyter Notebook. I decided to do a bit of research, because of the frequency I use this command,— there has to be a better (quicker) way of visualizing correlation in Python. Voila, and there is... By reading this short tutorial, you’ll learn a quicker way to calculate and visualize correlation with pandas. Here are few links that might interest you: - Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course] Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything. Let’s say we have the following DataFrame (it just has 4 columns with random numbers): import numpy as npimport pandas as pddf = pd.DataFrame(np.random.randint(0, 100, size=(15, 4)), columns=list("ABCD")) Calculating and visualizing correlation is as simple as (no other third party packages required): df.corr().style.background_gradient(cmap="Blues") Before we delve deeper into other types of correlations, I have to admit, I never used any other than Pearson correlation in practice. Regardless, It’s good to know that others do exist and pandas supports a few of them out of the box. Let me know in the comments if you’ve used any other than Pearson correlation in practice and what was the use case. By default, pandas calculates Pearson correlation, which is a measure of linear correlation between two sets of data. Pandas also supports: Kendall correlation — use it with df.corr(‘kendall’) Spearman correlation — use it with df.corr(‘spearman’) From minitab: Spearman correlation is often used to evaluate relationships involving ordinal variables. For example, you might use a Spearman correlation to evaluate whether the order in which employees complete a test exercise is related to the number of months they have been employed. From Stats Direct: Spearman’s rank correlation is satisfactory for testing a null hypothesis of independence between two variables but it is difficult to interpret when the null hypothesis is rejected. Kendall’s rank correlation improves upon this by reflecting the strength of the dependence between the variables being compared. As expected, Spearman correlation produces different values than Pearson: df.corr('spearman').style.background_gradient(cmap="Blues") To visualize correlation without using other packages is a neat trick, which makes practicing Data Science slightly more enjoyable. One such command might not seem much, but adding 10 such tricks in your toolbox can make a big difference. Applying style.background_gradient to correlation results is just the tip of the iceberg. This concept is useful for much, some of the things I already described in: towardsdatascience.com Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.
[ { "code": null, "e": 156, "s": 47, "text": "As a Data Scientist, I use correlation frequently to calculate and visualize relationships between features." }, { "code": null, "e": 376, "s": 156, "text": "I used to start by importing matplotlib and seaborn packages, which render a good-looking plot. But it’s cumbersome to import both packages just to visualize the correlation when starting with an empty Jupyter Notebook." }, { "code": null, "e": 557, "s": 376, "text": "I decided to do a bit of research, because of the frequency I use this command,— there has to be a better (quicker) way of visualizing correlation in Python. Voila, and there is..." }, { "code": null, "e": 668, "s": 557, "text": "By reading this short tutorial, you’ll learn a quicker way to calculate and visualize correlation with pandas." }, { "code": null, "e": 712, "s": 668, "text": "Here are few links that might interest you:" }, { "code": null, "e": 890, "s": 712, "text": "- Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course]" }, { "code": null, "e": 1061, "s": 890, "text": "Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything." }, { "code": null, "e": 1148, "s": 1061, "text": "Let’s say we have the following DataFrame (it just has 4 columns with random numbers):" }, { "code": null, "e": 1266, "s": 1148, "text": "import numpy as npimport pandas as pddf = pd.DataFrame(np.random.randint(0, 100, size=(15, 4)), columns=list(\"ABCD\"))" }, { "code": null, "e": 1364, "s": 1266, "text": "Calculating and visualizing correlation is as simple as (no other third party packages required):" }, { "code": null, "e": 1414, "s": 1364, "text": "df.corr().style.background_gradient(cmap=\"Blues\")" }, { "code": null, "e": 1650, "s": 1414, "text": "Before we delve deeper into other types of correlations, I have to admit, I never used any other than Pearson correlation in practice. Regardless, It’s good to know that others do exist and pandas supports a few of them out of the box." }, { "code": null, "e": 1767, "s": 1650, "text": "Let me know in the comments if you’ve used any other than Pearson correlation in practice and what was the use case." }, { "code": null, "e": 1885, "s": 1767, "text": "By default, pandas calculates Pearson correlation, which is a measure of linear correlation between two sets of data." }, { "code": null, "e": 1907, "s": 1885, "text": "Pandas also supports:" }, { "code": null, "e": 1960, "s": 1907, "text": "Kendall correlation — use it with df.corr(‘kendall’)" }, { "code": null, "e": 2015, "s": 1960, "text": "Spearman correlation — use it with df.corr(‘spearman’)" }, { "code": null, "e": 2029, "s": 2015, "text": "From minitab:" }, { "code": null, "e": 2303, "s": 2029, "text": "Spearman correlation is often used to evaluate relationships involving ordinal variables. For example, you might use a Spearman correlation to evaluate whether the order in which employees complete a test exercise is related to the number of months they have been employed." }, { "code": null, "e": 2322, "s": 2303, "text": "From Stats Direct:" }, { "code": null, "e": 2634, "s": 2322, "text": "Spearman’s rank correlation is satisfactory for testing a null hypothesis of independence between two variables but it is difficult to interpret when the null hypothesis is rejected. Kendall’s rank correlation improves upon this by reflecting the strength of the dependence between the variables being compared." }, { "code": null, "e": 2708, "s": 2634, "text": "As expected, Spearman correlation produces different values than Pearson:" }, { "code": null, "e": 2768, "s": 2708, "text": "df.corr('spearman').style.background_gradient(cmap=\"Blues\")" }, { "code": null, "e": 2900, "s": 2768, "text": "To visualize correlation without using other packages is a neat trick, which makes practicing Data Science slightly more enjoyable." }, { "code": null, "e": 3007, "s": 2900, "text": "One such command might not seem much, but adding 10 such tricks in your toolbox can make a big difference." }, { "code": null, "e": 3173, "s": 3007, "text": "Applying style.background_gradient to correlation results is just the tip of the iceberg. This concept is useful for much, some of the things I already described in:" }, { "code": null, "e": 3196, "s": 3173, "text": "towardsdatascience.com" } ]
How to remove partial string after a special character in R?
Sometimes we don’t require the whole string to proceed with the analysis, especially when it complicates the analysis or making no sense. In such type of situations, the part of string which we feel that is not necessary can be removed from the complete string. For example, suppose we have a string ID:00001-1 but we don’t want -1 in this string then we can remove it and this can be done with the help of gsub function. > x1<-c("ID:00001-1","ID:00100-1","ID:00201-4","ID:014700-3","ID:12045-5","ID:00012-2","ID:10078-3") > gsub("\\-.*","",x1) [1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078" > x2<-c("ID:00001/1","ID:00100/1","ID:00201/4","ID:014700/3","ID:12045/5","ID:00012/2","ID:10078/3") > gsub("\\/.*","",x2) [1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078" > x3<-c("ID:00001_1","ID:00100_1","ID:00201_4","ID:014700_3","ID:12045_5","ID:00012_2","ID:10078_3") > gsub("\\_.*","",x3) [1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078" > x4<-c("ID:00001@1","ID:00100@1","ID:00201@4","ID:014700@3","ID:12045@5","ID:00012@2","ID:10078@3") > gsub("\\@.*","",x4) [1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078" > x5<-c("ID:00001*1","ID:00100*1","ID:00201*4","ID:014700*3","ID:12045*5","ID:00012*2","ID:10078*3") > gsub("\\*.*","",x5) [1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078" > x6<-c("ID:00001#1","ID:00100#1","ID:00201#4","ID:014700#3","ID:12045#5","ID:00012#2","ID:10078#3") > gsub("\\#.*","",x6) [1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078" > x7<-c("ID:00001()1","ID:00100()1","ID:00201()4","ID:014700()3","ID:12045()5","ID:00012()2","ID:10078()3") > gsub("\\().*","",x7) [1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078" > x8<-c("ID:00001<>1","ID:00100<>1","ID:00201<>4","ID:014700<>3","ID:12045<>5","ID:00012<>2","ID:10078<>3") > gsub("\\<>.*","",x8) [1] "ID:00001<>1" "ID:00100<>1" "ID:00201<>4" "ID:014700<>3" "ID:12045<>5" "ID:00012<>2" "ID:10078<>3" > x9<-c("ID:00001&1","ID:00100&1","ID:00201&4","ID:014700&3","ID:12045&5","ID:00012&2","ID:10078&3") > gsub("\\&.*","",x9) [1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078" > x10<-c("ID:00001;1","ID:00100;1","ID:00201;4","ID:014700;3","ID:12045;5","ID:00012;2","ID:10078;3") > gsub("\\;.*","",x10) [1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078"
[ { "code": null, "e": 1484, "s": 1062, "text": "Sometimes we don’t require the whole string to proceed with the analysis, especially when it complicates the analysis or making no sense. In such type of situations, the part of string which we feel that is not necessary can be removed from the complete string. For example, suppose we have a string ID:00001-1 but we don’t want -1 in this string then we can remove it and this can be done with the help of gsub function." }, { "code": null, "e": 3573, "s": 1484, "text": "> x1<-c(\"ID:00001-1\",\"ID:00100-1\",\"ID:00201-4\",\"ID:014700-3\",\"ID:12045-5\",\"ID:00012-2\",\"ID:10078-3\")\n> gsub(\"\\\\-.*\",\"\",x1)\n[1] \"ID:00001\" \"ID:00100\" \"ID:00201\" \"ID:014700\" \"ID:12045\" \"ID:00012\" \"ID:10078\"\n> x2<-c(\"ID:00001/1\",\"ID:00100/1\",\"ID:00201/4\",\"ID:014700/3\",\"ID:12045/5\",\"ID:00012/2\",\"ID:10078/3\")\n> gsub(\"\\\\/.*\",\"\",x2)\n[1] \"ID:00001\" \"ID:00100\" \"ID:00201\" \"ID:014700\" \"ID:12045\" \"ID:00012\" \"ID:10078\"\n> x3<-c(\"ID:00001_1\",\"ID:00100_1\",\"ID:00201_4\",\"ID:014700_3\",\"ID:12045_5\",\"ID:00012_2\",\"ID:10078_3\")\n> gsub(\"\\\\_.*\",\"\",x3)\n[1] \"ID:00001\" \"ID:00100\" \"ID:00201\" \"ID:014700\" \"ID:12045\" \"ID:00012\" \"ID:10078\"\n> x4<-c(\"ID:00001@1\",\"ID:00100@1\",\"ID:00201@4\",\"ID:014700@3\",\"ID:12045@5\",\"ID:00012@2\",\"ID:10078@3\")\n> gsub(\"\\\\@.*\",\"\",x4)\n[1] \"ID:00001\" \"ID:00100\" \"ID:00201\" \"ID:014700\" \"ID:12045\" \"ID:00012\" \"ID:10078\"\n> x5<-c(\"ID:00001*1\",\"ID:00100*1\",\"ID:00201*4\",\"ID:014700*3\",\"ID:12045*5\",\"ID:00012*2\",\"ID:10078*3\")\n> gsub(\"\\\\*.*\",\"\",x5)\n[1] \"ID:00001\" \"ID:00100\" \"ID:00201\" \"ID:014700\" \"ID:12045\" \"ID:00012\" \"ID:10078\"\n> x6<-c(\"ID:00001#1\",\"ID:00100#1\",\"ID:00201#4\",\"ID:014700#3\",\"ID:12045#5\",\"ID:00012#2\",\"ID:10078#3\")\n> gsub(\"\\\\#.*\",\"\",x6)\n[1] \"ID:00001\" \"ID:00100\" \"ID:00201\" \"ID:014700\" \"ID:12045\" \"ID:00012\" \"ID:10078\"\n> x7<-c(\"ID:00001()1\",\"ID:00100()1\",\"ID:00201()4\",\"ID:014700()3\",\"ID:12045()5\",\"ID:00012()2\",\"ID:10078()3\")\n> gsub(\"\\\\().*\",\"\",x7)\n[1] \"ID:00001\" \"ID:00100\" \"ID:00201\" \"ID:014700\" \"ID:12045\" \"ID:00012\" \"ID:10078\"\n> x8<-c(\"ID:00001<>1\",\"ID:00100<>1\",\"ID:00201<>4\",\"ID:014700<>3\",\"ID:12045<>5\",\"ID:00012<>2\",\"ID:10078<>3\")\n> gsub(\"\\\\<>.*\",\"\",x8)\n[1] \"ID:00001<>1\" \"ID:00100<>1\" \"ID:00201<>4\" \"ID:014700<>3\" \"ID:12045<>5\" \"ID:00012<>2\" \"ID:10078<>3\"\n> x9<-c(\"ID:00001&1\",\"ID:00100&1\",\"ID:00201&4\",\"ID:014700&3\",\"ID:12045&5\",\"ID:00012&2\",\"ID:10078&3\")\n> gsub(\"\\\\&.*\",\"\",x9)\n[1] \"ID:00001\" \"ID:00100\" \"ID:00201\" \"ID:014700\" \"ID:12045\" \"ID:00012\" \"ID:10078\"\n> x10<-c(\"ID:00001;1\",\"ID:00100;1\",\"ID:00201;4\",\"ID:014700;3\",\"ID:12045;5\",\"ID:00012;2\",\"ID:10078;3\")\n> gsub(\"\\\\;.*\",\"\",x10)\n[1] \"ID:00001\" \"ID:00100\" \"ID:00201\" \"ID:014700\" \"ID:12045\" \"ID:00012\" \"ID:10078\"" } ]
What is OpenMP?
OpenMP is a set of compiler directives as well as an API for programs written in C, C++, or FORTRAN that provides support for parallel programming in shared-memory environments. OpenMP identifies parallel regions as blocks of code that may run in parallel. Application developers insert compiler directives into their code at parallel regions, and these directives instruct the OpenMP run-time library to execute the region in parallel. The following C program illustrates a compiler directive above the parallel region containing the printf() statement − #include <omp.h> #include <stdio.h> int main(int argc, char *argv[]){ /* sequential code */ #pragma omp parallel{ printf("I am a parallel region."); } /* sequential code */ return 0; } When OpenMP encounters the directive #pragma omp parallel It creates as many threads which are processing cores in the system. Thus, for a dual-core system, two threads are created, for a quad-core system, four are created; and so forth. Then all the threads simultaneously execute the parallel region. When each thread exits the parallel region, it is terminated. OpenMP provides several additional directives for running code regions in parallel, including parallelizing loops. In addition to providing directives for parallelization, OpenMP allows developers to choose among several levels of parallelism. E.g., they can set the number of threads manually. It also allows developers to identify whether data are shared between threads or are private to a thread. OpenMP is available on several open-source and commercial compilers for Linux, Windows, and Mac OS X systems.
[ { "code": null, "e": 1618, "s": 1062, "text": "OpenMP is a set of compiler directives as well as an API for programs written in C, C++, or FORTRAN that provides support for parallel programming in shared-memory environments. OpenMP identifies parallel regions as blocks of code that may run in parallel. Application developers insert compiler directives into their code at parallel regions, and these directives instruct the OpenMP run-time library to execute the region in parallel. The following C program illustrates a compiler directive above the parallel region containing the printf() statement −" }, { "code": null, "e": 1824, "s": 1618, "text": "#include <omp.h>\n#include <stdio.h>\nint main(int argc, char *argv[]){\n /* sequential code */\n #pragma omp parallel{\n printf(\"I am a parallel region.\");\n }\n /* sequential code */\n return 0;\n}" }, { "code": null, "e": 1861, "s": 1824, "text": "When OpenMP encounters the directive" }, { "code": null, "e": 1882, "s": 1861, "text": "#pragma omp parallel" }, { "code": null, "e": 2304, "s": 1882, "text": "It creates as many threads which are processing cores in the system. Thus, for a dual-core system, two threads are created, for a quad-core system, four are created; and so forth. Then all the threads simultaneously execute the parallel region. When each thread exits the parallel region, it is terminated. OpenMP provides several additional directives for running code regions in parallel, including parallelizing loops." }, { "code": null, "e": 2700, "s": 2304, "text": "In addition to providing directives for parallelization, OpenMP allows developers to choose among several levels of parallelism. E.g., they can set the number of threads manually. It also allows developers to identify whether data are shared between threads or are private to a thread. OpenMP is available on several open-source and commercial compilers for Linux, Windows, and Mac OS X systems." } ]
Nagios - Checks and States
Once the host and services are configured on Nagios, checks are used to see if the hosts and services are working as they are supposed to or not. Let us see an example to perform checks on host − Consider that you have put your host definitions inside host1.cfg file in /usr/local/nagios/etc/objects directory. cd /usr/local/nagios/etc/objects gedit host1.cfg This is how your host definitions look currently − define host { host_name host1 address 10.0.0.1 } Now let us add check_interval directive. This directive is used to perform scheduled checks of the hosts for the number you set; by default it is in minutes. Using the definition below, checks on the host will be performed after every 3 minutes. define host { host_name host1 address 10.0.0.1 check_interval 3 } In Nagios, 2 types of checks are performed on hosts and services − Active Checks Passive Checks Active checks are initiated by Nagios process and then run on a regular scheduled basis. The check logic inside Nagios process starts the Active check. To monitor hosts and services running on remote machines, Nagios executes plugins and tells what information to collect. Plugin then gets executed on the remote machine where is collects the required information and sends then back to Nagios daemon. Depending on the status received on hosts and services, appropriate action is taken. The figure shown below shows an active check − These are executed on regular intervals, as defined by check_interval and retry_interval. Passive checks are performed by external processes and the results are given back to Nagios for processing. Passive checks work as explained here − An external application checks the status on hosts/services and writes the result to External Command File. When Nagios daemon reads external command file, it reads and sends all the passive checks in the queue to process them later. Periodically when these checks are processed, notifications or alerts are sent depending on the information in check result. The figure shown below shows a passive check − Thus, the difference between active and passive check is that active checks are run by Nagios and passive checks are run by external applications. These checks are useful when you cannot monitor hosts/services on a regular basis. Nagios stores the status of the hosts and services it is monitoring to determine if they are working properly or not. There would be many cases when the failures will happen randomly and they are temporary; hence Nagios uses states to check the current status of a host or service. There are two types of states − Soft state Hard state When a host or service is down for a very short duration of time and its status is not known or different from previous one, then soft states are used. The host or the services will be tested again and again till the time the status is permanent. When max_check_attempts is executed and status of the host or service is still not OK, then hard state is used. Nagios executes event handlers to handle hard states. The following figure shows soft states and hard states. Print Add Notes Bookmark this page
[ { "code": null, "e": 2092, "s": 1896, "text": "Once the host and services are configured on Nagios, checks are used to see if the hosts and services are working as they are supposed to or not. Let us see an example to perform checks on host −" }, { "code": null, "e": 2207, "s": 2092, "text": "Consider that you have put your host definitions inside host1.cfg file in /usr/local/nagios/etc/objects directory." }, { "code": null, "e": 2257, "s": 2207, "text": "cd /usr/local/nagios/etc/objects\ngedit host1.cfg\n" }, { "code": null, "e": 2308, "s": 2257, "text": "This is how your host definitions look currently −" }, { "code": null, "e": 2364, "s": 2308, "text": "define host {\n host_name host1\n address 10.0.0.1\n}\n" }, { "code": null, "e": 2610, "s": 2364, "text": "Now let us add check_interval directive. This directive is used to perform scheduled checks of the hosts for the number you set; by default it is in minutes. Using the definition below, checks on the host will be performed after every 3 minutes." }, { "code": null, "e": 2686, "s": 2610, "text": "define host {\n host_name host1\n address 10.0.0.1\n check_interval 3\n}\n" }, { "code": null, "e": 2753, "s": 2686, "text": "In Nagios, 2 types of checks are performed on hosts and services −" }, { "code": null, "e": 2767, "s": 2753, "text": "Active Checks" }, { "code": null, "e": 2782, "s": 2767, "text": "Passive Checks" }, { "code": null, "e": 3269, "s": 2782, "text": "Active checks are initiated by Nagios process and then run on a regular scheduled basis. The check logic inside Nagios process starts the Active check. To monitor hosts and services running on remote machines, Nagios executes plugins and tells what information to collect. Plugin then gets executed on the remote machine where is collects the required information and sends then back to Nagios daemon. Depending on the status received on hosts and services, appropriate action is taken." }, { "code": null, "e": 3316, "s": 3269, "text": "The figure shown below shows an active check −" }, { "code": null, "e": 3406, "s": 3316, "text": "These are executed on regular intervals, as defined by check_interval and retry_interval." }, { "code": null, "e": 3514, "s": 3406, "text": "Passive checks are performed by external processes and the results are given back to Nagios for processing." }, { "code": null, "e": 3554, "s": 3514, "text": "Passive checks work as explained here −" }, { "code": null, "e": 3913, "s": 3554, "text": "An external application checks the status on hosts/services and writes the result to External Command File. When Nagios daemon reads external command file, it reads and sends all the passive checks in the queue to process them later. Periodically when these checks are processed, notifications or alerts are sent depending on the information in check result." }, { "code": null, "e": 3960, "s": 3913, "text": "The figure shown below shows a passive check −" }, { "code": null, "e": 4107, "s": 3960, "text": "Thus, the difference between active and passive check is that active checks are run by Nagios and passive checks are run by external applications." }, { "code": null, "e": 4190, "s": 4107, "text": "These checks are useful when you cannot monitor hosts/services on a regular basis." }, { "code": null, "e": 4472, "s": 4190, "text": "Nagios stores the status of the hosts and services it is monitoring to determine if they are working properly or not. There would be many cases when the failures will happen randomly and they are temporary; hence Nagios uses states to check the current status of a host or service." }, { "code": null, "e": 4504, "s": 4472, "text": "There are two types of states −" }, { "code": null, "e": 4515, "s": 4504, "text": "Soft state" }, { "code": null, "e": 4526, "s": 4515, "text": "Hard state" }, { "code": null, "e": 4773, "s": 4526, "text": "When a host or service is down for a very short duration of time and its status is not known or different from previous one, then soft states are used. The host or the services will be tested again and again till the time the status is permanent." }, { "code": null, "e": 4939, "s": 4773, "text": "When max_check_attempts is executed and status of the host or service is still not OK, then hard state is used. Nagios executes event handlers to handle hard states." }, { "code": null, "e": 4995, "s": 4939, "text": "The following figure shows soft states and hard states." }, { "code": null, "e": 5002, "s": 4995, "text": " Print" }, { "code": null, "e": 5013, "s": 5002, "text": " Add Notes" } ]
C - strtok function
C - Programming HOME C - Basic Introduction C - Program Structure C - Reserved Keywords C - Basic Datatypes C - Variable Types C - Storage Classes C - Using Constants C - Operator Types C - Control Statements C - Input and Output C - Pointing to Data C - Using Functions C - Play with Strings C - Structured Datatypes C - Working with Files C - Bits Manipulation C - Pre-Processors C - Useful Concepts C - Built-in Functions C - Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint #include <stdio.h> char *strtok(char *s, const char *delim) ; A sequence of calls to this function split str into tokens, which are sequences of contiguous characters spearated by any of the characters that are part of delimiters. On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning. To determine the beginning and the end of a token, the function first scans from the starting location for the first character not contained in separator (which becomes the beginning of the token). And then scans starting from this beginning of the token for the first character contained in separator, which becomes the end of the token. This end of the token is automatically replaced by a null-character by the function, and the beginning of the token is returned by the function. A pointer to the last token found in string. A pointer to the last token found in string. A null pointer is returned if there are no tokens left to retrieve. A null pointer is returned if there are no tokens left to retrieve. #include <stdio.h> int main () { char str[] ="- This, a sample string."; char * pch; printf ("Splitting string \"%s\" into tokens:\n",str); pch = strtok (str," ,.-"); while (pch != NULL) { printf ("%s\n",pch); pch = strtok (NULL, " ,.-"); } return 0; } It will proiduce following result: Splitting string "- This, a sample string." into tokens: This a sample string Advertisements 6 Lectures 1.5 hours Mr. Pradeep Kshetrapal 41 Lectures 5 hours AR Shankar 11 Lectures 58 mins Musab Zayadneh 59 Lectures 15.5 hours Narendra P 11 Lectures 1 hours Sagar Mehta 39 Lectures 4 hours Vikas Yadav Print Add Notes Bookmark this page
[ { "code": null, "e": 1475, "s": 1454, "text": "C - Programming HOME" }, { "code": null, "e": 1498, "s": 1475, "text": "C - Basic Introduction" }, { "code": null, "e": 1520, "s": 1498, "text": "C - Program Structure" }, { "code": null, "e": 1542, "s": 1520, "text": "C - Reserved Keywords" }, { "code": null, "e": 1562, "s": 1542, "text": "C - Basic Datatypes" }, { "code": null, "e": 1581, "s": 1562, "text": "C - Variable Types" }, { "code": null, "e": 1601, "s": 1581, "text": "C - Storage Classes" }, { "code": null, "e": 1621, "s": 1601, "text": "C - Using Constants" }, { "code": null, "e": 1640, "s": 1621, "text": "C - Operator Types" }, { "code": null, "e": 1663, "s": 1640, "text": "C - Control Statements" }, { "code": null, "e": 1684, "s": 1663, "text": "C - Input and Output" }, { "code": null, "e": 1705, "s": 1684, "text": "C - Pointing to Data" }, { "code": null, "e": 1725, "s": 1705, "text": "C - Using Functions" }, { "code": null, "e": 1747, "s": 1725, "text": "C - Play with Strings" }, { "code": null, "e": 1772, "s": 1747, "text": "C - Structured Datatypes" }, { "code": null, "e": 1795, "s": 1772, "text": "C - Working with Files" }, { "code": null, "e": 1817, "s": 1795, "text": "C - Bits Manipulation" }, { "code": null, "e": 1836, "s": 1817, "text": "C - Pre-Processors" }, { "code": null, "e": 1856, "s": 1836, "text": "C - Useful Concepts" }, { "code": null, "e": 1879, "s": 1856, "text": "C - Built-in Functions" }, { "code": null, "e": 1900, "s": 1879, "text": "C - Useful Resources" }, { "code": null, "e": 1918, "s": 1900, "text": "Computer Glossary" }, { "code": null, "e": 1929, "s": 1918, "text": "Who is Who" }, { "code": null, "e": 1964, "s": 1929, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2028, "s": 1964, "text": "#include <stdio.h>\n\nchar *strtok(char *s, const char *delim) ;\n" }, { "code": null, "e": 2197, "s": 2028, "text": "A sequence of calls to this function split str into tokens, which are sequences of contiguous characters spearated by any of the characters that are part of delimiters." }, { "code": null, "e": 2498, "s": 2197, "text": "On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning." }, { "code": null, "e": 2837, "s": 2498, "text": "To determine the beginning and the end of a token, the function first scans from the starting location for the first character not contained in separator (which becomes the beginning of the token). And then scans starting from this beginning of the token for the first character contained in separator, which becomes the end of the token." }, { "code": null, "e": 2982, "s": 2837, "text": "This end of the token is automatically replaced by a null-character by the function, and the beginning of the token is returned by the function." }, { "code": null, "e": 3027, "s": 2982, "text": "A pointer to the last token found in string." }, { "code": null, "e": 3072, "s": 3027, "text": "A pointer to the last token found in string." }, { "code": null, "e": 3140, "s": 3072, "text": "A null pointer is returned if there are no tokens left to retrieve." }, { "code": null, "e": 3208, "s": 3140, "text": "A null pointer is returned if there are no tokens left to retrieve." }, { "code": null, "e": 3487, "s": 3208, "text": "#include <stdio.h>\n\nint main ()\n{\n char str[] =\"- This, a sample string.\";\n char * pch;\n printf (\"Splitting string \\\"%s\\\" into tokens:\\n\",str);\n pch = strtok (str,\" ,.-\");\n while (pch != NULL)\n {\n printf (\"%s\\n\",pch);\n pch = strtok (NULL, \" ,.-\");\n }\n return 0;\n}\n" }, { "code": null, "e": 3522, "s": 3487, "text": "It will proiduce following result:" }, { "code": null, "e": 3601, "s": 3522, "text": "Splitting string \"- This, a sample string.\" into tokens:\nThis\na\nsample\nstring\n" }, { "code": null, "e": 3618, "s": 3601, "text": "\nAdvertisements\n" }, { "code": null, "e": 3652, "s": 3618, "text": "\n 6 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3676, "s": 3652, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 3709, "s": 3676, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 3721, "s": 3709, "text": " AR Shankar" }, { "code": null, "e": 3753, "s": 3721, "text": "\n 11 Lectures \n 58 mins\n" }, { "code": null, "e": 3769, "s": 3753, "text": " Musab Zayadneh" }, { "code": null, "e": 3805, "s": 3769, "text": "\n 59 Lectures \n 15.5 hours \n" }, { "code": null, "e": 3817, "s": 3805, "text": " Narendra P" }, { "code": null, "e": 3850, "s": 3817, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 3863, "s": 3850, "text": " Sagar Mehta" }, { "code": null, "e": 3896, "s": 3863, "text": "\n 39 Lectures \n 4 hours \n" }, { "code": null, "e": 3909, "s": 3896, "text": " Vikas Yadav" }, { "code": null, "e": 3916, "s": 3909, "text": " Print" }, { "code": null, "e": 3927, "s": 3916, "text": " Add Notes" } ]
How to implement Kohonen’s Self Organizing Maps | by Kosala Sananthana | Towards Data Science
Artificial neural networks (ANN) are inspired by the early models of sensory processing by the brain. An artificial neural network can be created by simulating a network of model neurons in a computer. By applying algorithms that mimic the processes of real neurons, we can make the network ‘learn’ to solve many types of problems. — Anders Krogh1 (Nature Biotechnology) In postmodern life, we engage with an enormous number of astonishing artificial neural network applications in each and every activity and we have no clue of their capacities and complexities. Artificial neural networks have been utilized to difficulties ranging from speech recognition to prediction of protein secondary structure, classification of cancers, and gene prediction1. Since the awareness of these advanced performances will be a necessity in the near future, we should have a better knowledge of these and we can start our journey of understanding ANNs from a simple level. As a basic type of ANNs, let’s consider a self-organizing map (SOM) or self-organizing feature map (SOFM) that is trained using unsupervised learning to produce a low-dimensional, discretized representation of the input space of the training samples, called a map. Self Organizing Map? It converts the nonlinear statistical relationships between high-dimensional data into simple geometric relationships of their image points on a low-dimensional display, usually a regular two-dimensional grid of nodes. As the SOM thereby compresses information while preserving the most important topological and/or metric relationships of the primary data elements on the display — Teuvo Kohonen2 Basically, SOMs are characterized as a nonlinear, ordered, smooth mapping of high-dimensional input data manifolds onto the elements of a regular, low-dimensional array2. After training the SOM’s neurons we get a low dimensional representation of high dimensional input data without disturbing the shape of the data distribution and relationship between each input data element. Self-organizing maps differ from other ANNs as they apply unsupervised learning as compared to error-correction learning (backpropagation with gradient descent etc), and in the sense that they use a neighborhood function to preserve the topological properties of the input space. Since its simplicity, we can easily explain and demonstrate its capabilities. For a detailed explanation please refer to Self-Organizing Maps by Teuvo Kohonen2. A simple illustration of the learning process is given in the above figure and we can understand the specialty of SOMs from this representation easily. Initially, input data(blue dots) occupy a special distribution in 2D space, and un-learned neuron(weights) values (red dots) are randomly distributed in a small area and after neurons get modified and learned by inputs, it gets the shape of the input data distribution step by step in the learning process. In addition, each neuron became a representation of one small cluster of input data space. Therefore in this demonstration, we were able to represent 1000 data points with 100 neurons, preserving the topology of the input data. That means we have built a relationship between high-dimension data to low-dimensional representation (map). For further calculations and predictions, we can utilize these few neuron values to represent the tremendous input data space which makes processes much faster. As a basic model of SOM, we are mapping from the ‘n’-dimensional input data space to a two-dimensional array of neurons (‘N’ number of neurons). This SOM can be implemented using the following procedure: “P” number of input vectors are available. ( i= 1, 2, ...,P) ith input vector has n elements: Xi = (xi1, xi2, ..., xin) “N” number of neurons (nodes or weights) are available. ( i= 1, 2, ..., N) ith neuron vector has n elements: mi = (mi1, mi2, ..., miN) These neuron vectors are arranged in a 2D matrix for representation. Assume all vector elements are real numbers. For a given input Xi, find the closest (smallest euclidean distance) neuron to the given input and signified the neuron by the c. For a given input Xi, after finding mc neuron, only update the neighborhood neuron set of mc: for t = 0, 1, 2, ... T. ( T is the number of iterations the models will get updated and mi (0) can be an initial arbitrary vector). The function hci(t) is the so-called neighborhood function, a smoothing kernel defined over the lattice points (matrix element). Since we only need to update neighboring neurons around the mc neuron, first we need to find a neighborhood set of matrix points around neuron mc. A simple topological neighborhood finding method is given below and more advanced smooth neighborhood finding methods can be found in the literature2. All the neurons inside the circle marked by Nc(t), we consider them as neighborhood set of ‘mc’ neurons. The neighborhood set of neurons’ radius Nc(t) is usually decreasing monotonically in iterations(t). We usually start with Nc(0) = √N/2 and we need to reduce the radius with each iteration. After finding the set of neighborhood neurons that need to be updated we can use the following hci(t) function and update neurons around mc. In this equation, || rc — ri|| define the distance between neuron’s 2D matrix positions (√N x √N matrix). The value of α(t) is identified as learning-rate factor (0 < α(t) < 1). Both α(t) and σ(t) are monotonically decreasing functions of time-varying as following: Do this learning process for each and every input data vector ( ‘P’ number of input data vectors). Then again do this same process again and again for T time iterations over the same input data vectors. After the T number of iterations, you will get a fully learned neuron matrix that maps our input data values. Using the above algorithm, a few interesting examples that have mentioned in Self-Organizing Maps Book by Teuvo Kohonen2 have been implemented using MATLAB and you can clone it to your local computer as follows: git clone https://github.com/KosalaHerath/kohonen-som.git Let’s define the repository’s home as <REPO_HOME>. Then, go to the following location and you can find three examples of MATLAB implementations and you can run them using any MATLAB version on your computer: <REPO_HOME>/source/kohonen_examples Otherwise, you can just click the following link and goto the implementation repository: github.com These examples are initiated with uniformly random distributed 2-dimensional (n=2) input data vectors. There were 1000 input data values (P=1000). In addition, we have defied the number of neurons as N = 10 x 10 = 100 and the number of iterations as T = 300. You can change these parameters and play with the model using the above implementations. This example’s input data values are square shapely random distributed over the 2-dimensional space. This example’s input data values are triangle shapely random distributed over the 2-dimensional space. This example’s input data values are square shapely random distributed over the 2-dimensional space and specifically, we consider a 1D neuron array instead of a 2D matrix. Therefore, the line was made by neuron array would try to cover all of the input data distribution as follows. Hence, now you can learn and play with these implementations with different inputs and modifications, and more you try will make you understand better. Please suggest any modifications that will improve these implementations from here. Cheers! 🍺 [1] Krogh, A. (2008). What are artificial neural networks? Nature Biotechnology, 26(2), pp.195–197. www.nature.com [2] Teuvo Kohonen (2001). Self-organizing maps. New York Springer.
[ { "code": null, "e": 542, "s": 171, "text": "Artificial neural networks (ANN) are inspired by the early models of sensory processing by the brain. An artificial neural network can be created by simulating a network of model neurons in a computer. By applying algorithms that mimic the processes of real neurons, we can make the network ‘learn’ to solve many types of problems. — Anders Krogh1 (Nature Biotechnology)" }, { "code": null, "e": 1130, "s": 542, "text": "In postmodern life, we engage with an enormous number of astonishing artificial neural network applications in each and every activity and we have no clue of their capacities and complexities. Artificial neural networks have been utilized to difficulties ranging from speech recognition to prediction of protein secondary structure, classification of cancers, and gene prediction1. Since the awareness of these advanced performances will be a necessity in the near future, we should have a better knowledge of these and we can start our journey of understanding ANNs from a simple level." }, { "code": null, "e": 1395, "s": 1130, "text": "As a basic type of ANNs, let’s consider a self-organizing map (SOM) or self-organizing feature map (SOFM) that is trained using unsupervised learning to produce a low-dimensional, discretized representation of the input space of the training samples, called a map." }, { "code": null, "e": 1416, "s": 1395, "text": "Self Organizing Map?" }, { "code": null, "e": 1814, "s": 1416, "text": "It converts the nonlinear statistical relationships between high-dimensional data into simple geometric relationships of their image points on a low-dimensional display, usually a regular two-dimensional grid of nodes. As the SOM thereby compresses information while preserving the most important topological and/or metric relationships of the primary data elements on the display — Teuvo Kohonen2" }, { "code": null, "e": 2634, "s": 1814, "text": "Basically, SOMs are characterized as a nonlinear, ordered, smooth mapping of high-dimensional input data manifolds onto the elements of a regular, low-dimensional array2. After training the SOM’s neurons we get a low dimensional representation of high dimensional input data without disturbing the shape of the data distribution and relationship between each input data element. Self-organizing maps differ from other ANNs as they apply unsupervised learning as compared to error-correction learning (backpropagation with gradient descent etc), and in the sense that they use a neighborhood function to preserve the topological properties of the input space. Since its simplicity, we can easily explain and demonstrate its capabilities. For a detailed explanation please refer to Self-Organizing Maps by Teuvo Kohonen2." }, { "code": null, "e": 3591, "s": 2634, "text": "A simple illustration of the learning process is given in the above figure and we can understand the specialty of SOMs from this representation easily. Initially, input data(blue dots) occupy a special distribution in 2D space, and un-learned neuron(weights) values (red dots) are randomly distributed in a small area and after neurons get modified and learned by inputs, it gets the shape of the input data distribution step by step in the learning process. In addition, each neuron became a representation of one small cluster of input data space. Therefore in this demonstration, we were able to represent 1000 data points with 100 neurons, preserving the topology of the input data. That means we have built a relationship between high-dimension data to low-dimensional representation (map). For further calculations and predictions, we can utilize these few neuron values to represent the tremendous input data space which makes processes much faster." }, { "code": null, "e": 3795, "s": 3591, "text": "As a basic model of SOM, we are mapping from the ‘n’-dimensional input data space to a two-dimensional array of neurons (‘N’ number of neurons). This SOM can be implemented using the following procedure:" }, { "code": null, "e": 3856, "s": 3795, "text": "“P” number of input vectors are available. ( i= 1, 2, ...,P)" }, { "code": null, "e": 3915, "s": 3856, "text": "ith input vector has n elements: Xi = (xi1, xi2, ..., xin)" }, { "code": null, "e": 3990, "s": 3915, "text": "“N” number of neurons (nodes or weights) are available. ( i= 1, 2, ..., N)" }, { "code": null, "e": 4050, "s": 3990, "text": "ith neuron vector has n elements: mi = (mi1, mi2, ..., miN)" }, { "code": null, "e": 4119, "s": 4050, "text": "These neuron vectors are arranged in a 2D matrix for representation." }, { "code": null, "e": 4164, "s": 4119, "text": "Assume all vector elements are real numbers." }, { "code": null, "e": 4294, "s": 4164, "text": "For a given input Xi, find the closest (smallest euclidean distance) neuron to the given input and signified the neuron by the c." }, { "code": null, "e": 4388, "s": 4294, "text": "For a given input Xi, after finding mc neuron, only update the neighborhood neuron set of mc:" }, { "code": null, "e": 4649, "s": 4388, "text": "for t = 0, 1, 2, ... T. ( T is the number of iterations the models will get updated and mi (0) can be an initial arbitrary vector). The function hci(t) is the so-called neighborhood function, a smoothing kernel defined over the lattice points (matrix element)." }, { "code": null, "e": 4947, "s": 4649, "text": "Since we only need to update neighboring neurons around the mc neuron, first we need to find a neighborhood set of matrix points around neuron mc. A simple topological neighborhood finding method is given below and more advanced smooth neighborhood finding methods can be found in the literature2." }, { "code": null, "e": 5241, "s": 4947, "text": "All the neurons inside the circle marked by Nc(t), we consider them as neighborhood set of ‘mc’ neurons. The neighborhood set of neurons’ radius Nc(t) is usually decreasing monotonically in iterations(t). We usually start with Nc(0) = √N/2 and we need to reduce the radius with each iteration." }, { "code": null, "e": 5382, "s": 5241, "text": "After finding the set of neighborhood neurons that need to be updated we can use the following hci(t) function and update neurons around mc." }, { "code": null, "e": 5648, "s": 5382, "text": "In this equation, || rc — ri|| define the distance between neuron’s 2D matrix positions (√N x √N matrix). The value of α(t) is identified as learning-rate factor (0 < α(t) < 1). Both α(t) and σ(t) are monotonically decreasing functions of time-varying as following:" }, { "code": null, "e": 5961, "s": 5648, "text": "Do this learning process for each and every input data vector ( ‘P’ number of input data vectors). Then again do this same process again and again for T time iterations over the same input data vectors. After the T number of iterations, you will get a fully learned neuron matrix that maps our input data values." }, { "code": null, "e": 6173, "s": 5961, "text": "Using the above algorithm, a few interesting examples that have mentioned in Self-Organizing Maps Book by Teuvo Kohonen2 have been implemented using MATLAB and you can clone it to your local computer as follows:" }, { "code": null, "e": 6231, "s": 6173, "text": "git clone https://github.com/KosalaHerath/kohonen-som.git" }, { "code": null, "e": 6439, "s": 6231, "text": "Let’s define the repository’s home as <REPO_HOME>. Then, go to the following location and you can find three examples of MATLAB implementations and you can run them using any MATLAB version on your computer:" }, { "code": null, "e": 6475, "s": 6439, "text": "<REPO_HOME>/source/kohonen_examples" }, { "code": null, "e": 6564, "s": 6475, "text": "Otherwise, you can just click the following link and goto the implementation repository:" }, { "code": null, "e": 6575, "s": 6564, "text": "github.com" }, { "code": null, "e": 6923, "s": 6575, "text": "These examples are initiated with uniformly random distributed 2-dimensional (n=2) input data vectors. There were 1000 input data values (P=1000). In addition, we have defied the number of neurons as N = 10 x 10 = 100 and the number of iterations as T = 300. You can change these parameters and play with the model using the above implementations." }, { "code": null, "e": 7024, "s": 6923, "text": "This example’s input data values are square shapely random distributed over the 2-dimensional space." }, { "code": null, "e": 7127, "s": 7024, "text": "This example’s input data values are triangle shapely random distributed over the 2-dimensional space." }, { "code": null, "e": 7410, "s": 7127, "text": "This example’s input data values are square shapely random distributed over the 2-dimensional space and specifically, we consider a 1D neuron array instead of a 2D matrix. Therefore, the line was made by neuron array would try to cover all of the input data distribution as follows." }, { "code": null, "e": 7646, "s": 7410, "text": "Hence, now you can learn and play with these implementations with different inputs and modifications, and more you try will make you understand better. Please suggest any modifications that will improve these implementations from here." }, { "code": null, "e": 7656, "s": 7646, "text": "Cheers! 🍺" }, { "code": null, "e": 7756, "s": 7656, "text": "[1] Krogh, A. (2008). What are artificial neural networks? Nature Biotechnology, 26(2), pp.195–197." }, { "code": null, "e": 7771, "s": 7756, "text": "www.nature.com" } ]
Tokens in C
Tokens are the smallest elements of a program, which are meaningful to the compiler. The following are the types of tokens: Keywords, Identifiers, Constant, Strings, Operators, etc. Let us begin with Keywords. Keywords are predefined, reserved words in C and each of which is associated with specific features. These words help us to use the functionality of C language. They have special meaning to the compilers. There are total 32 keywords in C. Each program element in C programming is known as an identifier. They are used for naming of variables, functions, array etc. These are user-defined names which consist of alphabets, number, underscore ‘_’. Identifier’s name should not be same or same as keywords. Keywords are not used as identifiers. Rules for naming C identifiers − It must begin with alphabets or underscore. It must begin with alphabets or underscore. Only alphabets, numbers, underscore can be used, no other special characters, punctuations are allowed. Only alphabets, numbers, underscore can be used, no other special characters, punctuations are allowed. It must not contain white-space. It must not contain white-space. It should not be a keyword. It should not be a keyword. It should be up to 31 characters long. It should be up to 31 characters long. A string is an array of characters ended with a null character(\0). This null character indicates that string has ended. Strings are always enclosed with double quotes(“ “). Let us see how to declare String in C language − char string[20] = {‘s’,’t’,’u’,’d’,’y’, ‘\0’}; char string[20] = “demo”; char string [] = “demo”; Here is an example of tokens in C language, Live Demo #include >stdio.h> int main() { // using keyword char char a1 = 'H'; int b = 8; float d = 5.6; // declaration of string char string[200] = "demodotcom"; if(b<10) printf("Character Value : %c\n",a1); else printf("Float value : %f\n",d); printf("String Value : %s\n", string); return 0; } Character Value : H String Value : demodotcom
[ { "code": null, "e": 1147, "s": 1062, "text": "Tokens are the smallest elements of a program, which are meaningful to the compiler." }, { "code": null, "e": 1244, "s": 1147, "text": "The following are the types of tokens: Keywords, Identifiers, Constant, Strings, Operators, etc." }, { "code": null, "e": 1272, "s": 1244, "text": "Let us begin with Keywords." }, { "code": null, "e": 1477, "s": 1272, "text": "Keywords are predefined, reserved words in C and each of which is associated with specific features. These words help us to use the functionality of C language. They have special meaning to the compilers." }, { "code": null, "e": 1511, "s": 1477, "text": "There are total 32 keywords in C." }, { "code": null, "e": 1814, "s": 1511, "text": "Each program element in C programming is known as an identifier. They are used for naming of variables, functions, array etc. These are user-defined names which consist of alphabets, number, underscore ‘_’. Identifier’s name should not be same or same as keywords. Keywords are not used as identifiers." }, { "code": null, "e": 1847, "s": 1814, "text": "Rules for naming C identifiers −" }, { "code": null, "e": 1891, "s": 1847, "text": "It must begin with alphabets or underscore." }, { "code": null, "e": 1935, "s": 1891, "text": "It must begin with alphabets or underscore." }, { "code": null, "e": 2039, "s": 1935, "text": "Only alphabets, numbers, underscore can be used, no other special characters, punctuations are allowed." }, { "code": null, "e": 2143, "s": 2039, "text": "Only alphabets, numbers, underscore can be used, no other special characters, punctuations are allowed." }, { "code": null, "e": 2176, "s": 2143, "text": "It must not contain white-space." }, { "code": null, "e": 2209, "s": 2176, "text": "It must not contain white-space." }, { "code": null, "e": 2237, "s": 2209, "text": "It should not be a keyword." }, { "code": null, "e": 2265, "s": 2237, "text": "It should not be a keyword." }, { "code": null, "e": 2304, "s": 2265, "text": "It should be up to 31 characters long." }, { "code": null, "e": 2343, "s": 2304, "text": "It should be up to 31 characters long." }, { "code": null, "e": 2517, "s": 2343, "text": "A string is an array of characters ended with a null character(\\0). This null character indicates that string has ended. Strings are always enclosed with double quotes(“ “)." }, { "code": null, "e": 2566, "s": 2517, "text": "Let us see how to declare String in C language −" }, { "code": null, "e": 2613, "s": 2566, "text": "char string[20] = {‘s’,’t’,’u’,’d’,’y’, ‘\\0’};" }, { "code": null, "e": 2639, "s": 2613, "text": "char string[20] = “demo”;" }, { "code": null, "e": 2664, "s": 2639, "text": "char string [] = “demo”;" }, { "code": null, "e": 2708, "s": 2664, "text": "Here is an example of tokens in C language," }, { "code": null, "e": 2719, "s": 2708, "text": " Live Demo" }, { "code": null, "e": 3042, "s": 2719, "text": "#include >stdio.h>\nint main() {\n // using keyword char\n char a1 = 'H';\n int b = 8;\n float d = 5.6;\n // declaration of string\n char string[200] = \"demodotcom\";\n if(b<10)\n printf(\"Character Value : %c\\n\",a1);\n else\n printf(\"Float value : %f\\n\",d);\n printf(\"String Value : %s\\n\", string);\n return 0;\n}" }, { "code": null, "e": 3088, "s": 3042, "text": "Character Value : H\nString Value : demodotcom" } ]
Code indentation in Lua Programming
Lua codes are not like Python when it comes to indentation. So, most of the code you will write will work even if it falls on another line, and you don’t necessarily need to have the nested code to be intended by a certain tab size. The code indentation in lua is more about making the code look much better and more readable. If your entire code is on one line or worse, if it is like multiple lines then I am afraid that your code isn’t very readable. While we can use the code editor’s indentation packages to do the indentation for us, it is still a good idea to use the indentation that Lua provides. Lua provides us with a script which we can make use of when we want to improve the indentation of our file, and running that script includes several steps and you must be aware of the parameters that you require that will help you increase the code indentation in your file. Let’s explore why we need the script. Consider the points listed below about the script − Reduces the Inconsistency of tab sizes. Handles added tabs done by automatic indentation. Makes the code look more like a homogeneous appearance. Removes tab indents and replaces them with spaces. Standardized indentation at 2 spaces per indent. Checks that line lengths don't exceed 80 characters. lua -f codeformat.lua --file myfile.lua --ts 4 --in 4 In the above usage example, the codeformat.lua is the Lua script file that will do all the work for the code indentation for you, the myfile.lua is the file whose indentation you want to improve, the 4 after the --ts flag tells Lua how much tab size you want to keep, and the last 4 tell Lua about the indentation space you want for your file.
[ { "code": null, "e": 1295, "s": 1062, "text": "Lua codes are not like Python when it comes to indentation. So, most of the code you will write will work even if it falls on another line, and you don’t necessarily need to have the nested code to be intended by a certain tab size." }, { "code": null, "e": 1516, "s": 1295, "text": "The code indentation in lua is more about making the code look much better and more readable. If your entire code is on one line or worse, if it is like multiple lines then I am afraid that your code isn’t very readable." }, { "code": null, "e": 1668, "s": 1516, "text": "While we can use the code editor’s indentation packages to do the indentation for us, it is still a good idea to use the indentation that Lua provides." }, { "code": null, "e": 1943, "s": 1668, "text": "Lua provides us with a script which we can make use of when we want to improve the indentation of our file, and running that script includes several steps and you must be aware of the parameters that you require that will help you increase the code indentation in your file." }, { "code": null, "e": 2033, "s": 1943, "text": "Let’s explore why we need the script. Consider the points listed below about the script −" }, { "code": null, "e": 2073, "s": 2033, "text": "Reduces the Inconsistency of tab sizes." }, { "code": null, "e": 2123, "s": 2073, "text": "Handles added tabs done by automatic indentation." }, { "code": null, "e": 2179, "s": 2123, "text": "Makes the code look more like a homogeneous appearance." }, { "code": null, "e": 2230, "s": 2179, "text": "Removes tab indents and replaces them with spaces." }, { "code": null, "e": 2279, "s": 2230, "text": "Standardized indentation at 2 spaces per indent." }, { "code": null, "e": 2332, "s": 2279, "text": "Checks that line lengths don't exceed 80 characters." }, { "code": null, "e": 2386, "s": 2332, "text": "lua -f codeformat.lua --file myfile.lua --ts 4 --in 4" }, { "code": null, "e": 2730, "s": 2386, "text": "In the above usage example, the codeformat.lua is the Lua script file that will do all the work for the code indentation for you, the myfile.lua is the file whose indentation you want to improve, the 4 after the --ts flag tells Lua how much tab size you want to keep, and the last 4 tell Lua about the indentation space you want for your file." } ]
How to remove text inside brackets in Python? - GeeksforGeeks
27 Mar, 2021 In this article, we will learn how to remove content inside brackets without removing brackets in python. Examples: Input: (hai)geeks Output: ()geeks Input: (geeks)for(geeks) Output: ()for() We can remove content inside brackets without removing brackets in 2 methods, one of them is to use the inbuilt methods from the re library and the second method is to implement this functionality by iterating the string using a for loop Method 1: We will use sub() method of re library (regular expressions). sub(): The functionality of sub() method is that it will find the specific pattern and replace it with some string. This method will find the substring which is present in the brackets or parenthesis and replace it with empty brackets. Approach : Import the re libraryNow find the sub-string present in the brackets and replace with () using sub() method.We need to pass the sub() method with 2 arguments those are pattern and string to be replaced with.Print the string. Import the re library Now find the sub-string present in the brackets and replace with () using sub() method. We need to pass the sub() method with 2 arguments those are pattern and string to be replaced with. Print the string. In the below code \(.*?\) represents the regular expression for finding the brackets containing some content. The brackets () have some special meaning in regular expression in python so Backlash \ is used to escape that meaning. Python3 # Importing moduleimport re # Input stringstring="(Geeks)for(Geeks)" # \(.*?\) ==> it is a regular expression for finding# the pattern for brackets containing some contentstring=re.sub("\(.*?\)","()",string) # Output stringprint(string) ()for() Time complexity: O(2^m + n). Where m is the size of the regex, and n is the size of the string. Here the sub() method will take 2^m time to find the pattern using the regex and O(n) to iterate through the string and replace with the “()”. Method 2: In this method, we will iterate through the string and if the character that is being iterated is not present in between the parenthesis then the character will be added to the resultant string. If there is an open or closed parenthesis present in the string then the parenthesis will be added to the resultant string but the string in between then is not added to the resultant string. Approach: Iterate the loop for each character in the string.If a ‘(‘ or ‘)’ appears in the string we will add it to the result string.If the parenthesis number in the string is zero then add the character to the result string.Here if the parenthesis number is greater than zero it indicates that the current character which is being iterated is present in between two parenthesesPrint the result string. Iterate the loop for each character in the string. If a ‘(‘ or ‘)’ appears in the string we will add it to the result string. If the parenthesis number in the string is zero then add the character to the result string. Here if the parenthesis number is greater than zero it indicates that the current character which is being iterated is present in between two parentheses Print the result string. Python3 # Input stringstring="geeks(for)geeks" # resultant stringresult = '' # paren counts the number of brackets encounteredparen= 0for ch in string: # if the character is ( then increment the paren # and add ( to the resultant string. if ch == '(': paren =paren+ 1 result = result + '(' # if the character is ) and paren is greater than 0, # then increment the paren and # add ) to the resultant string. elif (ch == ')') and paren: result = result + ')' paren =paren- 1 # if the character neither ( nor then add it to # resultant string. elif not paren: result += ch # print the resultant string.print(result) geeks()geeks Time complexity : O(n). Here n is the length of the string. In the code, we are iterating through the string and appending the content outside of the parenthesis so it would only take the time O(n). Picked python-regex Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python Graph Plotting in Python | Set 1
[ { "code": null, "e": 24085, "s": 24057, "text": "\n27 Mar, 2021" }, { "code": null, "e": 24191, "s": 24085, "text": "In this article, we will learn how to remove content inside brackets without removing brackets in python." }, { "code": null, "e": 24201, "s": 24191, "text": "Examples:" }, { "code": null, "e": 24277, "s": 24201, "text": "Input: (hai)geeks\nOutput: ()geeks\n\nInput: (geeks)for(geeks)\nOutput: ()for()" }, { "code": null, "e": 24515, "s": 24277, "text": "We can remove content inside brackets without removing brackets in 2 methods, one of them is to use the inbuilt methods from the re library and the second method is to implement this functionality by iterating the string using a for loop" }, { "code": null, "e": 24588, "s": 24515, "text": "Method 1: We will use sub() method of re library (regular expressions). " }, { "code": null, "e": 24704, "s": 24588, "text": "sub(): The functionality of sub() method is that it will find the specific pattern and replace it with some string." }, { "code": null, "e": 24824, "s": 24704, "text": "This method will find the substring which is present in the brackets or parenthesis and replace it with empty brackets." }, { "code": null, "e": 24835, "s": 24824, "text": "Approach :" }, { "code": null, "e": 25060, "s": 24835, "text": "Import the re libraryNow find the sub-string present in the brackets and replace with () using sub() method.We need to pass the sub() method with 2 arguments those are pattern and string to be replaced with.Print the string." }, { "code": null, "e": 25082, "s": 25060, "text": "Import the re library" }, { "code": null, "e": 25170, "s": 25082, "text": "Now find the sub-string present in the brackets and replace with () using sub() method." }, { "code": null, "e": 25270, "s": 25170, "text": "We need to pass the sub() method with 2 arguments those are pattern and string to be replaced with." }, { "code": null, "e": 25288, "s": 25270, "text": "Print the string." }, { "code": null, "e": 25519, "s": 25288, "text": "In the below code \\(.*?\\) represents the regular expression for finding the brackets containing some content. The brackets () have some special meaning in regular expression in python so Backlash \\ is used to escape that meaning. " }, { "code": null, "e": 25527, "s": 25519, "text": "Python3" }, { "code": "# Importing moduleimport re # Input stringstring=\"(Geeks)for(Geeks)\" # \\(.*?\\) ==> it is a regular expression for finding# the pattern for brackets containing some contentstring=re.sub(\"\\(.*?\\)\",\"()\",string) # Output stringprint(string)", "e": 25767, "s": 25527, "text": null }, { "code": null, "e": 25775, "s": 25767, "text": "()for()" }, { "code": null, "e": 25804, "s": 25775, "text": "Time complexity: O(2^m + n)." }, { "code": null, "e": 26014, "s": 25804, "text": "Where m is the size of the regex, and n is the size of the string. Here the sub() method will take 2^m time to find the pattern using the regex and O(n) to iterate through the string and replace with the “()”." }, { "code": null, "e": 26219, "s": 26014, "text": "Method 2: In this method, we will iterate through the string and if the character that is being iterated is not present in between the parenthesis then the character will be added to the resultant string." }, { "code": null, "e": 26411, "s": 26219, "text": "If there is an open or closed parenthesis present in the string then the parenthesis will be added to the resultant string but the string in between then is not added to the resultant string." }, { "code": null, "e": 26421, "s": 26411, "text": "Approach:" }, { "code": null, "e": 26815, "s": 26421, "text": "Iterate the loop for each character in the string.If a ‘(‘ or ‘)’ appears in the string we will add it to the result string.If the parenthesis number in the string is zero then add the character to the result string.Here if the parenthesis number is greater than zero it indicates that the current character which is being iterated is present in between two parenthesesPrint the result string." }, { "code": null, "e": 26866, "s": 26815, "text": "Iterate the loop for each character in the string." }, { "code": null, "e": 26941, "s": 26866, "text": "If a ‘(‘ or ‘)’ appears in the string we will add it to the result string." }, { "code": null, "e": 27034, "s": 26941, "text": "If the parenthesis number in the string is zero then add the character to the result string." }, { "code": null, "e": 27188, "s": 27034, "text": "Here if the parenthesis number is greater than zero it indicates that the current character which is being iterated is present in between two parentheses" }, { "code": null, "e": 27213, "s": 27188, "text": "Print the result string." }, { "code": null, "e": 27221, "s": 27213, "text": "Python3" }, { "code": "# Input stringstring=\"geeks(for)geeks\" # resultant stringresult = '' # paren counts the number of brackets encounteredparen= 0for ch in string: # if the character is ( then increment the paren # and add ( to the resultant string. if ch == '(': paren =paren+ 1 result = result + '(' # if the character is ) and paren is greater than 0, # then increment the paren and # add ) to the resultant string. elif (ch == ')') and paren: result = result + ')' paren =paren- 1 # if the character neither ( nor then add it to # resultant string. elif not paren: result += ch # print the resultant string.print(result)", "e": 27915, "s": 27221, "text": null }, { "code": null, "e": 27928, "s": 27915, "text": "geeks()geeks" }, { "code": null, "e": 27952, "s": 27928, "text": "Time complexity : O(n)." }, { "code": null, "e": 28127, "s": 27952, "text": "Here n is the length of the string. In the code, we are iterating through the string and appending the content outside of the parenthesis so it would only take the time O(n)." }, { "code": null, "e": 28134, "s": 28127, "text": "Picked" }, { "code": null, "e": 28147, "s": 28134, "text": "python-regex" }, { "code": null, "e": 28154, "s": 28147, "text": "Python" }, { "code": null, "e": 28252, "s": 28154, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28261, "s": 28252, "text": "Comments" }, { "code": null, "e": 28274, "s": 28261, "text": "Old Comments" }, { "code": null, "e": 28292, "s": 28274, "text": "Python Dictionary" }, { "code": null, "e": 28314, "s": 28292, "text": "Enumerate() in Python" }, { "code": null, "e": 28346, "s": 28314, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28388, "s": 28346, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28414, "s": 28388, "text": "Python String | replace()" }, { "code": null, "e": 28439, "s": 28414, "text": "sum() function in Python" }, { "code": null, "e": 28476, "s": 28439, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28532, "s": 28476, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28561, "s": 28532, "text": "*args and **kwargs in Python" } ]
Add given n time durations - GeeksforGeeks
03 May, 2021 Given n time durations in the form of MM : SS, where MM denotes minutes and SS denotes the seconds. The task is to add all the time duration and output answer in the form of HH : MM : SS.Examples: Input : n = 5 duration1 = 0 : 45 duration1 = 2 : 31 duration1 = 3 : 11 duration1 = 2 : 27 duration1 = 1 : 28 Output : 0 : 10 : 22 Initially, sum = 0 On adding duration 1, sum = 0 hour 0 minutes 45 seconds. On adding duration 2, sum = 0 hour 3 minutes 16 seconds. On adding duration 3, sum = 0 hour 6 minutes 27 seconds. On adding duration 4, sum = 0 hour 8 minutes 54 seconds. On adding duration 5, sum = 0 hour 10 minutes 22 seconds The idea is to convert all the given time duration to seconds. Once we know the duration in seconds, we can calculate the sum of durations in seconds. In order to get the number of hours, we have to divide the total duration in seconds by 3600. The remainder is used to calculate the number of minutes and seconds. By dividing the remainder with 60 we get the number of minutes, and the remainder of that division is the number of seconds.Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // CPP Program to find the sum of all duration// in the form of MM : SS.#include <bits/stdc++.h>using namespace std; // Print sum of all duration.void printSum(int m[], int s[], int n){ int total = 0; // finding total seconds for (int i = 0; i < n; i++) { total += s[i]; total += (m[i] * 60); } // print the hours. cout << total / 3600 << " : "; total %= 3600; // print the minutes. cout << total / 60 << ": "; total %= 60; // print the hours. cout << total << endl;} // Driven Programint main(){ int m[] = { 0, 2, 3, 2, 1 }; int s[] = { 45, 31, 11, 27, 28 }; int n = sizeof(m)/sizeof(m[0]); printSum(m, s, n); return 0;} // Java Program to find the// sum of all duration in// the form of MM : SS.class GFG{ // Print sum of all duration. static void printSum(int m[], int s[], int n) { int total = 0; // finding total seconds for (int i = 0; i < n; i++) { total += s[i]; total += (m[i] * 60); } // print the hours. System.out.print(total / 3600 + " : "); total %= 3600; // print the minutes. System.out.print(total / 60 +": "); total %= 60; // print the hours. System.out.println(total); } // Driver codepublic static void main (String[] args){ int m[] = {0, 2, 3, 2, 1 }; int s[] = { 45, 31, 11, 27, 28 }; int n = m.length; printSum(m, s, n);} } // This code is contributed by Anant Agarwal. # Python3 code to find the sum of# all duration in the form of MM : SS. # Print sum of all duration.def printSum (m, s, n ): total = 0 # finding total seconds for i in range(n): total += s[i] total += (m[i] * 60) # print the hours. print(int(total / 3600) , end= " : ") total %= 3600 # print the minutes. print(int(total / 60) , end=": ") total %= 60 # print the hours. print(int(total)) # Driven Codem = [ 0, 2, 3, 2, 1 ]s = [ 45, 31, 11, 27, 28 ]n = len(m)printSum(m, s, n) # This code is contributed by "Sharad_Bhardwaj". // C# Program to find the// sum of all duration in// the form of MM : SS.using System; class GFG{ // Print sum of all duration. static void printSum(int []m, int []s, int n) { int total = 0; // finding total seconds for (int i = 0; i < n; i++) { total += s[i]; total += (m[i] * 60); } // print the hours. Console.Write(total / 3600 + " : "); total %= 3600; // print the minutes. Console.Write(total / 60 +": "); total %= 60; // print the hours. Console.Write(total); } // Driver code public static void Main () { int []m = {0, 2, 3, 2, 1 }; int []s = { 45, 31, 11, 27, 28 }; int n = m.Length; printSum(m, s, n); }} // This code is contributed by vt_m. <?php// PHP Program to find the// sum of all duration// in the form of MM : SS. // Print sum of all duration.function printSum($m, $s, $n){ $total = 0; // finding total seconds for ($i = 0; $i < $n; $i++) { $total += $s[$i]; $total += ($m[$i] * 60); } // print the hours. echo floor($total / 3600) , " : "; $total %= 3600; // print the minutes. echo floor($total / 60) ,": "; $total %= 60; // print the hours. echo floor($total) ; } // Driver Code $m = array(0, 2, 3, 2, 1); $s= array(45, 31, 11, 27, 28); $n = count($m); printSum($m, $s, $n); // This code is contributed by anuj_67.?> <script>// javascript Program to find the// sum of all duration in// the form of MM : SS. // Print sum of all duration. function printSum(m, s, n) { var total = 0; // finding total seconds for (var i = 0; i < n; i++) { total += s[i]; total += (m[i] * 60); } // print the hours. document.write((total / 3600).toFixed(0) + " : "); total %= 3600; // print the minutes. document.write((total / 60).toFixed(0) +": "); total %= 60; // print the hours. document.write(total); } // Driver code var m = [0, 2, 3, 2, 1 ]; var s = [45, 31, 11, 27, 28 ]; var n = m.length; printSum(m, s, n); // This code is contributed by bunnyram19</script> Output: 0 : 10: 22 vt_m Akanksha_Rai bunnyram19 date-time-program School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Exceptions in Java Ternary Operator in Python Inline Functions in C++ Difference between Abstract Class and Interface in Java Exception Handling in C++ Destructors in C++ Python Exception Handling 'this' pointer in C++ Python program to add two numbers
[ { "code": null, "e": 24151, "s": 24123, "text": "\n03 May, 2021" }, { "code": null, "e": 24350, "s": 24151, "text": "Given n time durations in the form of MM : SS, where MM denotes minutes and SS denotes the seconds. The task is to add all the time duration and output answer in the form of HH : MM : SS.Examples: " }, { "code": null, "e": 24824, "s": 24350, "text": "Input : n = 5\n duration1 = 0 : 45\n duration1 = 2 : 31\n duration1 = 3 : 11\n duration1 = 2 : 27\n duration1 = 1 : 28\nOutput : 0 : 10 : 22\nInitially, sum = 0\nOn adding duration 1, sum = 0 hour 0 minutes 45 seconds.\nOn adding duration 2, sum = 0 hour 3 minutes 16 seconds.\nOn adding duration 3, sum = 0 hour 6 minutes 27 seconds.\nOn adding duration 4, sum = 0 hour 8 minutes 54 seconds.\nOn adding duration 5, sum = 0 hour 10 minutes 22 seconds" }, { "code": null, "e": 25313, "s": 24826, "text": "The idea is to convert all the given time duration to seconds. Once we know the duration in seconds, we can calculate the sum of durations in seconds. In order to get the number of hours, we have to divide the total duration in seconds by 3600. The remainder is used to calculate the number of minutes and seconds. By dividing the remainder with 60 we get the number of minutes, and the remainder of that division is the number of seconds.Below is the implementation of this approach: " }, { "code": null, "e": 25317, "s": 25313, "text": "C++" }, { "code": null, "e": 25322, "s": 25317, "text": "Java" }, { "code": null, "e": 25330, "s": 25322, "text": "Python3" }, { "code": null, "e": 25333, "s": 25330, "text": "C#" }, { "code": null, "e": 25337, "s": 25333, "text": "PHP" }, { "code": null, "e": 25348, "s": 25337, "text": "Javascript" }, { "code": "// CPP Program to find the sum of all duration// in the form of MM : SS.#include <bits/stdc++.h>using namespace std; // Print sum of all duration.void printSum(int m[], int s[], int n){ int total = 0; // finding total seconds for (int i = 0; i < n; i++) { total += s[i]; total += (m[i] * 60); } // print the hours. cout << total / 3600 << \" : \"; total %= 3600; // print the minutes. cout << total / 60 << \": \"; total %= 60; // print the hours. cout << total << endl;} // Driven Programint main(){ int m[] = { 0, 2, 3, 2, 1 }; int s[] = { 45, 31, 11, 27, 28 }; int n = sizeof(m)/sizeof(m[0]); printSum(m, s, n); return 0;}", "e": 26039, "s": 25348, "text": null }, { "code": "// Java Program to find the// sum of all duration in// the form of MM : SS.class GFG{ // Print sum of all duration. static void printSum(int m[], int s[], int n) { int total = 0; // finding total seconds for (int i = 0; i < n; i++) { total += s[i]; total += (m[i] * 60); } // print the hours. System.out.print(total / 3600 + \" : \"); total %= 3600; // print the minutes. System.out.print(total / 60 +\": \"); total %= 60; // print the hours. System.out.println(total); } // Driver codepublic static void main (String[] args){ int m[] = {0, 2, 3, 2, 1 }; int s[] = { 45, 31, 11, 27, 28 }; int n = m.length; printSum(m, s, n);} } // This code is contributed by Anant Agarwal.", "e": 26900, "s": 26039, "text": null }, { "code": "# Python3 code to find the sum of# all duration in the form of MM : SS. # Print sum of all duration.def printSum (m, s, n ): total = 0 # finding total seconds for i in range(n): total += s[i] total += (m[i] * 60) # print the hours. print(int(total / 3600) , end= \" : \") total %= 3600 # print the minutes. print(int(total / 60) , end=\": \") total %= 60 # print the hours. print(int(total)) # Driven Codem = [ 0, 2, 3, 2, 1 ]s = [ 45, 31, 11, 27, 28 ]n = len(m)printSum(m, s, n) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 27492, "s": 26900, "text": null }, { "code": "// C# Program to find the// sum of all duration in// the form of MM : SS.using System; class GFG{ // Print sum of all duration. static void printSum(int []m, int []s, int n) { int total = 0; // finding total seconds for (int i = 0; i < n; i++) { total += s[i]; total += (m[i] * 60); } // print the hours. Console.Write(total / 3600 + \" : \"); total %= 3600; // print the minutes. Console.Write(total / 60 +\": \"); total %= 60; // print the hours. Console.Write(total); } // Driver code public static void Main () { int []m = {0, 2, 3, 2, 1 }; int []s = { 45, 31, 11, 27, 28 }; int n = m.Length; printSum(m, s, n); }} // This code is contributed by vt_m.", "e": 28367, "s": 27492, "text": null }, { "code": "<?php// PHP Program to find the// sum of all duration// in the form of MM : SS. // Print sum of all duration.function printSum($m, $s, $n){ $total = 0; // finding total seconds for ($i = 0; $i < $n; $i++) { $total += $s[$i]; $total += ($m[$i] * 60); } // print the hours. echo floor($total / 3600) , \" : \"; $total %= 3600; // print the minutes. echo floor($total / 60) ,\": \"; $total %= 60; // print the hours. echo floor($total) ; } // Driver Code $m = array(0, 2, 3, 2, 1); $s= array(45, 31, 11, 27, 28); $n = count($m); printSum($m, $s, $n); // This code is contributed by anuj_67.?>", "e": 29030, "s": 28367, "text": null }, { "code": "<script>// javascript Program to find the// sum of all duration in// the form of MM : SS. // Print sum of all duration. function printSum(m, s, n) { var total = 0; // finding total seconds for (var i = 0; i < n; i++) { total += s[i]; total += (m[i] * 60); } // print the hours. document.write((total / 3600).toFixed(0) + \" : \"); total %= 3600; // print the minutes. document.write((total / 60).toFixed(0) +\": \"); total %= 60; // print the hours. document.write(total); } // Driver code var m = [0, 2, 3, 2, 1 ]; var s = [45, 31, 11, 27, 28 ]; var n = m.length; printSum(m, s, n); // This code is contributed by bunnyram19</script>", "e": 29891, "s": 29030, "text": null }, { "code": null, "e": 29901, "s": 29891, "text": "Output: " }, { "code": null, "e": 29912, "s": 29901, "text": "0 : 10: 22" }, { "code": null, "e": 29919, "s": 29914, "text": "vt_m" }, { "code": null, "e": 29932, "s": 29919, "text": "Akanksha_Rai" }, { "code": null, "e": 29943, "s": 29932, "text": "bunnyram19" }, { "code": null, "e": 29961, "s": 29943, "text": "date-time-program" }, { "code": null, "e": 29980, "s": 29961, "text": "School Programming" }, { "code": null, "e": 30078, "s": 29980, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30087, "s": 30078, "text": "Comments" }, { "code": null, "e": 30100, "s": 30087, "text": "Old Comments" }, { "code": null, "e": 30121, "s": 30100, "text": "Constructors in Java" }, { "code": null, "e": 30140, "s": 30121, "text": "Exceptions in Java" }, { "code": null, "e": 30167, "s": 30140, "text": "Ternary Operator in Python" }, { "code": null, "e": 30191, "s": 30167, "text": "Inline Functions in C++" }, { "code": null, "e": 30247, "s": 30191, "text": "Difference between Abstract Class and Interface in Java" }, { "code": null, "e": 30273, "s": 30247, "text": "Exception Handling in C++" }, { "code": null, "e": 30292, "s": 30273, "text": "Destructors in C++" }, { "code": null, "e": 30318, "s": 30292, "text": "Python Exception Handling" }, { "code": null, "e": 30340, "s": 30318, "text": "'this' pointer in C++" } ]
Tackling Jump Game Problems (LeetCode) | Towards Data Science
In this article, we will be tackling the two jump game problems which are available on LeetCode. These are pretty famous problems and can be a little tricky to solve in one go. Here, we would discuss various ways to solve both the problems step by step with complexity analysis. So, let’s start with the first one. Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you can reach the last index. Example 1: Input: nums = [2,3,1,1,4]Output: trueExplanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: Input: nums = [3,2,1,0,4]Output: falseExplanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. Constraints: 1 <= nums.length <= 3 * 10^4 0 <= nums[i][j] <= 10^5 There are many ways to approach this solution. One thing to note here is we only need to check whether we can reach or not. We do not need to care about the number of steps needed. We will be going with two simple linear solutions. Both of them have similar ideas but differ a little bit in implementation. Both the solutions would be O(N) time and O(1) space. We will not be going the DP way for this solution. So, let’s start with the first approach — the forward iteration approach. In this, we will start with the first element of the array and move forward by one step each time. We also define a maxReach variable which would keep track of the maximum we can reach from that particular index. E.g.: We are at index 2 and the number at index 2 is 4 so the maximum we can reach from here is index 2+4=6. So, we keep updating maxReach in each iteration. Also, we keep checking that the loop variable I should be less than maxReach always otherwise we are at an index which was not within our reach i.e. we cannot reach the last element. So, we break out if I exceed maxReach. So, to avoid the issues, at last, we check whether i==length of the array which signifies we have reached the end of the array. bool canJump(vector<int>& nums) { int i= 0, maxReach=0; while(i<nums.size() && i<=maxReach){ maxReach = max(i + nums[i], maxReach); i++; } if(i == nums.size()) return true; return false;} So, as you can see above we have our first solution which is really very easy to understand. We keep updating maxReach and our conditions do the rest of the job. As soon as we reach the end of the array or we surpass maxReach loop stops. So, if we have reached the end of the array we would be at array’s length which we wanted. Otherwise, we were not able to reach the last element of the array. So, now let’s move to the second method — the backward iteration approach. In this approach, we do just the same work but we start from the last element of the array and try to move backwards. If we can successfully reach the first element of the array, it means the result is true i.e. we can reach the last index of the array. We define the variable lastreach as the last element of the array. At each iteration, we update the lastreach variable by checking whether the lastreach variable is reachable from that index. If yes, the current index becomes the new lastreach. We keep on doing this until we reach the first element of the array. Now, we check whether lastreach variable is equal to 0 (index of 1st variable) which means we could have reached the last element had we started from the first one. bool canJump(vector<int>& nums) { int lastreach = nums.size()-1; for(int i=nums.size()-2;i>=0;i — ) { if(i+nums[i]>=lastreach) lastreach=i; } if(lastreach==0) return true; return false; } So, both are solutions are almost similar in functioning. One starts from the start of the array and the other from the end of the array. Hope you understood both the solutions. Now, let’s move to Jump Game II which is a bit more difficult and we would be using the same maxReach technique once again with some modifications. Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index. Example 1: Input: nums = [2,3,1,1,4]Output: 2Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: Input: nums = [2,3,0,1,4]Output: 2 Constraints: 1 <= nums.length <= 3 * 104 0 <= nums[i] <= 105 There are many ways to solve this problem, but two ways are very famous. One uses Dynamic Programing and takes a time of O(N2) while the other solution is a little smarter and operates in O(N) time. So, let’s see both the approaches and solutions one by one. The first solution uses Dynamic Programming and takes a time of O(N2). (It can give TLE error in LeetCode). Also, this solution uses O(N) space since we need to maintain an extra jumps array so it is definitely not optimal. In this, we first build a new array jumps which will store INT_MAX (maximum value in the respective languages). The purpose of this jumps array is to keep track of the minimum number of jumps needed to reach that particular index. So, we define jumps[0]=0 since we don’t require any jump to reach the 0th index. Now, we start a loop from the second array element till the last one. For each element, we have an inner loop which runs from the first element till that particular element. For each inner element, we check whether we can reach from that element to the outer element for which the inner loop is running in a single jump. If yes, we update the value of jumps[i] = min(jumsp[i], jumps[j]+1). This allows us to find the minimum number of jumps required to reach that particular index. This uses previous results and so is using Dynamic Programming. Since we have one outer loop running through each element of the array and an inner loop running from 0 to ith index, so it is O(N2). Also, we have an extra jumps array which consumes O(N) extra space. int jump(vector<int>& nums) { vector<int>jumps(nums.size(),INT_MAX); jumps[0]=0; for(int i=1;i<nums.size();i++) { for(int j=0;j<i;j++) { if(nums[j]>=i-j) jumps[i] = min(jumps[i], jumps[j]+1); } } return jumps[nums.size()-1];} The second approach is smarter and is very optimal as it takes no extra space and only O(N) time. In this approach, we define two variables maxReach and steps. Also, we have a jumps variable to count the number of jumps needed. We define both jumps and steps variable to the value of the first index of the array. maxReach means the maximum we can reach from that particular index which is the index plus the value of the index (the jump value). So, we keep updating it in each iteration so that whenever we move forward, the variable stores the maximum we can reach by using maxReach = max(maxReach, nums[i]+i) Also, at each iteration, we reduce our steps variable by 1. As we move forward we consume 1 step each time. So, whenever we run out of steps, it means we need to take 1 jump. So, we increase the jumps variable and also update the steps variable. The steps variable is updated to the value (maxReach — i) which means the difference between a maximum reach possible from that variable or any variable before it and the current index. So, we can take those steps and then we need to again jump. So, in this solution, we return jumps+1 as our answer since we only jump after we run out of steps but to perform that we needed a jump upfront. Also, you need to note that we moved only till the second last element and not the last element since at last step we do not need to consume one more step as we are already there and no need to jump more. We also took care of the edge case when there is only 1 element in the array, then we do not need to perform any jump. int jump(vector<int>& nums) { if(nums.size()==1) return 0; int maxReach = nums[0]; int steps = nums[0]; int jumps = 0; for(int i=1;i<nums.size()-1;i++) { maxReach = max(maxReach, nums[i]+i); steps--; if(steps==0) { jumps++; steps = maxReach - i; } } return jumps+1;} So, I hope it was a good experience reading this post and I hope you learned something out of it. Go, solve these problems on Leetcode. I have not covered Jump Game III. You should try it too. Thanks for reading! More articles to read after finishing this one:-
[ { "code": null, "e": 348, "s": 171, "text": "In this article, we will be tackling the two jump game problems which are available on LeetCode. These are pretty famous problems and can be a little tricky to solve in one go." }, { "code": null, "e": 486, "s": 348, "text": "Here, we would discuss various ways to solve both the problems step by step with complexity analysis. So, let’s start with the first one." }, { "code": null, "e": 589, "s": 486, "text": "Given an array of non-negative integers, you are initially positioned at the first index of the array." }, { "code": null, "e": 669, "s": 589, "text": "Each element in the array represents your maximum jump length at that position." }, { "code": null, "e": 712, "s": 669, "text": "Determine if you can reach the last index." }, { "code": null, "e": 723, "s": 712, "text": "Example 1:" }, { "code": null, "e": 836, "s": 723, "text": "Input: nums = [2,3,1,1,4]Output: trueExplanation: Jump 1 step from index 0 to 1, then 3 steps to the last index." }, { "code": null, "e": 847, "s": 836, "text": "Example 2:" }, { "code": null, "e": 1029, "s": 847, "text": "Input: nums = [3,2,1,0,4]Output: falseExplanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index." }, { "code": null, "e": 1042, "s": 1029, "text": "Constraints:" }, { "code": null, "e": 1071, "s": 1042, "text": "1 <= nums.length <= 3 * 10^4" }, { "code": null, "e": 1095, "s": 1071, "text": "0 <= nums[i][j] <= 10^5" }, { "code": null, "e": 1276, "s": 1095, "text": "There are many ways to approach this solution. One thing to note here is we only need to check whether we can reach or not. We do not need to care about the number of steps needed." }, { "code": null, "e": 1402, "s": 1276, "text": "We will be going with two simple linear solutions. Both of them have similar ideas but differ a little bit in implementation." }, { "code": null, "e": 1507, "s": 1402, "text": "Both the solutions would be O(N) time and O(1) space. We will not be going the DP way for this solution." }, { "code": null, "e": 1581, "s": 1507, "text": "So, let’s start with the first approach — the forward iteration approach." }, { "code": null, "e": 1794, "s": 1581, "text": "In this, we will start with the first element of the array and move forward by one step each time. We also define a maxReach variable which would keep track of the maximum we can reach from that particular index." }, { "code": null, "e": 1903, "s": 1794, "text": "E.g.: We are at index 2 and the number at index 2 is 4 so the maximum we can reach from here is index 2+4=6." }, { "code": null, "e": 2174, "s": 1903, "text": "So, we keep updating maxReach in each iteration. Also, we keep checking that the loop variable I should be less than maxReach always otherwise we are at an index which was not within our reach i.e. we cannot reach the last element. So, we break out if I exceed maxReach." }, { "code": null, "e": 2302, "s": 2174, "text": "So, to avoid the issues, at last, we check whether i==length of the array which signifies we have reached the end of the array." }, { "code": null, "e": 2526, "s": 2302, "text": "bool canJump(vector<int>& nums) { int i= 0, maxReach=0; while(i<nums.size() && i<=maxReach){ maxReach = max(i + nums[i], maxReach); i++; } if(i == nums.size()) return true; return false;}" }, { "code": null, "e": 2923, "s": 2526, "text": "So, as you can see above we have our first solution which is really very easy to understand. We keep updating maxReach and our conditions do the rest of the job. As soon as we reach the end of the array or we surpass maxReach loop stops. So, if we have reached the end of the array we would be at array’s length which we wanted. Otherwise, we were not able to reach the last element of the array." }, { "code": null, "e": 2998, "s": 2923, "text": "So, now let’s move to the second method — the backward iteration approach." }, { "code": null, "e": 3252, "s": 2998, "text": "In this approach, we do just the same work but we start from the last element of the array and try to move backwards. If we can successfully reach the first element of the array, it means the result is true i.e. we can reach the last index of the array." }, { "code": null, "e": 3566, "s": 3252, "text": "We define the variable lastreach as the last element of the array. At each iteration, we update the lastreach variable by checking whether the lastreach variable is reachable from that index. If yes, the current index becomes the new lastreach. We keep on doing this until we reach the first element of the array." }, { "code": null, "e": 3731, "s": 3566, "text": "Now, we check whether lastreach variable is equal to 0 (index of 1st variable) which means we could have reached the last element had we started from the first one." }, { "code": null, "e": 3953, "s": 3731, "text": "bool canJump(vector<int>& nums) { int lastreach = nums.size()-1; for(int i=nums.size()-2;i>=0;i — ) { if(i+nums[i]>=lastreach) lastreach=i; } if(lastreach==0) return true; return false; }" }, { "code": null, "e": 4131, "s": 3953, "text": "So, both are solutions are almost similar in functioning. One starts from the start of the array and the other from the end of the array. Hope you understood both the solutions." }, { "code": null, "e": 4279, "s": 4131, "text": "Now, let’s move to Jump Game II which is a bit more difficult and we would be using the same maxReach technique once again with some modifications." }, { "code": null, "e": 4382, "s": 4279, "text": "Given an array of non-negative integers, you are initially positioned at the first index of the array." }, { "code": null, "e": 4462, "s": 4382, "text": "Each element in the array represents your maximum jump length at that position." }, { "code": null, "e": 4531, "s": 4462, "text": "Your goal is to reach the last index in the minimum number of jumps." }, { "code": null, "e": 4588, "s": 4531, "text": "You can assume that you can always reach the last index." }, { "code": null, "e": 4599, "s": 4588, "text": "Example 1:" }, { "code": null, "e": 4767, "s": 4599, "text": "Input: nums = [2,3,1,1,4]Output: 2Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index." }, { "code": null, "e": 4778, "s": 4767, "text": "Example 2:" }, { "code": null, "e": 4813, "s": 4778, "text": "Input: nums = [2,3,0,1,4]Output: 2" }, { "code": null, "e": 4826, "s": 4813, "text": "Constraints:" }, { "code": null, "e": 4854, "s": 4826, "text": "1 <= nums.length <= 3 * 104" }, { "code": null, "e": 4874, "s": 4854, "text": "0 <= nums[i] <= 105" }, { "code": null, "e": 5073, "s": 4874, "text": "There are many ways to solve this problem, but two ways are very famous. One uses Dynamic Programing and takes a time of O(N2) while the other solution is a little smarter and operates in O(N) time." }, { "code": null, "e": 5133, "s": 5073, "text": "So, let’s see both the approaches and solutions one by one." }, { "code": null, "e": 5357, "s": 5133, "text": "The first solution uses Dynamic Programming and takes a time of O(N2). (It can give TLE error in LeetCode). Also, this solution uses O(N) space since we need to maintain an extra jumps array so it is definitely not optimal." }, { "code": null, "e": 5588, "s": 5357, "text": "In this, we first build a new array jumps which will store INT_MAX (maximum value in the respective languages). The purpose of this jumps array is to keep track of the minimum number of jumps needed to reach that particular index." }, { "code": null, "e": 6151, "s": 5588, "text": "So, we define jumps[0]=0 since we don’t require any jump to reach the 0th index. Now, we start a loop from the second array element till the last one. For each element, we have an inner loop which runs from the first element till that particular element. For each inner element, we check whether we can reach from that element to the outer element for which the inner loop is running in a single jump. If yes, we update the value of jumps[i] = min(jumsp[i], jumps[j]+1). This allows us to find the minimum number of jumps required to reach that particular index." }, { "code": null, "e": 6417, "s": 6151, "text": "This uses previous results and so is using Dynamic Programming. Since we have one outer loop running through each element of the array and an inner loop running from 0 to ith index, so it is O(N2). Also, we have an extra jumps array which consumes O(N) extra space." }, { "code": null, "e": 6708, "s": 6417, "text": "int jump(vector<int>& nums) { vector<int>jumps(nums.size(),INT_MAX); jumps[0]=0; for(int i=1;i<nums.size();i++) { for(int j=0;j<i;j++) { if(nums[j]>=i-j) jumps[i] = min(jumps[i], jumps[j]+1); } } return jumps[nums.size()-1];}" }, { "code": null, "e": 6936, "s": 6708, "text": "The second approach is smarter and is very optimal as it takes no extra space and only O(N) time. In this approach, we define two variables maxReach and steps. Also, we have a jumps variable to count the number of jumps needed." }, { "code": null, "e": 7022, "s": 6936, "text": "We define both jumps and steps variable to the value of the first index of the array." }, { "code": null, "e": 7320, "s": 7022, "text": "maxReach means the maximum we can reach from that particular index which is the index plus the value of the index (the jump value). So, we keep updating it in each iteration so that whenever we move forward, the variable stores the maximum we can reach by using maxReach = max(maxReach, nums[i]+i)" }, { "code": null, "e": 7812, "s": 7320, "text": "Also, at each iteration, we reduce our steps variable by 1. As we move forward we consume 1 step each time. So, whenever we run out of steps, it means we need to take 1 jump. So, we increase the jumps variable and also update the steps variable. The steps variable is updated to the value (maxReach — i) which means the difference between a maximum reach possible from that variable or any variable before it and the current index. So, we can take those steps and then we need to again jump." }, { "code": null, "e": 8162, "s": 7812, "text": "So, in this solution, we return jumps+1 as our answer since we only jump after we run out of steps but to perform that we needed a jump upfront. Also, you need to note that we moved only till the second last element and not the last element since at last step we do not need to consume one more step as we are already there and no need to jump more." }, { "code": null, "e": 8281, "s": 8162, "text": "We also took care of the edge case when there is only 1 element in the array, then we do not need to perform any jump." }, { "code": null, "e": 8636, "s": 8281, "text": "int jump(vector<int>& nums) { if(nums.size()==1) return 0; int maxReach = nums[0]; int steps = nums[0]; int jumps = 0; for(int i=1;i<nums.size()-1;i++) { maxReach = max(maxReach, nums[i]+i); steps--; if(steps==0) { jumps++; steps = maxReach - i; } } return jumps+1;}" }, { "code": null, "e": 8829, "s": 8636, "text": "So, I hope it was a good experience reading this post and I hope you learned something out of it. Go, solve these problems on Leetcode. I have not covered Jump Game III. You should try it too." } ]
Why and how are Python functions hashable?
An object is said to be hashable if it has a hash value that remains the same during its lifetime. It has a __hash__() method and it can be compared to other objects. For this, it needs the __eq__() or __cmp__()method. If hashable objects are equal when compared, then they have same hash value. Being hashable renders an object usable as a dictionary key and a set member as these data structures use hash values internally. All immutable built-in objects in python are hashable. Mutable containers like lists and dictionaries are not hashable while immutable container tuple is hashable Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is derived from their id(). The hash is apparently not necessarily the ID of the function: Consider given lambda function. m = lambda x: 1 print hash(m) print id(m) print m.__hash__() 1265925722 3074942372 1265925722 This shows that lambda functions are hashable Now let us consider given function f() as follows def f():pass print type(f) print f.__hash__() print hash(f) <type 'function'> 1265925978 1265925978 This shows that any function is hashable as it has a hash value that remains same over its lifetime.
[ { "code": null, "e": 1358, "s": 1062, "text": "An object is said to be hashable if it has a hash value that remains the same during its lifetime. It has a __hash__() method and it can be compared to other objects. For this, it needs the __eq__() or __cmp__()method. If hashable objects are equal when compared, then they have same hash value." }, { "code": null, "e": 1488, "s": 1358, "text": "Being hashable renders an object usable as a dictionary key and a set member as these data structures use hash values internally." }, { "code": null, "e": 1651, "s": 1488, "text": "All immutable built-in objects in python are hashable. Mutable containers like lists and dictionaries are not hashable while immutable container tuple is hashable" }, { "code": null, "e": 1828, "s": 1651, "text": "Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is derived from their id()." }, { "code": null, "e": 1923, "s": 1828, "text": "The hash is apparently not necessarily the ID of the function: Consider given lambda function." }, { "code": null, "e": 1984, "s": 1923, "text": "m = lambda x: 1\nprint hash(m)\nprint id(m)\nprint m.__hash__()" }, { "code": null, "e": 2017, "s": 1984, "text": "1265925722\n3074942372\n1265925722" }, { "code": null, "e": 2063, "s": 2017, "text": "This shows that lambda functions are hashable" }, { "code": null, "e": 2113, "s": 2063, "text": "Now let us consider given function f() as follows" }, { "code": null, "e": 2173, "s": 2113, "text": "def f():pass\nprint type(f)\nprint f.__hash__()\nprint hash(f)" }, { "code": null, "e": 2213, "s": 2173, "text": "<type 'function'>\n1265925978\n1265925978" }, { "code": null, "e": 2314, "s": 2213, "text": "This shows that any function is hashable as it has a hash value that remains same over its lifetime." } ]
How to write a program to copy characters from one file to another in Java?
To copy the contents of one file to other character by character import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyFiles { public static void main(String[] args) throws IOException { //Creating a File object to hold the source file File source = new File("D:\\ExampleDirectory\\SampleFile.txt"); //Creating a File object to hold the destination file File destination = new File("D:\\ExampleDirectory\\outputFile.txt"); //Creating an FileInputStream object FileInputStream inputStream = new FileInputStream(source); //Creating an FileOutputStream object FileOutputStream outputStream = new FileOutputStream(destination); //Creating a buffer to hold the data int length = (int) source.length(); byte[] buffer = new byte[length]; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } inputStream.close(); outputStream.close(); System.out.println("File copied successfully......."); } } File copied successfully.......
[ { "code": null, "e": 1127, "s": 1062, "text": "To copy the contents of one file to other character by character" }, { "code": null, "e": 2174, "s": 1127, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\npublic class CopyFiles {\n public static void main(String[] args) throws IOException {\n //Creating a File object to hold the source file\n File source = new File(\"D:\\\\ExampleDirectory\\\\SampleFile.txt\");\n //Creating a File object to hold the destination file\n File destination = new File(\"D:\\\\ExampleDirectory\\\\outputFile.txt\");\n //Creating an FileInputStream object\n FileInputStream inputStream = new FileInputStream(source);\n //Creating an FileOutputStream object\n FileOutputStream outputStream = new FileOutputStream(destination);\n //Creating a buffer to hold the data\n int length = (int) source.length();\n byte[] buffer = new byte[length];\n while ((length = inputStream.read(buffer)) > 0) {\n outputStream.write(buffer, 0, length);\n }\n inputStream.close();\n outputStream.close();\n System.out.println(\"File copied successfully.......\");\n }\n}" }, { "code": null, "e": 2206, "s": 2174, "text": "File copied successfully......." } ]
PySpark - Create DataFrame from List - GeeksforGeeks
30 May, 2021 In this article, we are going to discuss how to create a Pyspark dataframe from a list. To do this first create a list of data and a list of column names. Then pass this zipped data to spark.createDataFrame() method. This method is used to create DataFrame. The data attribute will be the list of data and the columns attribute will be the list of names. dataframe = spark.createDataFrame(data, columns) Example1: Python code to create Pyspark student dataframe from two lists. Python3 # importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of college data with two listsdata = [["java", "dbms", "python"], ["OOPS", "SQL", "Machine Learning"]] # giving column names of dataframecolumns = ["Subject 1", "Subject 2", "Subject 3"] # creating a dataframedataframe = spark.createDataFrame(data, columns) # show data framedataframe.show() Output: Example 2: Create a dataframe from 4 lists Python3 # importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of college data with two listsdata = [["node.js", "dbms", "integration"], ["jsp", "SQL", "trigonometry"], ["php", "oracle", "statistics"], [".net", "db2", "Machine Learning"]] # giving column names of dataframecolumns = ["Web Technologies", "Data bases", "Maths"] # creating a dataframedataframe = spark.createDataFrame(data, columns) # show data framedataframe.show() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n30 May, 2021" }, { "code": null, "e": 24381, "s": 24292, "text": "In this article, we are going to discuss how to create a Pyspark dataframe from a list. " }, { "code": null, "e": 24648, "s": 24381, "text": "To do this first create a list of data and a list of column names. Then pass this zipped data to spark.createDataFrame() method. This method is used to create DataFrame. The data attribute will be the list of data and the columns attribute will be the list of names." }, { "code": null, "e": 24697, "s": 24648, "text": "dataframe = spark.createDataFrame(data, columns)" }, { "code": null, "e": 24771, "s": 24697, "text": "Example1: Python code to create Pyspark student dataframe from two lists." }, { "code": null, "e": 24779, "s": 24771, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of college data with two listsdata = [[\"java\", \"dbms\", \"python\"], [\"OOPS\", \"SQL\", \"Machine Learning\"]] # giving column names of dataframecolumns = [\"Subject 1\", \"Subject 2\", \"Subject 3\"] # creating a dataframedataframe = spark.createDataFrame(data, columns) # show data framedataframe.show()", "e": 25323, "s": 24779, "text": null }, { "code": null, "e": 25331, "s": 25323, "text": "Output:" }, { "code": null, "e": 25374, "s": 25331, "text": "Example 2: Create a dataframe from 4 lists" }, { "code": null, "e": 25382, "s": 25374, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of college data with two listsdata = [[\"node.js\", \"dbms\", \"integration\"], [\"jsp\", \"SQL\", \"trigonometry\"], [\"php\", \"oracle\", \"statistics\"], [\".net\", \"db2\", \"Machine Learning\"]] # giving column names of dataframecolumns = [\"Web Technologies\", \"Data bases\", \"Maths\"] # creating a dataframedataframe = spark.createDataFrame(data, columns) # show data framedataframe.show()", "e": 26016, "s": 25382, "text": null }, { "code": null, "e": 26024, "s": 26016, "text": "Output:" }, { "code": null, "e": 26031, "s": 26024, "text": "Picked" }, { "code": null, "e": 26046, "s": 26031, "text": "Python-Pyspark" }, { "code": null, "e": 26053, "s": 26046, "text": "Python" }, { "code": null, "e": 26151, "s": 26053, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26160, "s": 26151, "text": "Comments" }, { "code": null, "e": 26173, "s": 26160, "text": "Old Comments" }, { "code": null, "e": 26205, "s": 26173, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26261, "s": 26205, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26316, "s": 26261, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26358, "s": 26316, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26400, "s": 26358, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26431, "s": 26400, "text": "Python | os.path.join() method" }, { "code": null, "e": 26470, "s": 26431, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26492, "s": 26470, "text": "Defaultdict in Python" }, { "code": null, "e": 26521, "s": 26492, "text": "Create a directory in Python" } ]
Create a linked list from two linked lists by choosing max element at each position - GeeksforGeeks
03 Dec, 2021 Given two linked list of equal sizes, the task is to create new linked list using those linked lists where at every step, the maximum of the two elements from both the linked lists is chosen and the other is skipped. Examples: Input: list1 = 5 -> 2 -> 3 -> 8 -> NULL list2 = 1 -> 7 -> 4 -> 5 -> NULL Output: 5 -> 7 -> 4 -> 8 -> NULL Input: list1 = 2 -> 8 -> 9 -> 3 -> NULL list2 = 5 -> 3 -> 6 -> 4 -> NULL Output: 5 -> 8 -> 9 -> 4 -> NULL Approach: We traverse both the linked list at the same time and compare node from both the lists. The node which is greater among them, will be added to the new linked list. We do this for each node and then print the nodes of the generated linked list. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Representation of nodestruct Node { int data; Node* next;}; // Function to insert node in a linked listvoid insert(Node** root, int item){ Node *ptr, *temp; temp = new Node; temp->data = item; temp->next = NULL; if (*root == NULL) *root = temp; else { ptr = *root; while (ptr->next != NULL) ptr = ptr->next; ptr->next = temp; }} // Function to print the// nodes of a linked listvoid display(Node* root){ while (root != NULL) { cout << root->data << " -> "; root = root->next; } cout << "NULL";} // Function to generate the required// linked list and return its headNode* newList(Node* root1, Node* root2){ Node *ptr1 = root1, *ptr2 = root2; Node* root = NULL; // While there are nodes left while (ptr1 != NULL) { // Maximum node at current position int currMax = ((ptr1->data < ptr2->data) ? ptr2->data : ptr1->data); // If current node is the first node // of the newly linked list being // generated then assign it to the root if (root == NULL) { Node* temp = new Node; temp->data = currMax; temp->next = NULL; root = temp; } // Else insert the newly // created node in the end else { insert(&root, currMax); } // Get to the next nodes ptr1 = ptr1->next; ptr2 = ptr2->next; } // Return the head of the // generated linked list return root;} // Driver codeint main(){ Node *root1 = NULL, *root2 = NULL, *root = NULL; // First linked list insert(&root1, 5); insert(&root1, 2); insert(&root1, 3); insert(&root1, 8); // Second linked list insert(&root2, 1); insert(&root2, 7); insert(&root2, 4); insert(&root2, 5); // Generate the new linked list // and get its head root = newList(root1, root2); // Display the nodes of the generated list display(root); return 0;} // Java implementation of the approachimport java.util.*;class GFG{ // Representation of nodestatic class Node{ int data; Node next;}; // Function to insert node in a linked liststatic Node insert(Node root, int item){ Node ptr, temp; temp = new Node(); temp.data = item; temp.next = null; if (root == null) root = temp; else { ptr = root; while (ptr.next != null) ptr = ptr.next; ptr.next = temp; } return root;} // Function to print the// nodes of a linked liststatic void display(Node root){ while (root != null) { System.out.print( root.data + " - > "); root = root.next; } System.out.print("null");} // Function to generate the required// linked list and return its headstatic Node newList(Node root1, Node root2){ Node ptr1 = root1, ptr2 = root2; Node root = null; // While there are nodes left while (ptr1 != null) { // Maximum node at current position int currMax = ((ptr1.data < ptr2.data) ? ptr2.data : ptr1.data); // If current node is the first node // of the newly linked list being // generated then assign it to the root if (root == null) { Node temp = new Node(); temp.data = currMax; temp.next = null; root = temp; } // Else insert the newly // created node in the end else { root = insert(root, currMax); } // Get to the next nodes ptr1 = ptr1.next; ptr2 = ptr2.next; } // Return the head of the // generated linked list return root;} // Driver codepublic static void main(String args[]){ Node root1 = null, root2 = null, root = null; // First linked list root1 = insert(root1, 5); root1 = insert(root1, 2); root1 = insert(root1, 3); root1 = insert(root1, 8); // Second linked list root2 = insert(root2, 1); root2 = insert(root2, 7); root2 = insert(root2, 4); root2 = insert(root2, 5); // Generate the new linked list // and get its head root = newList(root1, root2); // Display the nodes of the generated list display(root); }} // This code is contributed by Arnab Kundu # Python3 implementation of the approachimport math # Representation of nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to insert node in a linked listdef insert(root, item): #ptr, *temp temp = Node(item) temp.data = item temp.next = None if (root == None): root = temp else: ptr = root while (ptr.next != None): ptr = ptr.next ptr.next = temp return root # Function to print the# nodes of a linked listdef display(root): while (root != None) : print(root.data, end = "->") root = root.next print("NULL") # Function to generate the required# linked list and return its headdef newList(root1, root2): ptr1 = root1 ptr2 = root2 root = None # While there are nodes left while (ptr1 != None) : # Maximum node at current position currMax = ((ptr1.data < ptr2.data) and ptr2.data or ptr1.data) # If current node is the first node # of the newly linked list being # generated then assign it to the root if (root == None): temp = Node(currMax) temp.data = currMax temp.next = None root = temp # Else insert the newly # created node in the end else : root = insert(root, currMax) # Get to the next nodes ptr1 = ptr1.next ptr2 = ptr2.next # Return the head of the # generated linked list return root # Driver codeif __name__=='__main__': root1 = None root2 = None root = None # First linked list root1 = insert(root1, 5) root1 = insert(root1, 2) root1 = insert(root1, 3) root1 = insert(root1, 8) # Second linked list root2 = insert(root2, 1) root2 = insert(root2, 7) root2 = insert(root2, 4) root2 = insert(root2, 5) # Generate the new linked list # and get its head root = newList(root1, root2) # Display the nodes of the generated list display(root) # This code is contributed by Srathore // C# implementation of the approachusing System; class GFG{ // Representation of nodepublic class Node{ public int data; public Node next;}; // Function to insert node in a linked liststatic Node insert(Node root, int item){ Node ptr, temp; temp = new Node(); temp.data = item; temp.next = null; if (root == null) root = temp; else { ptr = root; while (ptr.next != null) ptr = ptr.next; ptr.next = temp; } return root;} // Function to print the// nodes of a linked liststatic void display(Node root){ while (root != null) { Console.Write( root.data + " - > "); root = root.next; } Console.Write("null");} // Function to generate the required// linked list and return its headstatic Node newList(Node root1, Node root2){ Node ptr1 = root1, ptr2 = root2; Node root = null; // While there are nodes left while (ptr1 != null) { // Maximum node at current position int currMax = ((ptr1.data < ptr2.data) ? ptr2.data : ptr1.data); // If current node is the first node // of the newly linked list being // generated then assign it to the root if (root == null) { Node temp = new Node(); temp.data = currMax; temp.next = null; root = temp; } // Else insert the newly // created node in the end else { root = insert(root, currMax); } // Get to the next nodes ptr1 = ptr1.next; ptr2 = ptr2.next; } // Return the head of the // generated linked list return root;} // Driver codepublic static void Main(String []args){ Node root1 = null, root2 = null, root = null; // First linked list root1 = insert(root1, 5); root1 = insert(root1, 2); root1 = insert(root1, 3); root1 = insert(root1, 8); // Second linked list root2 = insert(root2, 1); root2 = insert(root2, 7); root2 = insert(root2, 4); root2 = insert(root2, 5); // Generate the new linked list // and get its head root = newList(root1, root2); // Display the nodes of the generated list display(root); }} /* This code contributed by PrinciRaj1992 */ <script>// javascript implementation of the approach // Representation of nodeclass Node { constructor() { this.data = 0; this.next = null; }} // Function to insert node in a linked list function insert( root , item) { var ptr, temp; temp = new Node(); temp.data = item; temp.next = null; if (root == null) root = temp; else { ptr = root; while (ptr.next != null) ptr = ptr.next; ptr.next = temp; } return root; } // Function to print the // nodes of a linked list function display( root) { while (root != null) { document.write(root.data + " - > "); root = root.next; } document.write("null"); } // Function to generate the required // linked list and return its head function newList( root1, root2) { ptr1 = root1, ptr2 = root2; root = null; // While there are nodes left while (ptr1 != null) { // Maximum node at current position var currMax = ((ptr1.data < ptr2.data) ? ptr2.data : ptr1.data); // If current node is the first node // of the newly linked list being // generated then assign it to the root if (root == null) { temp = new Node(); temp.data = currMax; temp.next = null; root = temp; } // Else insert the newly // created node in the end else { root = insert(root, currMax); } // Get to the next nodes ptr1 = ptr1.next; ptr2 = ptr2.next; } // Return the head of the // generated linked list return root; } // Driver code root1 = null, root2 = null, root = null; // First linked list root1 = insert(root1, 5); root1 = insert(root1, 2); root1 = insert(root1, 3); root1 = insert(root1, 8); // Second linked list root2 = insert(root2, 1); root2 = insert(root2, 7); root2 = insert(root2, 4); root2 = insert(root2, 5); // Generate the new linked list // and get its head root = newList(root1, root2); // Display the nodes of the generated list display(root); // This code is contributed by todaysgaurav.</script> 5 -> 7 -> 4 -> 8 -> NULL andrew1234 princiraj1992 sapnasingh4991 todaysgaurav simranarora5sos Traversal Linked List Linked List Traversal Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Singly Linked List | Insertion Given a linked list which is sorted, how will you insert in sorted way Swap nodes in a linked list without swapping data Delete a node in a Doubly Linked List Circular Linked List | Set 2 (Traversal) Insert a node at a specific position in a linked list Program to implement Singly Linked List in C++ using class Priority Queue using Linked List Insertion Sort for Singly Linked List Real-time application of Data Structures
[ { "code": null, "e": 24934, "s": 24906, "text": "\n03 Dec, 2021" }, { "code": null, "e": 25151, "s": 24934, "text": "Given two linked list of equal sizes, the task is to create new linked list using those linked lists where at every step, the maximum of the two elements from both the linked lists is chosen and the other is skipped." }, { "code": null, "e": 25162, "s": 25151, "text": "Examples: " }, { "code": null, "e": 25268, "s": 25162, "text": "Input: list1 = 5 -> 2 -> 3 -> 8 -> NULL list2 = 1 -> 7 -> 4 -> 5 -> NULL Output: 5 -> 7 -> 4 -> 8 -> NULL" }, { "code": null, "e": 25375, "s": 25268, "text": "Input: list1 = 2 -> 8 -> 9 -> 3 -> NULL list2 = 5 -> 3 -> 6 -> 4 -> NULL Output: 5 -> 8 -> 9 -> 4 -> NULL " }, { "code": null, "e": 25629, "s": 25375, "text": "Approach: We traverse both the linked list at the same time and compare node from both the lists. The node which is greater among them, will be added to the new linked list. We do this for each node and then print the nodes of the generated linked list." }, { "code": null, "e": 25682, "s": 25629, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25686, "s": 25682, "text": "C++" }, { "code": null, "e": 25691, "s": 25686, "text": "Java" }, { "code": null, "e": 25699, "s": 25691, "text": "Python3" }, { "code": null, "e": 25702, "s": 25699, "text": "C#" }, { "code": null, "e": 25713, "s": 25702, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Representation of nodestruct Node { int data; Node* next;}; // Function to insert node in a linked listvoid insert(Node** root, int item){ Node *ptr, *temp; temp = new Node; temp->data = item; temp->next = NULL; if (*root == NULL) *root = temp; else { ptr = *root; while (ptr->next != NULL) ptr = ptr->next; ptr->next = temp; }} // Function to print the// nodes of a linked listvoid display(Node* root){ while (root != NULL) { cout << root->data << \" -> \"; root = root->next; } cout << \"NULL\";} // Function to generate the required// linked list and return its headNode* newList(Node* root1, Node* root2){ Node *ptr1 = root1, *ptr2 = root2; Node* root = NULL; // While there are nodes left while (ptr1 != NULL) { // Maximum node at current position int currMax = ((ptr1->data < ptr2->data) ? ptr2->data : ptr1->data); // If current node is the first node // of the newly linked list being // generated then assign it to the root if (root == NULL) { Node* temp = new Node; temp->data = currMax; temp->next = NULL; root = temp; } // Else insert the newly // created node in the end else { insert(&root, currMax); } // Get to the next nodes ptr1 = ptr1->next; ptr2 = ptr2->next; } // Return the head of the // generated linked list return root;} // Driver codeint main(){ Node *root1 = NULL, *root2 = NULL, *root = NULL; // First linked list insert(&root1, 5); insert(&root1, 2); insert(&root1, 3); insert(&root1, 8); // Second linked list insert(&root2, 1); insert(&root2, 7); insert(&root2, 4); insert(&root2, 5); // Generate the new linked list // and get its head root = newList(root1, root2); // Display the nodes of the generated list display(root); return 0;}", "e": 27839, "s": 25713, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;class GFG{ // Representation of nodestatic class Node{ int data; Node next;}; // Function to insert node in a linked liststatic Node insert(Node root, int item){ Node ptr, temp; temp = new Node(); temp.data = item; temp.next = null; if (root == null) root = temp; else { ptr = root; while (ptr.next != null) ptr = ptr.next; ptr.next = temp; } return root;} // Function to print the// nodes of a linked liststatic void display(Node root){ while (root != null) { System.out.print( root.data + \" - > \"); root = root.next; } System.out.print(\"null\");} // Function to generate the required// linked list and return its headstatic Node newList(Node root1, Node root2){ Node ptr1 = root1, ptr2 = root2; Node root = null; // While there are nodes left while (ptr1 != null) { // Maximum node at current position int currMax = ((ptr1.data < ptr2.data) ? ptr2.data : ptr1.data); // If current node is the first node // of the newly linked list being // generated then assign it to the root if (root == null) { Node temp = new Node(); temp.data = currMax; temp.next = null; root = temp; } // Else insert the newly // created node in the end else { root = insert(root, currMax); } // Get to the next nodes ptr1 = ptr1.next; ptr2 = ptr2.next; } // Return the head of the // generated linked list return root;} // Driver codepublic static void main(String args[]){ Node root1 = null, root2 = null, root = null; // First linked list root1 = insert(root1, 5); root1 = insert(root1, 2); root1 = insert(root1, 3); root1 = insert(root1, 8); // Second linked list root2 = insert(root2, 1); root2 = insert(root2, 7); root2 = insert(root2, 4); root2 = insert(root2, 5); // Generate the new linked list // and get its head root = newList(root1, root2); // Display the nodes of the generated list display(root); }} // This code is contributed by Arnab Kundu", "e": 30127, "s": 27839, "text": null }, { "code": "# Python3 implementation of the approachimport math # Representation of nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to insert node in a linked listdef insert(root, item): #ptr, *temp temp = Node(item) temp.data = item temp.next = None if (root == None): root = temp else: ptr = root while (ptr.next != None): ptr = ptr.next ptr.next = temp return root # Function to print the# nodes of a linked listdef display(root): while (root != None) : print(root.data, end = \"->\") root = root.next print(\"NULL\") # Function to generate the required# linked list and return its headdef newList(root1, root2): ptr1 = root1 ptr2 = root2 root = None # While there are nodes left while (ptr1 != None) : # Maximum node at current position currMax = ((ptr1.data < ptr2.data) and ptr2.data or ptr1.data) # If current node is the first node # of the newly linked list being # generated then assign it to the root if (root == None): temp = Node(currMax) temp.data = currMax temp.next = None root = temp # Else insert the newly # created node in the end else : root = insert(root, currMax) # Get to the next nodes ptr1 = ptr1.next ptr2 = ptr2.next # Return the head of the # generated linked list return root # Driver codeif __name__=='__main__': root1 = None root2 = None root = None # First linked list root1 = insert(root1, 5) root1 = insert(root1, 2) root1 = insert(root1, 3) root1 = insert(root1, 8) # Second linked list root2 = insert(root2, 1) root2 = insert(root2, 7) root2 = insert(root2, 4) root2 = insert(root2, 5) # Generate the new linked list # and get its head root = newList(root1, root2) # Display the nodes of the generated list display(root) # This code is contributed by Srathore", "e": 32224, "s": 30127, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Representation of nodepublic class Node{ public int data; public Node next;}; // Function to insert node in a linked liststatic Node insert(Node root, int item){ Node ptr, temp; temp = new Node(); temp.data = item; temp.next = null; if (root == null) root = temp; else { ptr = root; while (ptr.next != null) ptr = ptr.next; ptr.next = temp; } return root;} // Function to print the// nodes of a linked liststatic void display(Node root){ while (root != null) { Console.Write( root.data + \" - > \"); root = root.next; } Console.Write(\"null\");} // Function to generate the required// linked list and return its headstatic Node newList(Node root1, Node root2){ Node ptr1 = root1, ptr2 = root2; Node root = null; // While there are nodes left while (ptr1 != null) { // Maximum node at current position int currMax = ((ptr1.data < ptr2.data) ? ptr2.data : ptr1.data); // If current node is the first node // of the newly linked list being // generated then assign it to the root if (root == null) { Node temp = new Node(); temp.data = currMax; temp.next = null; root = temp; } // Else insert the newly // created node in the end else { root = insert(root, currMax); } // Get to the next nodes ptr1 = ptr1.next; ptr2 = ptr2.next; } // Return the head of the // generated linked list return root;} // Driver codepublic static void Main(String []args){ Node root1 = null, root2 = null, root = null; // First linked list root1 = insert(root1, 5); root1 = insert(root1, 2); root1 = insert(root1, 3); root1 = insert(root1, 8); // Second linked list root2 = insert(root2, 1); root2 = insert(root2, 7); root2 = insert(root2, 4); root2 = insert(root2, 5); // Generate the new linked list // and get its head root = newList(root1, root2); // Display the nodes of the generated list display(root); }} /* This code contributed by PrinciRaj1992 */", "e": 34515, "s": 32224, "text": null }, { "code": "<script>// javascript implementation of the approach // Representation of nodeclass Node { constructor() { this.data = 0; this.next = null; }} // Function to insert node in a linked list function insert( root , item) { var ptr, temp; temp = new Node(); temp.data = item; temp.next = null; if (root == null) root = temp; else { ptr = root; while (ptr.next != null) ptr = ptr.next; ptr.next = temp; } return root; } // Function to print the // nodes of a linked list function display( root) { while (root != null) { document.write(root.data + \" - > \"); root = root.next; } document.write(\"null\"); } // Function to generate the required // linked list and return its head function newList( root1, root2) { ptr1 = root1, ptr2 = root2; root = null; // While there are nodes left while (ptr1 != null) { // Maximum node at current position var currMax = ((ptr1.data < ptr2.data) ? ptr2.data : ptr1.data); // If current node is the first node // of the newly linked list being // generated then assign it to the root if (root == null) { temp = new Node(); temp.data = currMax; temp.next = null; root = temp; } // Else insert the newly // created node in the end else { root = insert(root, currMax); } // Get to the next nodes ptr1 = ptr1.next; ptr2 = ptr2.next; } // Return the head of the // generated linked list return root; } // Driver code root1 = null, root2 = null, root = null; // First linked list root1 = insert(root1, 5); root1 = insert(root1, 2); root1 = insert(root1, 3); root1 = insert(root1, 8); // Second linked list root2 = insert(root2, 1); root2 = insert(root2, 7); root2 = insert(root2, 4); root2 = insert(root2, 5); // Generate the new linked list // and get its head root = newList(root1, root2); // Display the nodes of the generated list display(root); // This code is contributed by todaysgaurav.</script>", "e": 36987, "s": 34515, "text": null }, { "code": null, "e": 37012, "s": 36987, "text": "5 -> 7 -> 4 -> 8 -> NULL" }, { "code": null, "e": 37025, "s": 37014, "text": "andrew1234" }, { "code": null, "e": 37039, "s": 37025, "text": "princiraj1992" }, { "code": null, "e": 37054, "s": 37039, "text": "sapnasingh4991" }, { "code": null, "e": 37067, "s": 37054, "text": "todaysgaurav" }, { "code": null, "e": 37083, "s": 37067, "text": "simranarora5sos" }, { "code": null, "e": 37093, "s": 37083, "text": "Traversal" }, { "code": null, "e": 37105, "s": 37093, "text": "Linked List" }, { "code": null, "e": 37117, "s": 37105, "text": "Linked List" }, { "code": null, "e": 37127, "s": 37117, "text": "Traversal" }, { "code": null, "e": 37225, "s": 37127, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37265, "s": 37225, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 37336, "s": 37265, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 37386, "s": 37336, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 37424, "s": 37386, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 37465, "s": 37424, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 37519, "s": 37465, "text": "Insert a node at a specific position in a linked list" }, { "code": null, "e": 37578, "s": 37519, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 37611, "s": 37578, "text": "Priority Queue using Linked List" }, { "code": null, "e": 37649, "s": 37611, "text": "Insertion Sort for Singly Linked List" } ]
10 Python Pandas tricks that make your work more efficient | by Shiu-Tang Li | Towards Data Science
Pandas is a widely used Python package for structured data. There’re many nice tutorials of it, but here I’d still like to introduce a few cool tricks the readers may not know before and I believe they’re useful. Everyone knows this command. But the data you’re trying to read is large, try adding this argument: nrows = 5 to only read in a tiny portion of the table before actually loading the whole table. Then you could avoid the mistake by choosing wrong delimiter (it may not always be comma separated). (Or, you can use ‘head’ command in linux to check out the first 5 rows (say) in any text file: head -n 5 data.txt (Thanks Ilya Levinson for pointing out a typo here)) Then, you can extract the column list by using df.columns.tolist() to extract all columns, and then add usecols = [‘c1’, ‘c2’, ...] argument to load the columns you need. Also, if you know the data types of a few specific columns, you can add the argument dtype = {‘c1’: str, ‘c2’: int, ...} so it would load faster. Another advantage of this argument that if you have a column which contains both strings and numbers, it’s a good practice to declare its type to be string, so you won’t get errors while trying to merge tables using this column as a key. If data preprocessing has to be done in Python, then this command would save you some time. After reading in a table, the default data types for each column could be bool, int64, float64, object, category, timedelta64, or datetime64. You can first check the distribution by df.dtypes.value_counts() to know all possible data types of your dataframe, then do df.select_dtypes(include=['float64', 'int64']) to select a sub-dataframe with only numerical features. This is an important command if you haven’t heard of it already. If you do the following commands: import pandas as pddf1 = pd.DataFrame({ 'a':[0,0,0], 'b': [1,1,1]})df2 = df1df2['a'] = df2['a'] + 1df1.head() You’ll find that df1 is changed. This is because df2 = df1 is not making a copy of df1 and assign it to df2, but setting up a pointer pointing to df1. So any changes in df2 would result in changes in df1. To fix this, you can do either df2 = df1.copy() or from copy import deepcopydf2 = deepcopy(df1) This is a cool command to do easy data transformations. You first define a dictionary with ‘keys’ being the old values and ‘values’ being the new values. level_map = {1: 'high', 2: 'medium', 3: 'low'}df['c_level'] = df['c'].map(level_map) Some examples: True, False to 1, 0 (for modeling); defining levels; user defined lexical encodings. If we’d like to create a new column with a few other columns as inputs, apply function would be quite useful sometimes. def rule(x, y): if x == 'high' and y > 10: return 1 else: return 0df = pd.DataFrame({ 'c1':[ 'high' ,'high', 'low', 'low'], 'c2': [0, 23, 17, 4]})df['new'] = df.apply(lambda x: rule(x['c1'], x['c2']), axis = 1)df.head() In the codes above, we define a function with two input variables, and use the apply function to apply it to columns ‘c1’ and ‘c2’. but the problem of ‘apply’ is that it’s sometimes too slow. Say if you’d like to calculate the maximum of two columns ‘c1’ and ‘c2’, of course you can do df['maximum'] = df.apply(lambda x: max(x['c1'], x['c2']), axis = 1) but you’ll find it much slower than this command: df['maximum'] = df[['c1','c2']].max(axis =1) Takeaway: Don’t use apply if you can get the same work done with other built-in functions (they’re often faster). For example, if you want to round column ‘c’ to integers, do round(df[‘c’], 0) or df[‘c’].round(0) instead of using the apply function: df.apply(lambda x: round(x['c'], 0), axis = 1). This is a command to check value distributions. For example, if you’d like to check what are the possible values and the frequency for each individual value in column ‘c’ you can do df['c'].value_counts() There’re some useful tricks / arguments of it:A. normalize = True: if you want to check the frequency instead of counts.B. dropna = False: if you also want to include missing values in the stats.C. df['c'].value_counts().reset_index(): if you want to convert the stats table into a pandas dataframe and manipulate itD. df['c'].value_counts().reset_index().sort_values(by='index') : show the stats sorted by distinct values in column ‘c’ instead of counts. (Update 2019.4.18 — for D. above, Hao Yang points out a simpler way without .reset_index(): df['c'].value_counts().sort_index()) When building models, you might want to exclude the row with too many missing values / the rows with all missing values. You can use .isnull() and .sum() to count the number of missing values within the specified columns. import pandas as pdimport numpy as npdf = pd.DataFrame({ 'id': [1,2,3], 'c1':[0,0,np.nan], 'c2': [np.nan,1,1]})df = df[['id', 'c1', 'c2']]df['num_nulls'] = df[['c1', 'c2']].isnull().sum(axis=1)df.head() In SQL we can do this using SELECT * FROM ... WHERE ID in (‘A001’, ‘C022’, ...) to get records with specific IDs. If you want to do the same thing with pandas, you can do df_filter = df['ID'].isin(['A001','C022',...])df[df_filter] You have a numerical column, and would like to classify the values in that column into groups, say top 5% into group 1, 5–20% into group 2, 20%-50% into group 3, bottom 50% into group 4. Of course, you can do it with pandas.cut, but I’d like to provide another option here: import numpy as npcut_points = [np.percentile(df['c'], i) for i in [50, 80, 95]]df['group'] = 1for i in range(3): df['group'] = df['group'] + (df['c'] < cut_points[i])# or <= cut_points[i] which is fast to run (no apply function used). Again this is a command that everyone would use. I’d like to point out two tricks here. The first one is print(df[:5].to_csv()) You can use this command to print out the first five rows of what are going to be written into the file exactly. Another trick is dealing with integers and missing values mixed together. If a column contains both missing values and integers, the data type would still be float instead of int. When you export the table, you can add float_format=‘%.0f’ to round all the floats to integers. Use this trick if you only want integer outputs for all columns — you’ll get rid of all annoying ‘.0’s.
[ { "code": null, "e": 385, "s": 172, "text": "Pandas is a widely used Python package for structured data. There’re many nice tutorials of it, but here I’d still like to introduce a few cool tricks the readers may not know before and I believe they’re useful." }, { "code": null, "e": 681, "s": 385, "text": "Everyone knows this command. But the data you’re trying to read is large, try adding this argument: nrows = 5 to only read in a tiny portion of the table before actually loading the whole table. Then you could avoid the mistake by choosing wrong delimiter (it may not always be comma separated)." }, { "code": null, "e": 848, "s": 681, "text": "(Or, you can use ‘head’ command in linux to check out the first 5 rows (say) in any text file: head -n 5 data.txt (Thanks Ilya Levinson for pointing out a typo here))" }, { "code": null, "e": 1403, "s": 848, "text": "Then, you can extract the column list by using df.columns.tolist() to extract all columns, and then add usecols = [‘c1’, ‘c2’, ...] argument to load the columns you need. Also, if you know the data types of a few specific columns, you can add the argument dtype = {‘c1’: str, ‘c2’: int, ...} so it would load faster. Another advantage of this argument that if you have a column which contains both strings and numbers, it’s a good practice to declare its type to be string, so you won’t get errors while trying to merge tables using this column as a key." }, { "code": null, "e": 1677, "s": 1403, "text": "If data preprocessing has to be done in Python, then this command would save you some time. After reading in a table, the default data types for each column could be bool, int64, float64, object, category, timedelta64, or datetime64. You can first check the distribution by" }, { "code": null, "e": 1702, "s": 1677, "text": "df.dtypes.value_counts()" }, { "code": null, "e": 1761, "s": 1702, "text": "to know all possible data types of your dataframe, then do" }, { "code": null, "e": 1808, "s": 1761, "text": "df.select_dtypes(include=['float64', 'int64'])" }, { "code": null, "e": 1864, "s": 1808, "text": "to select a sub-dataframe with only numerical features." }, { "code": null, "e": 1963, "s": 1864, "text": "This is an important command if you haven’t heard of it already. If you do the following commands:" }, { "code": null, "e": 2073, "s": 1963, "text": "import pandas as pddf1 = pd.DataFrame({ 'a':[0,0,0], 'b': [1,1,1]})df2 = df1df2['a'] = df2['a'] + 1df1.head()" }, { "code": null, "e": 2309, "s": 2073, "text": "You’ll find that df1 is changed. This is because df2 = df1 is not making a copy of df1 and assign it to df2, but setting up a pointer pointing to df1. So any changes in df2 would result in changes in df1. To fix this, you can do either" }, { "code": null, "e": 2326, "s": 2309, "text": "df2 = df1.copy()" }, { "code": null, "e": 2329, "s": 2326, "text": "or" }, { "code": null, "e": 2374, "s": 2329, "text": "from copy import deepcopydf2 = deepcopy(df1)" }, { "code": null, "e": 2528, "s": 2374, "text": "This is a cool command to do easy data transformations. You first define a dictionary with ‘keys’ being the old values and ‘values’ being the new values." }, { "code": null, "e": 2613, "s": 2528, "text": "level_map = {1: 'high', 2: 'medium', 3: 'low'}df['c_level'] = df['c'].map(level_map)" }, { "code": null, "e": 2713, "s": 2613, "text": "Some examples: True, False to 1, 0 (for modeling); defining levels; user defined lexical encodings." }, { "code": null, "e": 2833, "s": 2713, "text": "If we’d like to create a new column with a few other columns as inputs, apply function would be quite useful sometimes." }, { "code": null, "e": 3076, "s": 2833, "text": "def rule(x, y): if x == 'high' and y > 10: return 1 else: return 0df = pd.DataFrame({ 'c1':[ 'high' ,'high', 'low', 'low'], 'c2': [0, 23, 17, 4]})df['new'] = df.apply(lambda x: rule(x['c1'], x['c2']), axis = 1)df.head()" }, { "code": null, "e": 3208, "s": 3076, "text": "In the codes above, we define a function with two input variables, and use the apply function to apply it to columns ‘c1’ and ‘c2’." }, { "code": null, "e": 3362, "s": 3208, "text": "but the problem of ‘apply’ is that it’s sometimes too slow. Say if you’d like to calculate the maximum of two columns ‘c1’ and ‘c2’, of course you can do" }, { "code": null, "e": 3430, "s": 3362, "text": "df['maximum'] = df.apply(lambda x: max(x['c1'], x['c2']), axis = 1)" }, { "code": null, "e": 3480, "s": 3430, "text": "but you’ll find it much slower than this command:" }, { "code": null, "e": 3525, "s": 3480, "text": "df['maximum'] = df[['c1','c2']].max(axis =1)" }, { "code": null, "e": 3823, "s": 3525, "text": "Takeaway: Don’t use apply if you can get the same work done with other built-in functions (they’re often faster). For example, if you want to round column ‘c’ to integers, do round(df[‘c’], 0) or df[‘c’].round(0) instead of using the apply function: df.apply(lambda x: round(x['c'], 0), axis = 1)." }, { "code": null, "e": 4005, "s": 3823, "text": "This is a command to check value distributions. For example, if you’d like to check what are the possible values and the frequency for each individual value in column ‘c’ you can do" }, { "code": null, "e": 4028, "s": 4005, "text": "df['c'].value_counts()" }, { "code": null, "e": 4484, "s": 4028, "text": "There’re some useful tricks / arguments of it:A. normalize = True: if you want to check the frequency instead of counts.B. dropna = False: if you also want to include missing values in the stats.C. df['c'].value_counts().reset_index(): if you want to convert the stats table into a pandas dataframe and manipulate itD. df['c'].value_counts().reset_index().sort_values(by='index') : show the stats sorted by distinct values in column ‘c’ instead of counts." }, { "code": null, "e": 4613, "s": 4484, "text": "(Update 2019.4.18 — for D. above, Hao Yang points out a simpler way without .reset_index(): df['c'].value_counts().sort_index())" }, { "code": null, "e": 4835, "s": 4613, "text": "When building models, you might want to exclude the row with too many missing values / the rows with all missing values. You can use .isnull() and .sum() to count the number of missing values within the specified columns." }, { "code": null, "e": 5038, "s": 4835, "text": "import pandas as pdimport numpy as npdf = pd.DataFrame({ 'id': [1,2,3], 'c1':[0,0,np.nan], 'c2': [np.nan,1,1]})df = df[['id', 'c1', 'c2']]df['num_nulls'] = df[['c1', 'c2']].isnull().sum(axis=1)df.head()" }, { "code": null, "e": 5209, "s": 5038, "text": "In SQL we can do this using SELECT * FROM ... WHERE ID in (‘A001’, ‘C022’, ...) to get records with specific IDs. If you want to do the same thing with pandas, you can do" }, { "code": null, "e": 5269, "s": 5209, "text": "df_filter = df['ID'].isin(['A001','C022',...])df[df_filter]" }, { "code": null, "e": 5543, "s": 5269, "text": "You have a numerical column, and would like to classify the values in that column into groups, say top 5% into group 1, 5–20% into group 2, 20%-50% into group 3, bottom 50% into group 4. Of course, you can do it with pandas.cut, but I’d like to provide another option here:" }, { "code": null, "e": 5735, "s": 5543, "text": "import numpy as npcut_points = [np.percentile(df['c'], i) for i in [50, 80, 95]]df['group'] = 1for i in range(3): df['group'] = df['group'] + (df['c'] < cut_points[i])# or <= cut_points[i]" }, { "code": null, "e": 5782, "s": 5735, "text": "which is fast to run (no apply function used)." }, { "code": null, "e": 5887, "s": 5782, "text": "Again this is a command that everyone would use. I’d like to point out two tricks here. The first one is" }, { "code": null, "e": 5910, "s": 5887, "text": "print(df[:5].to_csv())" }, { "code": null, "e": 6023, "s": 5910, "text": "You can use this command to print out the first five rows of what are going to be written into the file exactly." } ]
time.Round() Function in Golang With Examples - GeeksforGeeks
21 Apr, 2020 In Go language, time packages supplies functionality for determining as well as viewing time. The Round() function in Go language is used to find the outcome of rounding the stated duration ‘d’ to the closest multiple of ‘m’ duration. Here, the rounding manner for middle values is to round far off from 0. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. Syntax: func (d Duration) Round(m Duration) Duration Here, d is the duration of time that will be rounded and m is the closest multiple. Return value: It returns maximum (or minimum) duration if the outcome surpasses the maximum (or minimum) value that could be stored in a duration. But if m is less than or equal to 0 then it returns unaltered ‘d’. Example 1: // Golang program to illustrate the usage of// Round() function // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Calling mainfunc main() { // Defining duration // of Round method d, _ := time.ParseDuration("5m7s") // Prints rounded d fmt.Printf("Rounded d is : %s", d.Round(6*time.Second))} Output: Rounded d is : 5m6s Here, ‘d’ is rounded to the closest multiple of m. Example 2: // Golang program to illustrate the usage of// Round() function // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Calling mainfunc main() { // Defining duration of Round method d, _ := time.ParseDuration("3m73.671s") // Array of m R := []time.Duration{ time.Microsecond, time.Second, 3 * time.Second, 9 * time.Minute, } // Using for loop and range to // iterate over an array for _, m := range R { // Prints rounded d of all // the items in an array fmt.Printf("Rounded(%s) is : %s\n", m, d.Round(m)) }} Output: Rounded(1μs) is : 4m13.671s Rounded(1s) is : 4m14s Rounded(3s) is : 4m15s Rounded(9m0s) is : 0s Here, an array of ‘d’ is formed first then a range is used in order to iterate over all the values of d. And at last Round() method is used to print all the rounded values of d. GoLang-time Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Time Formatting in Golang fmt.Sprintf() Function in Golang With Examples strings.Replace() Function in Golang With Examples How to Split a String in Golang? Golang Maps Slices in Golang Arrays in Go How to Trim a String in Golang? How to convert a string in lower case in Golang? Different Ways to Find the Type of Variable in Golang
[ { "code": null, "e": 24492, "s": 24464, "text": "\n21 Apr, 2020" }, { "code": null, "e": 24935, "s": 24492, "text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Round() function in Go language is used to find the outcome of rounding the stated duration ‘d’ to the closest multiple of ‘m’ duration. Here, the rounding manner for middle values is to round far off from 0. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions." }, { "code": null, "e": 24943, "s": 24935, "text": "Syntax:" }, { "code": null, "e": 24989, "s": 24943, "text": "func (d Duration) Round(m Duration) Duration\n" }, { "code": null, "e": 25073, "s": 24989, "text": "Here, d is the duration of time that will be rounded and m is the closest multiple." }, { "code": null, "e": 25287, "s": 25073, "text": "Return value: It returns maximum (or minimum) duration if the outcome surpasses the maximum (or minimum) value that could be stored in a duration. But if m is less than or equal to 0 then it returns unaltered ‘d’." }, { "code": null, "e": 25298, "s": 25287, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// Round() function // Including main packagepackage main // Importing fmt and timeimport ( \"fmt\" \"time\") // Calling mainfunc main() { // Defining duration // of Round method d, _ := time.ParseDuration(\"5m7s\") // Prints rounded d fmt.Printf(\"Rounded d is : %s\", d.Round(6*time.Second))}", "e": 25670, "s": 25298, "text": null }, { "code": null, "e": 25678, "s": 25670, "text": "Output:" }, { "code": null, "e": 25699, "s": 25678, "text": "Rounded d is : 5m6s\n" }, { "code": null, "e": 25750, "s": 25699, "text": "Here, ‘d’ is rounded to the closest multiple of m." }, { "code": null, "e": 25761, "s": 25750, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// Round() function // Including main packagepackage main // Importing fmt and timeimport ( \"fmt\" \"time\") // Calling mainfunc main() { // Defining duration of Round method d, _ := time.ParseDuration(\"3m73.671s\") // Array of m R := []time.Duration{ time.Microsecond, time.Second, 3 * time.Second, 9 * time.Minute, } // Using for loop and range to // iterate over an array for _, m := range R { // Prints rounded d of all // the items in an array fmt.Printf(\"Rounded(%s) is : %s\\n\", m, d.Round(m)) }}", "e": 26427, "s": 25761, "text": null }, { "code": null, "e": 26435, "s": 26427, "text": "Output:" }, { "code": null, "e": 26532, "s": 26435, "text": "Rounded(1μs) is : 4m13.671s\nRounded(1s) is : 4m14s\nRounded(3s) is : 4m15s\nRounded(9m0s) is : 0s\n" }, { "code": null, "e": 26710, "s": 26532, "text": "Here, an array of ‘d’ is formed first then a range is used in order to iterate over all the values of d. And at last Round() method is used to print all the rounded values of d." }, { "code": null, "e": 26722, "s": 26710, "text": "GoLang-time" }, { "code": null, "e": 26734, "s": 26722, "text": "Go Language" }, { "code": null, "e": 26832, "s": 26734, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26841, "s": 26832, "text": "Comments" }, { "code": null, "e": 26854, "s": 26841, "text": "Old Comments" }, { "code": null, "e": 26880, "s": 26854, "text": "Time Formatting in Golang" }, { "code": null, "e": 26927, "s": 26880, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 26978, "s": 26927, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 27011, "s": 26978, "text": "How to Split a String in Golang?" }, { "code": null, "e": 27023, "s": 27011, "text": "Golang Maps" }, { "code": null, "e": 27040, "s": 27023, "text": "Slices in Golang" }, { "code": null, "e": 27053, "s": 27040, "text": "Arrays in Go" }, { "code": null, "e": 27085, "s": 27053, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 27134, "s": 27085, "text": "How to convert a string in lower case in Golang?" } ]
Convert array with duplicate values to object with number of repeated occurrences in JavaScript
Suppose, we have an array string that contains some duplicate entries like this − const arr = ['California','Texas','Texas','Texas','New York','Missouri','New Mexico','California']; We are required to write a JavaScript function that takes in one such array. Our function should then construct an array of objects that contains an object for each unique entry and a property "count" that contains its count in the original array. Therefore, the final output for the above array should look something like this − const output = [ {'name':'California', 'count':2}, {'name':'Texas', 'count':3}, {'name':'New York', 'count':1}, {'name':'Missouri', 'count':1}, {'name':'New Mexico', 'count':1}, ]; The code for this will be − const arr = ['California','Texas','Texas','Texas','New York','Missouri','New Mexico','California']; const findOccurrences = (arr = []) => { const res = []; arr.forEach(el => { const index = res.findIndex(obj => { return obj['name'] === el; }); if(index === -1){ res.push({ "name": el, "count": 1 }) } else{ res[index]["count"]++; }; }); return res; }; console.log(findOccurrences(arr)); And the output in the console will be − [ { name: 'California', count: 2 }, { name: 'Texas', count: 3 }, { name: 'New York', count: 1 }, { name: 'Missouri', count: 1 }, { name: 'New Mexico', count: 1 } ]
[ { "code": null, "e": 1144, "s": 1062, "text": "Suppose, we have an array string that contains some duplicate entries like this −" }, { "code": null, "e": 1244, "s": 1144, "text": "const arr = ['California','Texas','Texas','Texas','New\nYork','Missouri','New Mexico','California'];" }, { "code": null, "e": 1492, "s": 1244, "text": "We are required to write a JavaScript function that takes in one such array. Our function should then construct an array of objects that contains an object for each unique entry and a property \"count\" that contains its count in the original array." }, { "code": null, "e": 1574, "s": 1492, "text": "Therefore, the final output for the above array should look something like this −" }, { "code": null, "e": 1770, "s": 1574, "text": "const output = [\n {'name':'California', 'count':2},\n {'name':'Texas', 'count':3},\n {'name':'New York', 'count':1},\n {'name':'Missouri', 'count':1},\n {'name':'New Mexico', 'count':1},\n];" }, { "code": null, "e": 1798, "s": 1770, "text": "The code for this will be −" }, { "code": null, "e": 2293, "s": 1798, "text": "const arr = ['California','Texas','Texas','Texas','New York','Missouri','New Mexico','California'];\nconst findOccurrences = (arr = []) => {\n const res = [];\n arr.forEach(el => {\n const index = res.findIndex(obj => {\n return obj['name'] === el;\n });\n if(index === -1){\n res.push({\n \"name\": el,\n \"count\": 1\n })\n }\n else{\n res[index][\"count\"]++;\n };\n });\n return res;\n};\nconsole.log(findOccurrences(arr));" }, { "code": null, "e": 2333, "s": 2293, "text": "And the output in the console will be −" }, { "code": null, "e": 2512, "s": 2333, "text": "[\n { name: 'California', count: 2 },\n { name: 'Texas', count: 3 },\n { name: 'New York', count: 1 },\n { name: 'Missouri', count: 1 },\n { name: 'New Mexico', count: 1 }\n]" } ]
Python | Removing duplicates from tuple - GeeksforGeeks
29 Oct, 2019 Many times, while working with Python tuples, we can have a problem of removing duplicates. This is a very common problem and can occur in any form of programming set up, be it regular programming or web development. Let’s discuss certain ways in which this task can be performed. Method #1 : Using set() + tuple()This is the most straight forward way to remove duplicates. In this, we convert the tuple to a set, removing duplicates and then converting it back again using tuple(). # Python3 code to demonstrate working of# Removing duplicates from tuple # using tuple() + set() # initialize tupletest_tup = (1, 3, 5, 2, 3, 5, 1, 1, 3) # printing original tuple print("The original tuple is : " + str(test_tup)) # Removing duplicates from tuple # using tuple() + set()res = tuple(set(test_tup)) # printing resultprint("The tuple after removing duplicates : " + str(res)) The original tuple is : (1, 3, 5, 2, 3, 5, 1, 1, 3) The tuple after removing duplicates : (1, 2, 3, 5) Method #2 : Using OrderedDict() + fromkeys()The combination of above functions can also be used to perform this particular task. In this, we convert the tuples to dictionary removing duplicates and then accessing it’s keys. # Python3 code to demonstrate working of# Removing duplicates from tuple # using OrderedDict() + fromkeys()from collections import OrderedDict # initialize tupletest_tup = (1, 3, 5, 2, 3, 5, 1, 1, 3) # printing original tuple print("The original tuple is : " + str(test_tup)) # Removing duplicates from tuple # using OrderedDict() + fromkeys()res = tuple(OrderedDict.fromkeys(test_tup).keys()) # printing resultprint("The tuple after removing duplicates : " + str(res)) The original tuple is : (1, 3, 5, 2, 3, 5, 1, 1, 3) The tuple after removing duplicates : (1, 2, 3, 5) Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24292, "s": 24264, "text": "\n29 Oct, 2019" }, { "code": null, "e": 24573, "s": 24292, "text": "Many times, while working with Python tuples, we can have a problem of removing duplicates. This is a very common problem and can occur in any form of programming set up, be it regular programming or web development. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 24775, "s": 24573, "text": "Method #1 : Using set() + tuple()This is the most straight forward way to remove duplicates. In this, we convert the tuple to a set, removing duplicates and then converting it back again using tuple()." }, { "code": "# Python3 code to demonstrate working of# Removing duplicates from tuple # using tuple() + set() # initialize tupletest_tup = (1, 3, 5, 2, 3, 5, 1, 1, 3) # printing original tuple print(\"The original tuple is : \" + str(test_tup)) # Removing duplicates from tuple # using tuple() + set()res = tuple(set(test_tup)) # printing resultprint(\"The tuple after removing duplicates : \" + str(res))", "e": 25168, "s": 24775, "text": null }, { "code": null, "e": 25272, "s": 25168, "text": "The original tuple is : (1, 3, 5, 2, 3, 5, 1, 1, 3)\nThe tuple after removing duplicates : (1, 2, 3, 5)\n" }, { "code": null, "e": 25498, "s": 25274, "text": "Method #2 : Using OrderedDict() + fromkeys()The combination of above functions can also be used to perform this particular task. In this, we convert the tuples to dictionary removing duplicates and then accessing it’s keys." }, { "code": "# Python3 code to demonstrate working of# Removing duplicates from tuple # using OrderedDict() + fromkeys()from collections import OrderedDict # initialize tupletest_tup = (1, 3, 5, 2, 3, 5, 1, 1, 3) # printing original tuple print(\"The original tuple is : \" + str(test_tup)) # Removing duplicates from tuple # using OrderedDict() + fromkeys()res = tuple(OrderedDict.fromkeys(test_tup).keys()) # printing resultprint(\"The tuple after removing duplicates : \" + str(res))", "e": 25972, "s": 25498, "text": null }, { "code": null, "e": 26076, "s": 25972, "text": "The original tuple is : (1, 3, 5, 2, 3, 5, 1, 1, 3)\nThe tuple after removing duplicates : (1, 2, 3, 5)\n" }, { "code": null, "e": 26098, "s": 26076, "text": "Python tuple-programs" }, { "code": null, "e": 26105, "s": 26098, "text": "Python" }, { "code": null, "e": 26121, "s": 26105, "text": "Python Programs" }, { "code": null, "e": 26219, "s": 26121, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26251, "s": 26219, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26307, "s": 26251, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26349, "s": 26307, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26391, "s": 26349, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26413, "s": 26391, "text": "Defaultdict in Python" }, { "code": null, "e": 26435, "s": 26413, "text": "Defaultdict in Python" }, { "code": null, "e": 26481, "s": 26435, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26520, "s": 26481, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26558, "s": 26520, "text": "Python | Convert a list to dictionary" } ]
How to add Django debug toolbar to your project?
Django toolbox is a debugging tool that is used to debug database queries, Django website loading speed, and many other things. Debug toolbar is very popular among developers and everyone is using it. So, let's dive into to see how to implement it. Create an app with the name "myapp". First, install the django-debug-toolbar − pip install django-debug-toolbar Now, add 'debug_toolbar' to your INSTALLED_APPS in settings.py − INSTALLED_APPS = [ # ... 'debug_toolbar', 'myapp' ] This will add the debug toolbar as an app in our project. Next, in your middleware, add the following − MIDDLEWARE = [ # ... 'debug_toolbar.middleware.DebugToolbarMiddleware', # ... ] This is used to give access to the database. Now, in urls.py of your project main directory, add the debug toolbar url − import debug_toolbar from django.conf import settings from django.urls import include, path urlpatterns = [ ... path('__debug__/', include(debug_toolbar.urls)), path('', include('myapp.urls')) ] URL will define where all the debug reports should show and where the debug toolbar is needed to be hosted. Now, in settings.py, add one more variable INTERNAL_IPS and mention localhost in it − INTERNAL_IPS = [ # ... '127.0.0.1', # ... ] This variable will define which URL should be debugged and on which debug should be shown. Next, in views.py of app, add the following − from django.shortcuts import render # Create your views here. def home(request): return render(request,"home.html") It will render the frontend file. Now, in urls.py of app, add the following − from django.urls import path from . import views urlpatterns = [ path('',views.home,name="home" ), ] It will render the main view. Next, create a folder in the app directory and name it templates and add home.html in it. In home.html, add the following simple code − <!DOCTYPE html> <html> <head> </head> <body> <h1>success</h1> </body> </html> It will just render a simple message. You will see this toolbar at the right side of your screen on every URL endpoint −
[ { "code": null, "e": 1311, "s": 1062, "text": "Django toolbox is a debugging tool that is used to debug database queries, Django website loading speed, and many other things. Debug toolbar is very popular among developers and everyone is using it. So, let's dive into to see how to implement it." }, { "code": null, "e": 1348, "s": 1311, "text": "Create an app with the name \"myapp\"." }, { "code": null, "e": 1390, "s": 1348, "text": "First, install the django-debug-toolbar −" }, { "code": null, "e": 1423, "s": 1390, "text": "pip install django-debug-toolbar" }, { "code": null, "e": 1488, "s": 1423, "text": "Now, add 'debug_toolbar' to your INSTALLED_APPS in settings.py −" }, { "code": null, "e": 1549, "s": 1488, "text": "INSTALLED_APPS = [\n # ...\n 'debug_toolbar',\n 'myapp'\n]" }, { "code": null, "e": 1607, "s": 1549, "text": "This will add the debug toolbar as an app in our project." }, { "code": null, "e": 1653, "s": 1607, "text": "Next, in your middleware, add the following −" }, { "code": null, "e": 1742, "s": 1653, "text": "MIDDLEWARE = [\n # ...\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n # ...\n]" }, { "code": null, "e": 1787, "s": 1742, "text": "This is used to give access to the database." }, { "code": null, "e": 1863, "s": 1787, "text": "Now, in urls.py of your project main directory, add the debug toolbar url −" }, { "code": null, "e": 2064, "s": 1863, "text": "import debug_toolbar\nfrom django.conf import settings\nfrom django.urls import include, path\nurlpatterns = [\n ...\n path('__debug__/', include(debug_toolbar.urls)),\npath('', include('myapp.urls'))\n]" }, { "code": null, "e": 2172, "s": 2064, "text": "URL will define where all the debug reports should show and where the debug toolbar is needed to be hosted." }, { "code": null, "e": 2258, "s": 2172, "text": "Now, in settings.py, add one more variable INTERNAL_IPS and mention localhost in it −" }, { "code": null, "e": 2311, "s": 2258, "text": "INTERNAL_IPS = [\n # ...\n '127.0.0.1',\n # ...\n]" }, { "code": null, "e": 2402, "s": 2311, "text": "This variable will define which URL should be debugged and on which debug should be shown." }, { "code": null, "e": 2448, "s": 2402, "text": "Next, in views.py of app, add the following −" }, { "code": null, "e": 2568, "s": 2448, "text": "from django.shortcuts import render\n\n# Create your views here.\ndef home(request):\n return render(request,\"home.html\")" }, { "code": null, "e": 2602, "s": 2568, "text": "It will render the frontend file." }, { "code": null, "e": 2646, "s": 2602, "text": "Now, in urls.py of app, add the following −" }, { "code": null, "e": 2750, "s": 2646, "text": "from django.urls import path\nfrom . import views\nurlpatterns = [\n path('',views.home,name=\"home\" ),\n]" }, { "code": null, "e": 2780, "s": 2750, "text": "It will render the main view." }, { "code": null, "e": 2916, "s": 2780, "text": "Next, create a folder in the app directory and name it templates and add home.html in it. In home.html, add the following simple code −" }, { "code": null, "e": 3013, "s": 2916, "text": "<!DOCTYPE html>\n<html>\n <head>\n\n </head>\n <body>\n <h1>success</h1>\n </body>\n</html>" }, { "code": null, "e": 3051, "s": 3013, "text": "It will just render a simple message." }, { "code": null, "e": 3134, "s": 3051, "text": "You will see this toolbar at the right side of your screen on every URL\nendpoint −" } ]
10x times faster Pandas Apply in a single line change of code | by Satyam Kumar | Towards Data Science
Pandas is one of the popular Python packages among the data science community, as it offers a vast API and flexible data structures for data explorations and visualization. When it comes to handling and processing large-size datasets, it fails. One can load and process a large-size dataset in chunks or use distributed parallel-computing libraries like Dask, Pandarallel, Vaex, etc. Modin library or multiprocessing package can be used to execute the Python functions in parallel and speed up the workflow. In my previous articles, I have discussed the hands-on implementation of Dask, Vaex, Modin, multiprocessing libraries. Sometimes we are not willing to use Dask or Vaex library instead of Pandas, or one does not want to write all that extraneous code just to execute few functions in parallel. Can we parallelize the execution of the Python function without much code change? —Yes for sure apply() function in Pandas library allows developers to pass a function and apply it on every single value of the series. The function's execution apply() comes with a huge improvement as it segregates the data according to the conditions required. Usage of apply() function is preferred for Pandas Series rather than the custom calling of the function. In this article, we will discuss how to further parallelize the execution of the apply() function and optimize the time constraints using the Swifter package. Swifter is an open-source package that speeds up the function execution. It can be integrated with Pandas objects for ease of usage. The parallel execution of any function in Python can be done with a single line change of code by integrating the swifter package. Swifter automatically picks the best way to implement the apply() function by either vectorizing or using Dask implementation in the backend to parallelize the execution. For a small size dataset Swifter may choose to execute with Pandas apply() function. The swifter package can be installed from PyPl using pip install swifter and import it using import swifter. I have created a function that performs some random operations on the Pandas Series. Firstly, we will execute the function using apply(): # Call random_function for col1 and col2 columns using apply()df['new_col'] = df.apply(lambda x: random_func(x['col1'], x['col2'])) Now to parallelize the function execution we can integrate the swifter package with Pandas data frame object: # Call random_function for col1 and col2 columns for parallel executiondf['new_col'] = df.swifter.apply(lambda x: random_func(x['col1'], x['col2'])) Just by integrating the keyword swifter, one can parallelize the execution of the function. I have compared the benchmark time numbers for the execution of the function using apply() and by integrating the swifter package with Pandas data frame object then calling apply(). Now let's observe the improvements in the execution speed. The performance is recorded on a system with RAM: 64GB with 10 CPU cores. We can observe from the above plot that after using the swifter package for parallelism, speed-up the workflow by almost 10x times for 65 million data samples. Swifter is a great tool to parallelize the execution of your Python function. It automatically chooses the fastest way to execute your function by either vectorizing or using Dask in the backend. We are getting a 10x faster execution time for 65 million records, which will increase further as sample size increases. It can be a handy tool to optimize the function execution with just one work of code change. One can also use the Python multiprocessing library to execute your custom in parallel, but it will require few lines of change in the code. Read my previous article related to parallelization of optimization of the code: 4 Libraries that can parallelize the existing Pandas ecosystem Speed up your Pandas Workflow with Modin 30 times Faster Python Function Execution with Multiprocessing module 400x times faster Pandas Data Frame Iteration 3x times faster Pandas with PyPolars Optimize Pandas Memory Usage for Large Datasets 20x times faster Grid Search Cross-Validation [1] Swifter GitHub Repository: https://github.com/jmcarpenter2/swifter Thank You for Reading
[ { "code": null, "e": 417, "s": 172, "text": "Pandas is one of the popular Python packages among the data science community, as it offers a vast API and flexible data structures for data explorations and visualization. When it comes to handling and processing large-size datasets, it fails." }, { "code": null, "e": 799, "s": 417, "text": "One can load and process a large-size dataset in chunks or use distributed parallel-computing libraries like Dask, Pandarallel, Vaex, etc. Modin library or multiprocessing package can be used to execute the Python functions in parallel and speed up the workflow. In my previous articles, I have discussed the hands-on implementation of Dask, Vaex, Modin, multiprocessing libraries." }, { "code": null, "e": 973, "s": 799, "text": "Sometimes we are not willing to use Dask or Vaex library instead of Pandas, or one does not want to write all that extraneous code just to execute few functions in parallel." }, { "code": null, "e": 1069, "s": 973, "text": "Can we parallelize the execution of the Python function without much code change? —Yes for sure" }, { "code": null, "e": 1318, "s": 1069, "text": "apply() function in Pandas library allows developers to pass a function and apply it on every single value of the series. The function's execution apply() comes with a huge improvement as it segregates the data according to the conditions required." }, { "code": null, "e": 1582, "s": 1318, "text": "Usage of apply() function is preferred for Pandas Series rather than the custom calling of the function. In this article, we will discuss how to further parallelize the execution of the apply() function and optimize the time constraints using the Swifter package." }, { "code": null, "e": 1846, "s": 1582, "text": "Swifter is an open-source package that speeds up the function execution. It can be integrated with Pandas objects for ease of usage. The parallel execution of any function in Python can be done with a single line change of code by integrating the swifter package." }, { "code": null, "e": 2102, "s": 1846, "text": "Swifter automatically picks the best way to implement the apply() function by either vectorizing or using Dask implementation in the backend to parallelize the execution. For a small size dataset Swifter may choose to execute with Pandas apply() function." }, { "code": null, "e": 2211, "s": 2102, "text": "The swifter package can be installed from PyPl using pip install swifter and import it using import swifter." }, { "code": null, "e": 2349, "s": 2211, "text": "I have created a function that performs some random operations on the Pandas Series. Firstly, we will execute the function using apply():" }, { "code": null, "e": 2481, "s": 2349, "text": "# Call random_function for col1 and col2 columns using apply()df['new_col'] = df.apply(lambda x: random_func(x['col1'], x['col2']))" }, { "code": null, "e": 2591, "s": 2481, "text": "Now to parallelize the function execution we can integrate the swifter package with Pandas data frame object:" }, { "code": null, "e": 2740, "s": 2591, "text": "# Call random_function for col1 and col2 columns for parallel executiondf['new_col'] = df.swifter.apply(lambda x: random_func(x['col1'], x['col2']))" }, { "code": null, "e": 2832, "s": 2740, "text": "Just by integrating the keyword swifter, one can parallelize the execution of the function." }, { "code": null, "e": 3073, "s": 2832, "text": "I have compared the benchmark time numbers for the execution of the function using apply() and by integrating the swifter package with Pandas data frame object then calling apply(). Now let's observe the improvements in the execution speed." }, { "code": null, "e": 3147, "s": 3073, "text": "The performance is recorded on a system with RAM: 64GB with 10 CPU cores." }, { "code": null, "e": 3307, "s": 3147, "text": "We can observe from the above plot that after using the swifter package for parallelism, speed-up the workflow by almost 10x times for 65 million data samples." }, { "code": null, "e": 3503, "s": 3307, "text": "Swifter is a great tool to parallelize the execution of your Python function. It automatically chooses the fastest way to execute your function by either vectorizing or using Dask in the backend." }, { "code": null, "e": 3624, "s": 3503, "text": "We are getting a 10x faster execution time for 65 million records, which will increase further as sample size increases." }, { "code": null, "e": 3858, "s": 3624, "text": "It can be a handy tool to optimize the function execution with just one work of code change. One can also use the Python multiprocessing library to execute your custom in parallel, but it will require few lines of change in the code." }, { "code": null, "e": 3939, "s": 3858, "text": "Read my previous article related to parallelization of optimization of the code:" }, { "code": null, "e": 4002, "s": 3939, "text": "4 Libraries that can parallelize the existing Pandas ecosystem" }, { "code": null, "e": 4043, "s": 4002, "text": "Speed up your Pandas Workflow with Modin" }, { "code": null, "e": 4113, "s": 4043, "text": "30 times Faster Python Function Execution with Multiprocessing module" }, { "code": null, "e": 4159, "s": 4113, "text": "400x times faster Pandas Data Frame Iteration" }, { "code": null, "e": 4196, "s": 4159, "text": "3x times faster Pandas with PyPolars" }, { "code": null, "e": 4244, "s": 4196, "text": "Optimize Pandas Memory Usage for Large Datasets" }, { "code": null, "e": 4290, "s": 4244, "text": "20x times faster Grid Search Cross-Validation" }, { "code": null, "e": 4361, "s": 4290, "text": "[1] Swifter GitHub Repository: https://github.com/jmcarpenter2/swifter" } ]
Is there any way in MongoDB to get the inner value of json data?
To get inner value of JSON data, use find() along with dot(.) notation. Let us create a collection with documents − > db.demo235.insertOne( ... { ... "id":101, ... "details":[ ... { ... "Name":"Chris Brown", ... "Age":21 ... }, ... { ... "Name":"David Miller", ... "Age":24 ... } ... ], ... "otherdetails":[ ... { ... "Score":56, ... "Subject":"MongoDB" ... }, ... { ... "Score":78, ... "Subject":"MySQL" ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e418d22f4cebbeaebec514b") } Display all documents from a collection with the help of find() method − > db.demo235.find().pretty(); This will produce the following output − { "_id" : ObjectId("5e418d22f4cebbeaebec514b"), "id" : 101, "details" : [ { "Name" : "Chris Brown", "Age" : 21 }, { "Name" : "David Miller", "Age" : 24 } ], "otherdetails" : [ { "Score" : 56, "Subject" : "MongoDB" }, { "Score" : 78, "Subject" : "MySQL" } ] } Following is the query to get the inner value of json data − > db.demo235.find({},{"otherdetails.Subject":1,_id:0}); This will produce the following output − { "otherdetails" : [ { "Subject" : "MongoDB" }, { "Subject" : "MySQL" } ] }
[ { "code": null, "e": 1178, "s": 1062, "text": "To get inner value of JSON data, use find() along with dot(.) notation. Let us create a collection with documents −" }, { "code": null, "e": 1757, "s": 1178, "text": "> db.demo235.insertOne(\n... {\n... \"id\":101,\n... \"details\":[\n... {\n... \"Name\":\"Chris Brown\",\n... \"Age\":21\n... },\n... {\n... \"Name\":\"David Miller\",\n... \"Age\":24\n... }\n... ],\n... \"otherdetails\":[\n... {\n... \"Score\":56,\n... \"Subject\":\"MongoDB\"\n... },\n... {\n... \"Score\":78,\n... \"Subject\":\"MySQL\"\n... }\n... ]\n... }\n...);\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e418d22f4cebbeaebec514b\")\n}" }, { "code": null, "e": 1830, "s": 1757, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1860, "s": 1830, "text": "> db.demo235.find().pretty();" }, { "code": null, "e": 1901, "s": 1860, "text": "This will produce the following output −" }, { "code": null, "e": 2298, "s": 1901, "text": "{\n \"_id\" : ObjectId(\"5e418d22f4cebbeaebec514b\"),\n \"id\" : 101,\n \"details\" : [\n {\n \"Name\" : \"Chris Brown\",\n \"Age\" : 21\n },\n {\n \"Name\" : \"David Miller\",\n \"Age\" : 24\n }\n ],\n \"otherdetails\" : [\n {\n \"Score\" : 56,\n \"Subject\" : \"MongoDB\"\n },\n {\n \"Score\" : 78,\n \"Subject\" : \"MySQL\"\n }\n ]\n}" }, { "code": null, "e": 2359, "s": 2298, "text": "Following is the query to get the inner value of json data −" }, { "code": null, "e": 2415, "s": 2359, "text": "> db.demo235.find({},{\"otherdetails.Subject\":1,_id:0});" }, { "code": null, "e": 2456, "s": 2415, "text": "This will produce the following output −" }, { "code": null, "e": 2532, "s": 2456, "text": "{ \"otherdetails\" : [ { \"Subject\" : \"MongoDB\" }, { \"Subject\" : \"MySQL\" } ] }" } ]
What is CGI in Python?
The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers. The current version is CGI/1.1 and CGI/1.2 is under progress. To understand the concept of CGI, let us see what happens when we click a hyper link to browse a particular web page or URL. Your browser contacts the HTTP web server and demands for the URL, i.e., filename. Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file. Web browser takes response from web server and displays either the received file or error message. However, it is possible to set up the HTTP server so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs is sent back for your browser to display. This function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can be a Python Script, PERL Script, Shell Script, C or C++ program, etc. Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI Directory and by convention it is named as /var/www/cgi-bin. By convention, CGI files have extension as. cgi, but you can keep your files with python extension .py as well. By default, the Linux server is configured to run only the scripts in the cgi-bin directory in /var/www. If you want to specify any other directory to run your CGI scripts, comment the following lines in the httpd.conf file − <Directory "/var/www/cgi-bin"> AllowOverride None Options ExecCGI Order allow,deny Allow from all </Directory> <Directory "/var/www/cgi-bin"> Options All </Directory> Here, we assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell, etc.
[ { "code": null, "e": 1204, "s": 1062, "text": "The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers." }, { "code": null, "e": 1266, "s": 1204, "text": "The current version is CGI/1.1 and CGI/1.2 is under progress." }, { "code": null, "e": 1391, "s": 1266, "text": "To understand the concept of CGI, let us see what happens when we click a hyper link to browse a particular web page or URL." }, { "code": null, "e": 1474, "s": 1391, "text": "Your browser contacts the HTTP web server and demands for the URL, i.e., filename." }, { "code": null, "e": 1662, "s": 1474, "text": "Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file." }, { "code": null, "e": 1761, "s": 1662, "text": "Web browser takes response from web server and displays either the received file or error message." }, { "code": null, "e": 2206, "s": 1761, "text": "However, it is possible to set up the HTTP server so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs is sent back for your browser to display. This function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can be a Python Script, PERL Script, Shell Script, C or C++ program, etc." }, { "code": null, "e": 2633, "s": 2206, "text": "Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI Directory and by convention it is named as /var/www/cgi-bin. By convention, CGI files have extension as. cgi, but you can keep your files with python extension .py as well." }, { "code": null, "e": 2859, "s": 2633, "text": "By default, the Linux server is configured to run only the scripts in the cgi-bin directory in /var/www. If you want to specify any other directory to run your CGI scripts, comment the following lines in the httpd.conf file −" }, { "code": null, "e": 3038, "s": 2859, "text": "<Directory \"/var/www/cgi-bin\">\n AllowOverride None\n Options ExecCGI\n Order allow,deny\n Allow from all\n</Directory>\n<Directory \"/var/www/cgi-bin\">\nOptions All\n</Directory>" }, { "code": null, "e": 3178, "s": 3038, "text": "Here, we assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell, etc." } ]
How to change Tkinter Button state from disabled to normal?
Tkinter provides Button widgets to create a button for triggering an event. Let us suppose we have created a button that is already disabled in an application. In order to change the state of the button, we can use the state property. The state property is used to enable and disable a button in an application. In order to change the state of the application, we have two operations: state=DISABLED and state=NORMAL. #Import the required libraries from tkinter import * #Create an instance of tkinter frame win= Tk() #Set the geometry of frame win.geometry("650x450") #Define a function for Button Object def quit_win(): win.destroy() #Create a button to quit the window Button(win,text="Quit", command=quit_win, font=('Helvetica bold',20), state= NORMAL).pack(pady=5) win.mainloop() The output when the button is disabled, Output when Button state=NORMAL
[ { "code": null, "e": 1297, "s": 1062, "text": "Tkinter provides Button widgets to create a button for triggering an event. Let us suppose we have created a button that is already disabled in an application. In order to change the state of the button, we can use the state property." }, { "code": null, "e": 1480, "s": 1297, "text": "The state property is used to enable and disable a button in an application. In order to change the state of the application, we have two operations: state=DISABLED and state=NORMAL." }, { "code": null, "e": 1855, "s": 1480, "text": "#Import the required libraries\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Set the geometry of frame\nwin.geometry(\"650x450\")\n\n#Define a function for Button Object\ndef quit_win():\n win.destroy()\n\n#Create a button to quit the window\nButton(win,text=\"Quit\", command=quit_win, font=('Helvetica bold',20),\nstate= NORMAL).pack(pady=5)\n\nwin.mainloop()" }, { "code": null, "e": 1895, "s": 1855, "text": "The output when the button is disabled," }, { "code": null, "e": 1927, "s": 1895, "text": "Output when Button state=NORMAL" } ]
Find next palindrome prime - GeeksforGeeks
21 May, 2021 Find the smallest palindrome number which is prime too and greater then given number N.Examples: Input : N = 7 Output :11 11 is the smallest palindrome prime which is greater than N. Input : N = 112 Output : 131 A simple approach is to start a loop from N+1. For every number, check if it is palindrome and prime.An efficient solution is based on below observations. All palindrome with even digits is multiple of 11. We can prove as follow: 11 % 11 = 0 1111 % 11 = 0 111111 % 11 = 0 11111111 % 11 = 0So: 1001 % 11 = (1111 – 11 * 10) % 11 = 0 100001 % 11 = (111111 – 1111 * 10) % 11 = 0 10000001 % 11 = (11111111 – 111111 * 10) % 11 = 0For any palindrome with even digits: abcddcba % 11 = (a * 10000001 + b * 100001 * 10 + c * 1001 * 100 + d * 11 * 1000) % 11 = 0All palindrome with even digits is multiple of 11. So among them, 11 is the only one prime if (8 <= N <= 11) return 11 For other, we consider only palindrome with odd digits. C++ Java Python3 C# PHP Javascript // CPP program to find next palindromic// prime for a given number.#include <iostream>#include <string>using namespace std; bool isPrime(int num){ if (num < 2 || num % 2 == 0) return num == 2; for (int i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true;} int primePalindrome(int N){ // if(8<=N<=11) return 11 if (8 <= N && N <= 11) return 11; // generate odd length palindrome number // which will cover given constraint. for (int x = 1; x < 100000; ++x) { string s = to_string(x), r(s.rbegin(), s.rend()); int y = stoi(s + r.substr(1)); // if y>=N and it is a prime number // then return it. if (y >= N && isPrime(y)) return y; } return -1;} // Driver codeint main(){ cout << primePalindrome(112); return 0;} // Java program to find next palindromic// prime for a given number.import java.lang.*;class Geeks { static boolean isPrime(int num){ if (num < 2 || num % 2 == 0) return num == 2; for (int i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true;} static int primePalindrome(int N){ // if(8<=N<=11) return 11 if (8 <= N && N <= 11) return 11; // generate odd length palindrome number // which will cover given constraint. for (int x = 1; x < 100000; ++x) { String s = Integer.toString(x); StringBuffer buffer = new StringBuffer(s); buffer.reverse(); int y = Integer.parseInt(s + buffer.substring(1).toString()); // if y>=N and it is a prime number // then return it. if (y >= N && isPrime(y) == true) return y; } return -1;} // Driver codepublic static void main(String args[]){ System.out.print(primePalindrome(112)); }} # Python3 program to find next palindromic# prime for a given number.import math as mt def isPrime(num): if (num < 2 or num % 2 == 0): return num == 2 for i in range(3, mt.ceil(mt.sqrt(num + 1))): if (num % i == 0): return False return True def primePalindrome(N): # if(8<=N<=11) return 11 if (8 <= N and N <= 11): return 11 # generate odd length palindrome number # which will cover given constraint. for x in range(1, 100000): s = str(x) d = s[::-1] y = int(s + d[1:]) # if y>=N and it is a prime number # then return it. if (y >= N and isPrime(y)): return y # Driver codeprint(primePalindrome(112)) # This code is contributed by# Mohit kumar 29 // C# program to find next palindromic// prime for a given number.using System;using System.Text;using System.Collections; class Geeks { static bool isPrime(int num){ if (num < 2 || num % 2 == 0) return num == 2; for (int i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true;} static int primePalindrome(int N){ // if(8<=N<=11) return 11 if (8 <= N && N <= 11) return 11; // generate odd length palindrome number // which will cover given constraint. for (int x = 1; x < 100000; ++x) { string s = x.ToString(); char[] buffer = s.ToCharArray(); Array.Reverse(buffer); int y = Int32.Parse(s + new string(buffer).Substring(1)); // if y>=N and it is a prime number // then return it. if (y >= N && isPrime(y) == true) return y; } return -1;} // Driver codepublic static void Main(){ Console.WriteLine(primePalindrome(112));}} // This code is contributed by Mithun Kumar. <?php// PHP program to find next palindromic// prime for a given number. function isPrime($num){ if ($num < 2 || $num % 2 == 0) return $num == 2; for ($i = 3; $i * $i <= $num; $i += 2) if ($num % $i == 0) return false; return true;} function primePalindrome($N){ // if(8<=N<=11) return 11 if (8 <= $N && $N <= 11) return 11; // generate odd length palindrome number // which will cover given constraint. for ($x = 1; $x < 100000; ++$x) { $s = strval($x); $r = strrev($s); $y = intval($s.substr($r, 1)); // if y>=N and it is a prime number // then return it. if ($y >= $N && isPrime($y) == true) return $y; } return -1;} // Driver codeprint(primePalindrome(112)); // This code is contributed by mits?> <script>// Javascript program to find next palindromic// prime for a given number. function isPrime(num){ if (num < 2 || num % 2 == 0) return num == 2; for (i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true;} function primePalindrome(N){ // if(8<=N<=11) return 11 if (8 <= N && N <= 11) return 11; // generate odd length palindrome number // which will cover given constraint. for (let x = 1; x < 100000; ++x) { let s = String(x); let r = s.split("").reverse().join(""); let y = parseInt(s + r.substr(1)); // if y>=N and it is a prime number // then return it. if (y >= N && isPrime(y) == true) return y; } return -1;} // Driver codedocument.write(primePalindrome(112)); // This code is contributed by gfgking</script> 131 ankita_saini mohit kumar 29 Mithun Kumar gfgking number-digits palindrome Prime Number Mathematical Mathematical Prime Number palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Find all factors of a natural number | Set 1 Program to find sum of elements in a given array The Knight's tour problem | Backtracking-1 Program for factorial of a number Operators in C / C++ Minimum number of jumps to reach end Find minimum number of coins that make a given value
[ { "code": null, "e": 24177, "s": 24149, "text": "\n21 May, 2021" }, { "code": null, "e": 24276, "s": 24177, "text": "Find the smallest palindrome number which is prime too and greater then given number N.Examples: " }, { "code": null, "e": 24392, "s": 24276, "text": "Input : N = 7\nOutput :11\n11 is the smallest palindrome prime which\nis greater than N.\n\nInput : N = 112\nOutput : 131" }, { "code": null, "e": 25121, "s": 24394, "text": "A simple approach is to start a loop from N+1. For every number, check if it is palindrome and prime.An efficient solution is based on below observations. All palindrome with even digits is multiple of 11. We can prove as follow: 11 % 11 = 0 1111 % 11 = 0 111111 % 11 = 0 11111111 % 11 = 0So: 1001 % 11 = (1111 – 11 * 10) % 11 = 0 100001 % 11 = (111111 – 1111 * 10) % 11 = 0 10000001 % 11 = (11111111 – 111111 * 10) % 11 = 0For any palindrome with even digits: abcddcba % 11 = (a * 10000001 + b * 100001 * 10 + c * 1001 * 100 + d * 11 * 1000) % 11 = 0All palindrome with even digits is multiple of 11. So among them, 11 is the only one prime if (8 <= N <= 11) return 11 For other, we consider only palindrome with odd digits. " }, { "code": null, "e": 25125, "s": 25121, "text": "C++" }, { "code": null, "e": 25130, "s": 25125, "text": "Java" }, { "code": null, "e": 25138, "s": 25130, "text": "Python3" }, { "code": null, "e": 25141, "s": 25138, "text": "C#" }, { "code": null, "e": 25145, "s": 25141, "text": "PHP" }, { "code": null, "e": 25156, "s": 25145, "text": "Javascript" }, { "code": "// CPP program to find next palindromic// prime for a given number.#include <iostream>#include <string>using namespace std; bool isPrime(int num){ if (num < 2 || num % 2 == 0) return num == 2; for (int i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true;} int primePalindrome(int N){ // if(8<=N<=11) return 11 if (8 <= N && N <= 11) return 11; // generate odd length palindrome number // which will cover given constraint. for (int x = 1; x < 100000; ++x) { string s = to_string(x), r(s.rbegin(), s.rend()); int y = stoi(s + r.substr(1)); // if y>=N and it is a prime number // then return it. if (y >= N && isPrime(y)) return y; } return -1;} // Driver codeint main(){ cout << primePalindrome(112); return 0;}", "e": 26014, "s": 25156, "text": null }, { "code": "// Java program to find next palindromic// prime for a given number.import java.lang.*;class Geeks { static boolean isPrime(int num){ if (num < 2 || num % 2 == 0) return num == 2; for (int i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true;} static int primePalindrome(int N){ // if(8<=N<=11) return 11 if (8 <= N && N <= 11) return 11; // generate odd length palindrome number // which will cover given constraint. for (int x = 1; x < 100000; ++x) { String s = Integer.toString(x); StringBuffer buffer = new StringBuffer(s); buffer.reverse(); int y = Integer.parseInt(s + buffer.substring(1).toString()); // if y>=N and it is a prime number // then return it. if (y >= N && isPrime(y) == true) return y; } return -1;} // Driver codepublic static void main(String args[]){ System.out.print(primePalindrome(112)); }}", "e": 27005, "s": 26014, "text": null }, { "code": "# Python3 program to find next palindromic# prime for a given number.import math as mt def isPrime(num): if (num < 2 or num % 2 == 0): return num == 2 for i in range(3, mt.ceil(mt.sqrt(num + 1))): if (num % i == 0): return False return True def primePalindrome(N): # if(8<=N<=11) return 11 if (8 <= N and N <= 11): return 11 # generate odd length palindrome number # which will cover given constraint. for x in range(1, 100000): s = str(x) d = s[::-1] y = int(s + d[1:]) # if y>=N and it is a prime number # then return it. if (y >= N and isPrime(y)): return y # Driver codeprint(primePalindrome(112)) # This code is contributed by# Mohit kumar 29", "e": 27779, "s": 27005, "text": null }, { "code": "// C# program to find next palindromic// prime for a given number.using System;using System.Text;using System.Collections; class Geeks { static bool isPrime(int num){ if (num < 2 || num % 2 == 0) return num == 2; for (int i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true;} static int primePalindrome(int N){ // if(8<=N<=11) return 11 if (8 <= N && N <= 11) return 11; // generate odd length palindrome number // which will cover given constraint. for (int x = 1; x < 100000; ++x) { string s = x.ToString(); char[] buffer = s.ToCharArray(); Array.Reverse(buffer); int y = Int32.Parse(s + new string(buffer).Substring(1)); // if y>=N and it is a prime number // then return it. if (y >= N && isPrime(y) == true) return y; } return -1;} // Driver codepublic static void Main(){ Console.WriteLine(primePalindrome(112));}} // This code is contributed by Mithun Kumar.", "e": 28812, "s": 27779, "text": null }, { "code": "<?php// PHP program to find next palindromic// prime for a given number. function isPrime($num){ if ($num < 2 || $num % 2 == 0) return $num == 2; for ($i = 3; $i * $i <= $num; $i += 2) if ($num % $i == 0) return false; return true;} function primePalindrome($N){ // if(8<=N<=11) return 11 if (8 <= $N && $N <= 11) return 11; // generate odd length palindrome number // which will cover given constraint. for ($x = 1; $x < 100000; ++$x) { $s = strval($x); $r = strrev($s); $y = intval($s.substr($r, 1)); // if y>=N and it is a prime number // then return it. if ($y >= $N && isPrime($y) == true) return $y; } return -1;} // Driver codeprint(primePalindrome(112)); // This code is contributed by mits?>", "e": 29638, "s": 28812, "text": null }, { "code": "<script>// Javascript program to find next palindromic// prime for a given number. function isPrime(num){ if (num < 2 || num % 2 == 0) return num == 2; for (i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true;} function primePalindrome(N){ // if(8<=N<=11) return 11 if (8 <= N && N <= 11) return 11; // generate odd length palindrome number // which will cover given constraint. for (let x = 1; x < 100000; ++x) { let s = String(x); let r = s.split(\"\").reverse().join(\"\"); let y = parseInt(s + r.substr(1)); // if y>=N and it is a prime number // then return it. if (y >= N && isPrime(y) == true) return y; } return -1;} // Driver codedocument.write(primePalindrome(112)); // This code is contributed by gfgking</script>", "e": 30505, "s": 29638, "text": null }, { "code": null, "e": 30509, "s": 30505, "text": "131" }, { "code": null, "e": 30524, "s": 30511, "text": "ankita_saini" }, { "code": null, "e": 30539, "s": 30524, "text": "mohit kumar 29" }, { "code": null, "e": 30552, "s": 30539, "text": "Mithun Kumar" }, { "code": null, "e": 30560, "s": 30552, "text": "gfgking" }, { "code": null, "e": 30574, "s": 30560, "text": "number-digits" }, { "code": null, "e": 30585, "s": 30574, "text": "palindrome" }, { "code": null, "e": 30598, "s": 30585, "text": "Prime Number" }, { "code": null, "e": 30611, "s": 30598, "text": "Mathematical" }, { "code": null, "e": 30624, "s": 30611, "text": "Mathematical" }, { "code": null, "e": 30637, "s": 30624, "text": "Prime Number" }, { "code": null, "e": 30648, "s": 30637, "text": "palindrome" }, { "code": null, "e": 30746, "s": 30648, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30755, "s": 30746, "text": "Comments" }, { "code": null, "e": 30768, "s": 30755, "text": "Old Comments" }, { "code": null, "e": 30792, "s": 30768, "text": "Merge two sorted arrays" }, { "code": null, "e": 30835, "s": 30792, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30849, "s": 30835, "text": "Prime Numbers" }, { "code": null, "e": 30894, "s": 30849, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 30943, "s": 30894, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30986, "s": 30943, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 31020, "s": 30986, "text": "Program for factorial of a number" }, { "code": null, "e": 31041, "s": 31020, "text": "Operators in C / C++" }, { "code": null, "e": 31078, "s": 31041, "text": "Minimum number of jumps to reach end" } ]
Cd cmd command - GeeksforGeeks
30 Sep, 2020 Cd is the abbreviation or synonym for chdir. It is a command found inside the Windows Command Processor (cmd) that allows for change of the current working directory of a shell instance. The CWD (Current Working Directory) is a path (of a directory) inside the file system, where the shell is currently working. The current working directory is essential for resolving relative paths. Cd is a generic command found in the Command Interpreter of most operating systems. Description of the Command :Displays the name of or changes the current directory. CHDIR [/D] [drive:][path] CHDIR [..] CD [/D] [drive:][path] CD [..] .. Specifies that you want to change to the parent directory. Type CD drive: to display the current directory in the specified drive.Type CD without parameters to display the current drive and directory.Use the /D switch to change the current drive in addition to changing the current directory for a drive. Some of the output is truncated due to its large length. In order to obtain the above text execute the cd /? command on cmd. It should be noted that chdir is an alias for cd, and therefore can be replaced for all of its occurrences. Using the Command : Displaying the Current Working Directory :Displaying the current working directory is not generally not required on cmd. This is because the default prompt in cmd displays the Current drive and path (CWD) along with the greater than sign ( > ) at all times ($P$G code). But for the sake of completeness, we would be describing it as well. To display the Current Working Directory, execute the cd command without any arguments.Syntax :cdApparent from the above output, it is not necessary for us to print the cwd as it is already being displayed by the prompt. Throughout the article, we will be using C:\Users as our CWD.Changing the CWD :We can change the Current Working Directory to different paths in the system. The following are the options –1. To a Directory of Current Drive :To change the working directory, execute command cd followed by an absolute or relative path of the directory you are wanting to become the CWD. Where the path should qualify the following criteria –The Path should be of a Directory.The Directory should be existing.Path can be absolute or relative. If a relative path is used, then the path should be relative to the CWD.Syntax :cd [Path]2. To a Directory of Another Drive :To change the working directory to another drive, execute command cd /D followed by a path to a directory. The path should qualify the following criteria –The path should be absolute.The path should contain the drive letter followed by a drive qualifier (DRIVE_LETTER & COLON).Syntax :cd /d [Path]3. An additional way to change the CWD to another drive without the usage of the cd command is to execute the drive letter followed by a colon.Syntax :(Drive_Letter): Displaying the Current Working Directory :Displaying the current working directory is not generally not required on cmd. This is because the default prompt in cmd displays the Current drive and path (CWD) along with the greater than sign ( > ) at all times ($P$G code). But for the sake of completeness, we would be describing it as well. To display the Current Working Directory, execute the cd command without any arguments.Syntax :cdApparent from the above output, it is not necessary for us to print the cwd as it is already being displayed by the prompt. Throughout the article, we will be using C:\Users as our CWD. Syntax : cd Apparent from the above output, it is not necessary for us to print the cwd as it is already being displayed by the prompt. Throughout the article, we will be using C:\Users as our CWD. Changing the CWD :We can change the Current Working Directory to different paths in the system. The following are the options –1. To a Directory of Current Drive :To change the working directory, execute command cd followed by an absolute or relative path of the directory you are wanting to become the CWD. Where the path should qualify the following criteria –The Path should be of a Directory.The Directory should be existing.Path can be absolute or relative. If a relative path is used, then the path should be relative to the CWD.Syntax :cd [Path]2. To a Directory of Another Drive :To change the working directory to another drive, execute command cd /D followed by a path to a directory. The path should qualify the following criteria –The path should be absolute.The path should contain the drive letter followed by a drive qualifier (DRIVE_LETTER & COLON).Syntax :cd /d [Path]3. An additional way to change the CWD to another drive without the usage of the cd command is to execute the drive letter followed by a colon.Syntax :(Drive_Letter): 1. To a Directory of Current Drive :To change the working directory, execute command cd followed by an absolute or relative path of the directory you are wanting to become the CWD. Where the path should qualify the following criteria – The Path should be of a Directory. The Directory should be existing. Path can be absolute or relative. If a relative path is used, then the path should be relative to the CWD. Syntax : cd [Path] 2. To a Directory of Another Drive :To change the working directory to another drive, execute command cd /D followed by a path to a directory. The path should qualify the following criteria – The path should be absolute. The path should contain the drive letter followed by a drive qualifier (DRIVE_LETTER & COLON). Syntax : cd /d [Path] 3. An additional way to change the CWD to another drive without the usage of the cd command is to execute the drive letter followed by a colon. Syntax : (Drive_Letter): Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Page Replacement Algorithms in Operating Systems Program for FCFS CPU Scheduling | Set 1 Program for Round Robin scheduling | Set 1 Introduction of Deadlock in Operating System Inter Process Communication (IPC) Introduction of Operating System - Set 1 Difference between Process and Thread CPU Scheduling in Operating Systems Paging in Operating System Semaphores in Process Synchronization
[ { "code": null, "e": 24774, "s": 24746, "text": "\n30 Sep, 2020" }, { "code": null, "e": 25243, "s": 24774, "text": "Cd is the abbreviation or synonym for chdir. It is a command found inside the Windows Command Processor (cmd) that allows for change of the current working directory of a shell instance. The CWD (Current Working Directory) is a path (of a directory) inside the file system, where the shell is currently working. The current working directory is essential for resolving relative paths. Cd is a generic command found in the Command Interpreter of most operating systems." }, { "code": null, "e": 25326, "s": 25243, "text": "Description of the Command :Displays the name of or changes the current directory." }, { "code": null, "e": 25459, "s": 25326, "text": "CHDIR [/D] [drive:][path]\nCHDIR [..]\nCD [/D] [drive:][path]\nCD [..]\n\n.. Specifies that you want to change to the parent directory." }, { "code": null, "e": 25705, "s": 25459, "text": "Type CD drive: to display the current directory in the specified drive.Type CD without parameters to display the current drive and directory.Use the /D switch to change the current drive in addition to changing the current directory for a drive." }, { "code": null, "e": 25762, "s": 25705, "text": "Some of the output is truncated due to its large length." }, { "code": null, "e": 25830, "s": 25762, "text": "In order to obtain the above text execute the cd /? command on cmd." }, { "code": null, "e": 25938, "s": 25830, "text": "It should be noted that chdir is an alias for cd, and therefore can be replaced for all of its occurrences." }, { "code": null, "e": 25958, "s": 25938, "text": "Using the Command :" }, { "code": null, "e": 27631, "s": 25958, "text": "Displaying the Current Working Directory :Displaying the current working directory is not generally not required on cmd. This is because the default prompt in cmd displays the Current drive and path (CWD) along with the greater than sign ( > ) at all times ($P$G code). But for the sake of completeness, we would be describing it as well. To display the Current Working Directory, execute the cd command without any arguments.Syntax :cdApparent from the above output, it is not necessary for us to print the cwd as it is already being displayed by the prompt. Throughout the article, we will be using C:\\Users as our CWD.Changing the CWD :We can change the Current Working Directory to different paths in the system. The following are the options –1. To a Directory of Current Drive :To change the working directory, execute command cd followed by an absolute or relative path of the directory you are wanting to become the CWD. Where the path should qualify the following criteria –The Path should be of a Directory.The Directory should be existing.Path can be absolute or relative. If a relative path is used, then the path should be relative to the CWD.Syntax :cd [Path]2. To a Directory of Another Drive :To change the working directory to another drive, execute command cd /D followed by a path to a directory. The path should qualify the following criteria –The path should be absolute.The path should contain the drive letter followed by a drive qualifier (DRIVE_LETTER & COLON).Syntax :cd /d [Path]3. An additional way to change the CWD to another drive without the usage of the cd command is to execute the drive letter followed by a colon.Syntax :(Drive_Letter):" }, { "code": null, "e": 28253, "s": 27631, "text": "Displaying the Current Working Directory :Displaying the current working directory is not generally not required on cmd. This is because the default prompt in cmd displays the Current drive and path (CWD) along with the greater than sign ( > ) at all times ($P$G code). But for the sake of completeness, we would be describing it as well. To display the Current Working Directory, execute the cd command without any arguments.Syntax :cdApparent from the above output, it is not necessary for us to print the cwd as it is already being displayed by the prompt. Throughout the article, we will be using C:\\Users as our CWD." }, { "code": null, "e": 28262, "s": 28253, "text": "Syntax :" }, { "code": null, "e": 28265, "s": 28262, "text": "cd" }, { "code": null, "e": 28451, "s": 28265, "text": "Apparent from the above output, it is not necessary for us to print the cwd as it is already being displayed by the prompt. Throughout the article, we will be using C:\\Users as our CWD." }, { "code": null, "e": 29503, "s": 28451, "text": "Changing the CWD :We can change the Current Working Directory to different paths in the system. The following are the options –1. To a Directory of Current Drive :To change the working directory, execute command cd followed by an absolute or relative path of the directory you are wanting to become the CWD. Where the path should qualify the following criteria –The Path should be of a Directory.The Directory should be existing.Path can be absolute or relative. If a relative path is used, then the path should be relative to the CWD.Syntax :cd [Path]2. To a Directory of Another Drive :To change the working directory to another drive, execute command cd /D followed by a path to a directory. The path should qualify the following criteria –The path should be absolute.The path should contain the drive letter followed by a drive qualifier (DRIVE_LETTER & COLON).Syntax :cd /d [Path]3. An additional way to change the CWD to another drive without the usage of the cd command is to execute the drive letter followed by a colon.Syntax :(Drive_Letter):" }, { "code": null, "e": 29739, "s": 29503, "text": "1. To a Directory of Current Drive :To change the working directory, execute command cd followed by an absolute or relative path of the directory you are wanting to become the CWD. Where the path should qualify the following criteria –" }, { "code": null, "e": 29774, "s": 29739, "text": "The Path should be of a Directory." }, { "code": null, "e": 29808, "s": 29774, "text": "The Directory should be existing." }, { "code": null, "e": 29915, "s": 29808, "text": "Path can be absolute or relative. If a relative path is used, then the path should be relative to the CWD." }, { "code": null, "e": 29924, "s": 29915, "text": "Syntax :" }, { "code": null, "e": 29934, "s": 29924, "text": "cd [Path]" }, { "code": null, "e": 30126, "s": 29934, "text": "2. To a Directory of Another Drive :To change the working directory to another drive, execute command cd /D followed by a path to a directory. The path should qualify the following criteria –" }, { "code": null, "e": 30155, "s": 30126, "text": "The path should be absolute." }, { "code": null, "e": 30250, "s": 30155, "text": "The path should contain the drive letter followed by a drive qualifier (DRIVE_LETTER & COLON)." }, { "code": null, "e": 30259, "s": 30250, "text": "Syntax :" }, { "code": null, "e": 30272, "s": 30259, "text": "cd /d [Path]" }, { "code": null, "e": 30416, "s": 30272, "text": "3. An additional way to change the CWD to another drive without the usage of the cd command is to execute the drive letter followed by a colon." }, { "code": null, "e": 30425, "s": 30416, "text": "Syntax :" }, { "code": null, "e": 30441, "s": 30425, "text": "(Drive_Letter):" }, { "code": null, "e": 30459, "s": 30441, "text": "Operating Systems" }, { "code": null, "e": 30477, "s": 30459, "text": "Operating Systems" }, { "code": null, "e": 30575, "s": 30477, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30584, "s": 30575, "text": "Comments" }, { "code": null, "e": 30597, "s": 30584, "text": "Old Comments" }, { "code": null, "e": 30646, "s": 30597, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 30686, "s": 30646, "text": "Program for FCFS CPU Scheduling | Set 1" }, { "code": null, "e": 30729, "s": 30686, "text": "Program for Round Robin scheduling | Set 1" }, { "code": null, "e": 30774, "s": 30729, "text": "Introduction of Deadlock in Operating System" }, { "code": null, "e": 30808, "s": 30774, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 30849, "s": 30808, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 30887, "s": 30849, "text": "Difference between Process and Thread" }, { "code": null, "e": 30923, "s": 30887, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 30950, "s": 30923, "text": "Paging in Operating System" } ]
SQL Relationships With SQLAlchemy | by Mike Wolfe | Towards Data Science
A couple of weeks ago, I wrote an article about leveraging the power of Entity Framework to minimize having to do complicated Linq queries. Essentially, the solution was to create configurations for each table in the database and then define the relationship between the tables within the configuration. It wasn’t exactly an easy task. In fact, it was a little confusing. But it got me thinking if something similar could be accomplished using SQLAlchemy for Python. In our scenario, we have a database containing three tables, Application, ApplicationRunner, and ApplicationLog. The Application table contains a foreign key called ApplicationRunnerId. This key creates a one-to-one relationship between the Application and ApplicationRunner tables. As for the ApplicationLog table, it holds a foreign key to the Application table specifying a one-to-many relationship. Taking a look at our current code, all of the heavy lifting of determining table attributes and relationships is being automatically handled by SQLAlchemy. As for getting the data, we have to either manually query each table, or use a join method. For the sake of simplicity, we are manually querying each table. Instead of being lazy and letting SQLAlchemy do all the hard work, we can take more of a code-first approach and create manual configurations for our tables. Before we can start modifying the table classes, there are a few extra things we need to import. The first will allow us to define different types for the table attributes, while the second gives us the functionality to create relationships between tables. from sqlalchemy import Column, ForeignKey, Integer, String, Numeric, DateTime, ForeignKey, CHAR, Tablefrom sqlalchemy.orm import relationship Once imported, we can start working on the Application table by defining all the attributes and setting a primary key. The attribute types will match what the field type is in the database (INT will be Integer, VARCHAR will be String, etc.). class Application(Base): __tablename__ = "Application" ApplicationId = Column(Integer, primary_key=True) ApplicationName = Column(String(100), nullable=False) Next, the ApplicationRunner table. class ApplicationRunner(Base): __tablename__ = "ApplicationRunner" ApplicationRunnerId = Column(Integer, primary_key=True) ApplicationRunnerName = Column(String(50), nullable=False) Before going any further, we need to create a one-to-one relationship between these two tables. To start off, we will need to add a foreign key to the Application table. ApplicationRunnerId = Column(Integer, ForeignKey("ApplicationRunner.ApplicationRunnerId")) Then, we will add a new class attribute to create a relationship with the ApplicationRunner table. This relationship is special because we will utilize lazy joined loading. Essentially, lazy loading is the objects that are returned from a query without their related objects loaded in. Once the related objects are referenced, another SELECT statement will be run to load in the requested object. As for the “joined”, this adds a JOIN to the initial SELECT to keep everything in the same result set. Runner = relationship("ApplicationRunner", lazy="joined") The next thing we need to do is add a relationship to the ApplicationRunner table. While doing so, we need to make sure this relationship will back reference the ApplicationRunner table and that it does not need a list of objects since it's a one-to-one relationship. ApplicationRelationship = relationship("Application", backref="ApplicationRunner", uselist=False) Now that we have these tables defined and configured, we can move on to the ApplicationLog table. Just like we did with the previous two tables, the attributes and primary key need to be defined first. class ApplicationLog(Base): ApplicationLogId - Column(Integer, primary_key=True) ApplicationLogMessage - Column(String(250), nullable=False) Again, in order to create the relationship, a foreign key is needed in this new table. ApplicationId = Column(Integer, ForeignKey("Application.ApplicationId")) Lastly, the one-to-many relationship will look like this for the ApplicationLog table. ApplicationRelationship = relationship("Application", backref="ApplicationLog", uselist=True) But for the application table, it will look like this. Log = relationship(“ApplicationLog”, lazy=”joined”) With everything finally set up, we can run a query to get our data. application = session.query(Application).filter(Application.ApplicationId == command.ApplicationId).one() Getting data from the Application table can be easily done. print(application.the_attribute) But, if you’re looking to access the data from the ApplicationRunner table: print(application.ApplicationRunner.the_attribute) Finally, to view the records from the ApplicationLog table, a FOR loop will be needed. for item in application.ApplicationLog: print(item.the_attribute) Right off the bat, you’ll notice that setting up the configurations takes way longer than having SQLAlchemy automatically handle it for you. Just like in Entity Framework, it can also be a little confusing/complicated to get things up and running. However, this process wasn’t all bad. By configuring the tables through a code-first view, it removes some of the black box that SQLAlchemy can be and give more power back to the developer. With that being said though, it does create more mystery around the querying side since you can’t see the extra joins or selects. All in all, I thought this was a very enlightening and fun experience. It definitely answered my questions regarding SQLAlchemy’s abilities. However, at the same time, it also brought up some new questions about performance. As someone who writes a lot of APIs where fast requests are a necessity, would this kind of query and configuring be advisable. Let me know what your thoughts are about SQLAlchemy and configuring table relationships within it. In a future post, I plan on exploring these performance questions. Until the next time, happy coding and cheers! Read all my articles for free with my weekly newsletter, thanks! Want to read all articles on Medium? Become a Medium member today! Check out some of my recent articles:
[ { "code": null, "e": 638, "s": 171, "text": "A couple of weeks ago, I wrote an article about leveraging the power of Entity Framework to minimize having to do complicated Linq queries. Essentially, the solution was to create configurations for each table in the database and then define the relationship between the tables within the configuration. It wasn’t exactly an easy task. In fact, it was a little confusing. But it got me thinking if something similar could be accomplished using SQLAlchemy for Python." }, { "code": null, "e": 1041, "s": 638, "text": "In our scenario, we have a database containing three tables, Application, ApplicationRunner, and ApplicationLog. The Application table contains a foreign key called ApplicationRunnerId. This key creates a one-to-one relationship between the Application and ApplicationRunner tables. As for the ApplicationLog table, it holds a foreign key to the Application table specifying a one-to-many relationship." }, { "code": null, "e": 1197, "s": 1041, "text": "Taking a look at our current code, all of the heavy lifting of determining table attributes and relationships is being automatically handled by SQLAlchemy." }, { "code": null, "e": 1354, "s": 1197, "text": "As for getting the data, we have to either manually query each table, or use a join method. For the sake of simplicity, we are manually querying each table." }, { "code": null, "e": 1512, "s": 1354, "text": "Instead of being lazy and letting SQLAlchemy do all the hard work, we can take more of a code-first approach and create manual configurations for our tables." }, { "code": null, "e": 1769, "s": 1512, "text": "Before we can start modifying the table classes, there are a few extra things we need to import. The first will allow us to define different types for the table attributes, while the second gives us the functionality to create relationships between tables." }, { "code": null, "e": 1911, "s": 1769, "text": "from sqlalchemy import Column, ForeignKey, Integer, String, Numeric, DateTime, ForeignKey, CHAR, Tablefrom sqlalchemy.orm import relationship" }, { "code": null, "e": 2153, "s": 1911, "text": "Once imported, we can start working on the Application table by defining all the attributes and setting a primary key. The attribute types will match what the field type is in the database (INT will be Integer, VARCHAR will be String, etc.)." }, { "code": null, "e": 2324, "s": 2153, "text": "class Application(Base): __tablename__ = \"Application\" ApplicationId = Column(Integer, primary_key=True) ApplicationName = Column(String(100), nullable=False)" }, { "code": null, "e": 2359, "s": 2324, "text": "Next, the ApplicationRunner table." }, { "code": null, "e": 2553, "s": 2359, "text": "class ApplicationRunner(Base): __tablename__ = \"ApplicationRunner\" ApplicationRunnerId = Column(Integer, primary_key=True) ApplicationRunnerName = Column(String(50), nullable=False)" }, { "code": null, "e": 2723, "s": 2553, "text": "Before going any further, we need to create a one-to-one relationship between these two tables. To start off, we will need to add a foreign key to the Application table." }, { "code": null, "e": 2814, "s": 2723, "text": "ApplicationRunnerId = Column(Integer, ForeignKey(\"ApplicationRunner.ApplicationRunnerId\"))" }, { "code": null, "e": 3314, "s": 2814, "text": "Then, we will add a new class attribute to create a relationship with the ApplicationRunner table. This relationship is special because we will utilize lazy joined loading. Essentially, lazy loading is the objects that are returned from a query without their related objects loaded in. Once the related objects are referenced, another SELECT statement will be run to load in the requested object. As for the “joined”, this adds a JOIN to the initial SELECT to keep everything in the same result set." }, { "code": null, "e": 3372, "s": 3314, "text": "Runner = relationship(\"ApplicationRunner\", lazy=\"joined\")" }, { "code": null, "e": 3640, "s": 3372, "text": "The next thing we need to do is add a relationship to the ApplicationRunner table. While doing so, we need to make sure this relationship will back reference the ApplicationRunner table and that it does not need a list of objects since it's a one-to-one relationship." }, { "code": null, "e": 3738, "s": 3640, "text": "ApplicationRelationship = relationship(\"Application\", backref=\"ApplicationRunner\", uselist=False)" }, { "code": null, "e": 3940, "s": 3738, "text": "Now that we have these tables defined and configured, we can move on to the ApplicationLog table. Just like we did with the previous two tables, the attributes and primary key need to be defined first." }, { "code": null, "e": 4089, "s": 3940, "text": "class ApplicationLog(Base): ApplicationLogId - Column(Integer, primary_key=True) ApplicationLogMessage - Column(String(250), nullable=False)" }, { "code": null, "e": 4176, "s": 4089, "text": "Again, in order to create the relationship, a foreign key is needed in this new table." }, { "code": null, "e": 4249, "s": 4176, "text": "ApplicationId = Column(Integer, ForeignKey(\"Application.ApplicationId\"))" }, { "code": null, "e": 4336, "s": 4249, "text": "Lastly, the one-to-many relationship will look like this for the ApplicationLog table." }, { "code": null, "e": 4430, "s": 4336, "text": "ApplicationRelationship = relationship(\"Application\", backref=\"ApplicationLog\", uselist=True)" }, { "code": null, "e": 4485, "s": 4430, "text": "But for the application table, it will look like this." }, { "code": null, "e": 4537, "s": 4485, "text": "Log = relationship(“ApplicationLog”, lazy=”joined”)" }, { "code": null, "e": 4605, "s": 4537, "text": "With everything finally set up, we can run a query to get our data." }, { "code": null, "e": 4711, "s": 4605, "text": "application = session.query(Application).filter(Application.ApplicationId == command.ApplicationId).one()" }, { "code": null, "e": 4771, "s": 4711, "text": "Getting data from the Application table can be easily done." }, { "code": null, "e": 4804, "s": 4771, "text": "print(application.the_attribute)" }, { "code": null, "e": 4880, "s": 4804, "text": "But, if you’re looking to access the data from the ApplicationRunner table:" }, { "code": null, "e": 4931, "s": 4880, "text": "print(application.ApplicationRunner.the_attribute)" }, { "code": null, "e": 5018, "s": 4931, "text": "Finally, to view the records from the ApplicationLog table, a FOR loop will be needed." }, { "code": null, "e": 5088, "s": 5018, "text": "for item in application.ApplicationLog: print(item.the_attribute)" }, { "code": null, "e": 5656, "s": 5088, "text": "Right off the bat, you’ll notice that setting up the configurations takes way longer than having SQLAlchemy automatically handle it for you. Just like in Entity Framework, it can also be a little confusing/complicated to get things up and running. However, this process wasn’t all bad. By configuring the tables through a code-first view, it removes some of the black box that SQLAlchemy can be and give more power back to the developer. With that being said though, it does create more mystery around the querying side since you can’t see the extra joins or selects." }, { "code": null, "e": 6221, "s": 5656, "text": "All in all, I thought this was a very enlightening and fun experience. It definitely answered my questions regarding SQLAlchemy’s abilities. However, at the same time, it also brought up some new questions about performance. As someone who writes a lot of APIs where fast requests are a necessity, would this kind of query and configuring be advisable. Let me know what your thoughts are about SQLAlchemy and configuring table relationships within it. In a future post, I plan on exploring these performance questions. Until the next time, happy coding and cheers!" }, { "code": null, "e": 6286, "s": 6221, "text": "Read all my articles for free with my weekly newsletter, thanks!" }, { "code": null, "e": 6353, "s": 6286, "text": "Want to read all articles on Medium? Become a Medium member today!" } ]
Very simple Python script for extracting most common words from a story | by Tirthajyoti Sarkar | Towards Data Science
What is the most used word in all of Shakespeare plays? Was ‘king’ more often used than ‘Lord’ or vice versa? To answer these type of fun questions, one often needs to quickly examine and plot most frequent words in a text file (often downloaded from open source portals such as Project Gutenberg). However, if you search on the web or on Stackoverflow, you will most probably see examples of nltk and use of CountVectorizer. While they are incredibly powerful and fun to use, the matter of the fact is, you don’t need them if the only thing you want is to extract most common words appearing in a single text corpus. Below, I am showing a very simple Python 3 code snippet to do just that — using only a dictionary and simple string manipulation methods. Feel free to copy the code and use your own stopwords to make it better! import collectionsimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inline# Read input file, note the encoding is specified here # It may be different in your text filefile = open('PrideandPrejudice.txt', encoding="utf8")a= file.read()# Stopwordsstopwords = set(line.strip() for line in open('stopwords.txt'))stopwords = stopwords.union(set(['mr','mrs','one','two','said']))# Instantiate a dictionary, and for every word in the file, # Add to the dictionary if it doesn't exist. If it does, increase the count.wordcount = {}# To eliminate duplicates, remember to split by punctuation, and use case demiliters.for word in a.lower().split(): word = word.replace(".","") word = word.replace(",","") word = word.replace(":","") word = word.replace("\"","") word = word.replace("!","") word = word.replace("“","") word = word.replace("†̃","") word = word.replace("*","") if word not in stopwords: if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1# Print most common wordn_print = int(input("How many most common words to print: "))print("\nOK. The {} most common words are as follows\n".format(n_print))word_counter = collections.Counter(wordcount)for word, count in word_counter.most_common(n_print): print(word, ": ", count)# Close the filefile.close()# Create a data frame of the most common words # Draw a bar chartlst = word_counter.most_common(n_print)df = pd.DataFrame(lst, columns = ['Word', 'Count'])df.plot.bar(x='Word',y='Count') An example of the code output and plot of the 10 most frequently used words in the corpus. The text is ‘Pride and Prejudice’ and you can see the familiar names of Elizabeth and Mr. Darcy! :) Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
[ { "code": null, "e": 282, "s": 172, "text": "What is the most used word in all of Shakespeare plays? Was ‘king’ more often used than ‘Lord’ or vice versa?" }, { "code": null, "e": 790, "s": 282, "text": "To answer these type of fun questions, one often needs to quickly examine and plot most frequent words in a text file (often downloaded from open source portals such as Project Gutenberg). However, if you search on the web or on Stackoverflow, you will most probably see examples of nltk and use of CountVectorizer. While they are incredibly powerful and fun to use, the matter of the fact is, you don’t need them if the only thing you want is to extract most common words appearing in a single text corpus." }, { "code": null, "e": 928, "s": 790, "text": "Below, I am showing a very simple Python 3 code snippet to do just that — using only a dictionary and simple string manipulation methods." }, { "code": null, "e": 1001, "s": 928, "text": "Feel free to copy the code and use your own stopwords to make it better!" }, { "code": null, "e": 2544, "s": 1001, "text": "import collectionsimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inline# Read input file, note the encoding is specified here # It may be different in your text filefile = open('PrideandPrejudice.txt', encoding=\"utf8\")a= file.read()# Stopwordsstopwords = set(line.strip() for line in open('stopwords.txt'))stopwords = stopwords.union(set(['mr','mrs','one','two','said']))# Instantiate a dictionary, and for every word in the file, # Add to the dictionary if it doesn't exist. If it does, increase the count.wordcount = {}# To eliminate duplicates, remember to split by punctuation, and use case demiliters.for word in a.lower().split(): word = word.replace(\".\",\"\") word = word.replace(\",\",\"\") word = word.replace(\":\",\"\") word = word.replace(\"\\\"\",\"\") word = word.replace(\"!\",\"\") word = word.replace(\"“\",\"\") word = word.replace(\"†̃\",\"\") word = word.replace(\"*\",\"\") if word not in stopwords: if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1# Print most common wordn_print = int(input(\"How many most common words to print: \"))print(\"\\nOK. The {} most common words are as follows\\n\".format(n_print))word_counter = collections.Counter(wordcount)for word, count in word_counter.most_common(n_print): print(word, \": \", count)# Close the filefile.close()# Create a data frame of the most common words # Draw a bar chartlst = word_counter.most_common(n_print)df = pd.DataFrame(lst, columns = ['Word', 'Count'])df.plot.bar(x='Word',y='Count')" }, { "code": null, "e": 2735, "s": 2544, "text": "An example of the code output and plot of the 10 most frequently used words in the corpus. The text is ‘Pride and Prejudice’ and you can see the familiar names of Elizabeth and Mr. Darcy! :)" } ]