title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to define where to navigate when using the arrow keys in CSS ?
26 May, 2021 In this article, we will learn how to define where to navigate when using the arrow keys in CSS. Approach: We can do this task by using nav-up, nav-down, nav-right, and nav-up CSS properties together. These properties are used to navigate through the navigation key from the keyboard. The properties define where to focus when the user is navigating by using the navigation key. So by using these four properties we can do this task in the following steps: When we are on the left button we will set the nav-right and nav-down value to #Geeks2 which is the upper button and the nav-left and nav-up value to #Geeks4 which is the down button. Same as we do with other buttons, we can navigate through the navigation key from the keyboard. Syntax: nav-up: auto | id | target-name | initial | inherit; nav-down: auto | id | target-name | initial | inherit; nav-right: auto | id | target-name | initial | inherit; nav-left: auto | id | target-name | initial | inherit; Note: Only Opera 12.0 is supported by these properties. Example: HTML <!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> body{ font-size: 30px; } button { position: absolute; } h1 { color: green; } button { background-color: rgb(153, 153, 153); border-radius: 25px; font-size: 20px; } /*When we are on Left button we change it's navigation using nav properties*/ #Geeks1 { nav-right: #Geeks2; nav-left: #Geeks4; nav-down: #Geeks2; nav-up: #Geeks4; top: 35%; left: 43%; nav-index: 1; } /*When we are on top button we change it's navigation using nav properties*/ #Geeks2 { nav-right: #Geeks3; nav-left: #Geeks1; nav-down: #Geeks3; nav-up: #Geeks1; top: 50%; left: 65%; nav-index: 2; } /*When we are on right button we change it's navigation using nav properties*/ #Geeks3 { nav-right: #Geeks4; nav-left: #Geeks2; nav-down: #Geeks4; nav-up: #Geeks2; top: 65%; left: 43%; nav-index: 3; } /*When we are on bottom button we change it's navigation using nav properties*/ #Geeks4 { nav-right: #Geeks1; nav-left: #Geeks3; nav-down: #Geeks1; nav-up: #Geeks3; top: 50%; left: 20%; nav-index: 4; } </style></head> <body> <center> <h2>GeeksforGeeks</h2> <p> Press the <samp>Shift</samp> key while navigating with the arrow keys. </p> </center> <button id="Geeks1">Up <i class="fa fa-arrow-up"></i> </button> <button id="Geeks2">Right <i class="fa fa-arrow-right"></i> </button> <button id="Geeks3">Down <i class="fa fa-arrow-down"></i> </button> <button id="Geeks4">Left <i class="fa fa-arrow-left"></i> </button> </body> </html> Output: arrow keys CSS-Properties CSS-Questions Picked CSS Web Technologies 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 Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2021" }, { "code": null, "e": 125, "s": 28, "text": "In this article, we will learn how to define where to navigate when using the arrow keys in CSS." }, { "code": null, "e": 485, "s": 125, "text": "Approach: We can do this task by using nav-up, nav-down, nav-right, and nav-up CSS properties together. These properties are used to navigate through the navigation key from the keyboard. The properties define where to focus when the user is navigating by using the navigation key. So by using these four properties we can do this task in the following steps:" }, { "code": null, "e": 669, "s": 485, "text": "When we are on the left button we will set the nav-right and nav-down value to #Geeks2 which is the upper button and the nav-left and nav-up value to #Geeks4 which is the down button." }, { "code": null, "e": 765, "s": 669, "text": "Same as we do with other buttons, we can navigate through the navigation key from the keyboard." }, { "code": null, "e": 773, "s": 765, "text": "Syntax:" }, { "code": null, "e": 992, "s": 773, "text": "nav-up: auto | id | target-name | initial | inherit;\nnav-down: auto | id | target-name | initial | inherit;\nnav-right: auto | id | target-name | initial | inherit;\nnav-left: auto | id | target-name | initial | inherit;" }, { "code": null, "e": 1048, "s": 992, "text": "Note: Only Opera 12.0 is supported by these properties." }, { "code": null, "e": 1057, "s": 1048, "text": "Example:" }, { "code": null, "e": 1062, "s": 1057, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <style> body{ font-size: 30px; } button { position: absolute; } h1 { color: green; } button { background-color: rgb(153, 153, 153); border-radius: 25px; font-size: 20px; } /*When we are on Left button we change it's navigation using nav properties*/ #Geeks1 { nav-right: #Geeks2; nav-left: #Geeks4; nav-down: #Geeks2; nav-up: #Geeks4; top: 35%; left: 43%; nav-index: 1; } /*When we are on top button we change it's navigation using nav properties*/ #Geeks2 { nav-right: #Geeks3; nav-left: #Geeks1; nav-down: #Geeks3; nav-up: #Geeks1; top: 50%; left: 65%; nav-index: 2; } /*When we are on right button we change it's navigation using nav properties*/ #Geeks3 { nav-right: #Geeks4; nav-left: #Geeks2; nav-down: #Geeks4; nav-up: #Geeks2; top: 65%; left: 43%; nav-index: 3; } /*When we are on bottom button we change it's navigation using nav properties*/ #Geeks4 { nav-right: #Geeks1; nav-left: #Geeks3; nav-down: #Geeks1; nav-up: #Geeks3; top: 50%; left: 20%; nav-index: 4; } </style></head> <body> <center> <h2>GeeksforGeeks</h2> <p> Press the <samp>Shift</samp> key while navigating with the arrow keys. </p> </center> <button id=\"Geeks1\">Up <i class=\"fa fa-arrow-up\"></i> </button> <button id=\"Geeks2\">Right <i class=\"fa fa-arrow-right\"></i> </button> <button id=\"Geeks3\">Down <i class=\"fa fa-arrow-down\"></i> </button> <button id=\"Geeks4\">Left <i class=\"fa fa-arrow-left\"></i> </button> </body> </html>", "e": 3292, "s": 1062, "text": null }, { "code": null, "e": 3300, "s": 3292, "text": "Output:" }, { "code": null, "e": 3311, "s": 3300, "text": "arrow keys" }, { "code": null, "e": 3326, "s": 3311, "text": "CSS-Properties" }, { "code": null, "e": 3340, "s": 3326, "text": "CSS-Questions" }, { "code": null, "e": 3347, "s": 3340, "text": "Picked" }, { "code": null, "e": 3351, "s": 3347, "text": "CSS" }, { "code": null, "e": 3368, "s": 3351, "text": "Web Technologies" }, { "code": null, "e": 3466, "s": 3368, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3505, "s": 3466, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3544, "s": 3505, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3583, "s": 3544, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3620, "s": 3583, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 3649, "s": 3620, "text": "Form validation using jQuery" }, { "code": null, "e": 3682, "s": 3649, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3743, "s": 3682, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3786, "s": 3743, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3858, "s": 3786, "text": "Differences between Functional Components and Class Components in React" } ]
Frequent Item set in Data set (Association Rule Mining)
09 Jun, 2022 Association Mining searches for frequent items in the data-set. In frequent mining usually the interesting associations and correlations between item sets in transactional and relational databases are found. In short, Frequent Mining shows which items appear together in a transaction or relation. Need of Association Mining: Frequent mining is generation of association rules from a Transactional Dataset. If there are 2 items X and Y purchased frequently then its good to put them together in stores or provide some discount offer on one item on purchase of other item. This can really increase the sales. For example it is likely to find that if a customer buys Milk and bread he/she also buys Butter. So the association rule is [‘milk]^[‘bread’]=>[‘butter’]. So seller can suggest the customer to buy butter if he/she buys Milk and Bread. Support : It is one of the measure of interestingness. This tells about usefulness and certainty of rules. 5% Support means total 5% of transactions in database follow the rule. Support(A -> B) = Support_count(A ∪ B) Confidence: A confidence of 60% means that 60% of the customers who purchased a milk and bread also bought butter. Confidence(A -> B) = Support_count(A ∪ B) / Support_count(A) If a rule satisfies both minimum support and minimum confidence, it is a strong rule. Support_count(X) : Number of transactions in which X appears. If X is A union B then it is the number of transactions in which A and B both are present. Maximal Itemset: An itemset is maximal frequent if none of its supersets are frequent. Closed Itemset:An itemset is closed if none of its immediate supersets have same support count same as Itemset. K- Itemset:Itemset which contains K items is a K-itemset. So it can be said that an itemset is frequent if the corresponding support count is greater than minimum support count. Example On finding Frequent Itemsets – Consider the given dataset with given transactions. Lets say minimum support count is 3 Relation hold is maximal frequent => closed => frequent 1-frequent: {A} = 3; // not closed due to {A, C} and not maximal {B} = 4; // not closed due to {B, D} and no maximal {C} = 4; // not closed due to {C, D} not maximal {D} = 5; // closed item-set since not immediate super-set has same count. Not maximal 2-frequent: {A, B} = 2 // not frequent because support count < minimum support count so ignore {A, C} = 3 // not closed due to {A, C, D} {A, D} = 3 // not closed due to {A, C, D} {B, C} = 3 // not closed due to {B, C, D} {B, D} = 4 // closed but not maximal due to {B, C, D} {C, D} = 4 // closed but not maximal due to {B, C, D} 3-frequent: {A, B, C} = 2 // ignore not frequent because support count < minimum support count {A, B, D} = 2 // ignore not frequent because support count < minimum support count {A, C, D} = 3 // maximal frequent {B, C, D} = 3 // maximal frequent 4-frequent: {A, B, C, D} = 2 //ignore not frequent </ kshitijjain2 simmytarika5 data mining Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jun, 2022" }, { "code": null, "e": 897, "s": 54, "text": "Association Mining searches for frequent items in the data-set. In frequent mining usually the interesting associations and correlations between item sets in transactional and relational databases are found. In short, Frequent Mining shows which items appear together in a transaction or relation. Need of Association Mining: Frequent mining is generation of association rules from a Transactional Dataset. If there are 2 items X and Y purchased frequently then its good to put them together in stores or provide some discount offer on one item on purchase of other item. This can really increase the sales. For example it is likely to find that if a customer buys Milk and bread he/she also buys Butter. So the association rule is [‘milk]^[‘bread’]=>[‘butter’]. So seller can suggest the customer to buy butter if he/she buys Milk and Bread." }, { "code": null, "e": 1075, "s": 897, "text": "Support : It is one of the measure of interestingness. This tells about usefulness and certainty of rules. 5% Support means total 5% of transactions in database follow the rule." }, { "code": null, "e": 1116, "s": 1077, "text": "Support(A -> B) = Support_count(A ∪ B)" }, { "code": null, "e": 1231, "s": 1116, "text": "Confidence: A confidence of 60% means that 60% of the customers who purchased a milk and bread also bought butter." }, { "code": null, "e": 1294, "s": 1233, "text": "Confidence(A -> B) = Support_count(A ∪ B) / Support_count(A)" }, { "code": null, "e": 1381, "s": 1294, "text": "If a rule satisfies both minimum support and minimum confidence, it is a strong rule. " }, { "code": null, "e": 1534, "s": 1381, "text": "Support_count(X) : Number of transactions in which X appears. If X is A union B then it is the number of transactions in which A and B both are present." }, { "code": null, "e": 1621, "s": 1534, "text": "Maximal Itemset: An itemset is maximal frequent if none of its supersets are frequent." }, { "code": null, "e": 1733, "s": 1621, "text": "Closed Itemset:An itemset is closed if none of its immediate supersets have same support count same as Itemset." }, { "code": null, "e": 1911, "s": 1733, "text": "K- Itemset:Itemset which contains K items is a K-itemset. So it can be said that an itemset is frequent if the corresponding support count is greater than minimum support count." }, { "code": null, "e": 2003, "s": 1911, "text": "Example On finding Frequent Itemsets – Consider the given dataset with given transactions. " }, { "code": null, "e": 2039, "s": 2003, "text": "Lets say minimum support count is 3" }, { "code": null, "e": 2095, "s": 2039, "text": "Relation hold is maximal frequent => closed => frequent" }, { "code": null, "e": 2348, "s": 2095, "text": "1-frequent: {A} = 3; // not closed due to {A, C} and not maximal {B} = 4; // not closed due to {B, D} and no maximal {C} = 4; // not closed due to {C, D} not maximal {D} = 5; // closed item-set since not immediate super-set has same count. Not maximal " }, { "code": null, "e": 2678, "s": 2348, "text": "2-frequent: {A, B} = 2 // not frequent because support count < minimum support count so ignore {A, C} = 3 // not closed due to {A, C, D} {A, D} = 3 // not closed due to {A, C, D} {B, C} = 3 // not closed due to {B, C, D} {B, D} = 4 // closed but not maximal due to {B, C, D} {C, D} = 4 // closed but not maximal due to {B, C, D} " }, { "code": null, "e": 2925, "s": 2678, "text": "3-frequent: {A, B, C} = 2 // ignore not frequent because support count < minimum support count {A, B, D} = 2 // ignore not frequent because support count < minimum support count {A, C, D} = 3 // maximal frequent {B, C, D} = 3 // maximal frequent " }, { "code": null, "e": 2979, "s": 2925, "text": "4-frequent: {A, B, C, D} = 2 //ignore not frequent </" }, { "code": null, "e": 2992, "s": 2979, "text": "kshitijjain2" }, { "code": null, "e": 3005, "s": 2992, "text": "simmytarika5" }, { "code": null, "e": 3017, "s": 3005, "text": "data mining" }, { "code": null, "e": 3043, "s": 3017, "text": "Advanced Computer Subject" } ]
jQuery lose focus event
29 Jul, 2020 Lose focus event can occur mainly through focusout() and blur() method. Both of them lose focus when the method gets triggered. These events differ slightly from each other but all of them serve the main purpose of losing focus.Focusout() is often used in combination with focusin() and blur() is often used in combination with focus(). Note that focusout() method also gets triggered when child elements lose focus. Syntax: $(selector).focusout(function) or $(selector).blur(function) Here, function is the parameter, which is optional and occurs when focusout() and blur() method get triggered. Example 1: This example shows the use of focusout() to lose focus. <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("div").focusin(function () { $(this).css("background-color", "#008000"); }); $("div").focusout(function () { $(this).css("background-color", "#FFFFFF"); }); }); </script></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <div style="border: 1px dashed green;padding:10px;"> Course: <input type="text"><br> </div> <p> Clicking outside the input text field enables triggering of focusout event. </p></body> </html> Output: Normal Output: When clicked inside the input text-field: When clicked outside the text field, it gets back to normal: Example 2: This example shows the use of blur() to lose focus. <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("input").blur(function () { alert("Losefocus event occurs"); }); }); </script></head> <body> <h1 style="color:Green;"> GeeksforGeeks </h1> <div style="border: 1px dashed green;padding:10px;"> Course: <input type="text"><br> </div> <p> Clicking outside the input text field enables triggering of blur event. </p></body> </html> Output:Normal Output When clicked inside the input text-field When clicked outside the text field, it displays this pop-up jQuery-Events Picked CSS HTML JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS 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 ? HTTP headers | Content-Type
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2020" }, { "code": null, "e": 365, "s": 28, "text": "Lose focus event can occur mainly through focusout() and blur() method. Both of them lose focus when the method gets triggered. These events differ slightly from each other but all of them serve the main purpose of losing focus.Focusout() is often used in combination with focusin() and blur() is often used in combination with focus()." }, { "code": null, "e": 445, "s": 365, "text": "Note that focusout() method also gets triggered when child elements lose focus." }, { "code": null, "e": 453, "s": 445, "text": "Syntax:" }, { "code": null, "e": 484, "s": 453, "text": "$(selector).focusout(function)" }, { "code": null, "e": 487, "s": 484, "text": "or" }, { "code": null, "e": 514, "s": 487, "text": "$(selector).blur(function)" }, { "code": null, "e": 625, "s": 514, "text": "Here, function is the parameter, which is optional and occurs when focusout() and blur() method get triggered." }, { "code": null, "e": 692, "s": 625, "text": "Example 1: This example shows the use of focusout() to lose focus." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"div\").focusin(function () { $(this).css(\"background-color\", \"#008000\"); }); $(\"div\").focusout(function () { $(this).css(\"background-color\", \"#FFFFFF\"); }); }); </script></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <div style=\"border: 1px dashed green;padding:10px;\"> Course: <input type=\"text\"><br> </div> <p> Clicking outside the input text field enables triggering of focusout event. </p></body> </html>", "e": 1437, "s": 692, "text": null }, { "code": null, "e": 1445, "s": 1437, "text": "Output:" }, { "code": null, "e": 1460, "s": 1445, "text": "Normal Output:" }, { "code": null, "e": 1502, "s": 1460, "text": "When clicked inside the input text-field:" }, { "code": null, "e": 1563, "s": 1502, "text": "When clicked outside the text field, it gets back to normal:" }, { "code": null, "e": 1626, "s": 1563, "text": "Example 2: This example shows the use of blur() to lose focus." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"input\").blur(function () { alert(\"Losefocus event occurs\"); }); }); </script></head> <body> <h1 style=\"color:Green;\"> GeeksforGeeks </h1> <div style=\"border: 1px dashed green;padding:10px;\"> Course: <input type=\"text\"><br> </div> <p> Clicking outside the input text field enables triggering of blur event. </p></body> </html>", "e": 2248, "s": 1626, "text": null }, { "code": null, "e": 2269, "s": 2248, "text": "Output:Normal Output" }, { "code": null, "e": 2310, "s": 2269, "text": "When clicked inside the input text-field" }, { "code": null, "e": 2371, "s": 2310, "text": "When clicked outside the text field, it displays this pop-up" }, { "code": null, "e": 2385, "s": 2371, "text": "jQuery-Events" }, { "code": null, "e": 2392, "s": 2385, "text": "Picked" }, { "code": null, "e": 2396, "s": 2392, "text": "CSS" }, { "code": null, "e": 2401, "s": 2396, "text": "HTML" }, { "code": null, "e": 2408, "s": 2401, "text": "JQuery" }, { "code": null, "e": 2425, "s": 2408, "text": "Web Technologies" }, { "code": null, "e": 2452, "s": 2425, "text": "Web technologies Questions" }, { "code": null, "e": 2457, "s": 2452, "text": "HTML" }, { "code": null, "e": 2555, "s": 2457, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2594, "s": 2555, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 2633, "s": 2594, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2672, "s": 2633, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2701, "s": 2672, "text": "Form validation using jQuery" }, { "code": null, "e": 2738, "s": 2701, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 2762, "s": 2738, "text": "REST API (Introduction)" }, { "code": null, "e": 2815, "s": 2762, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2875, "s": 2815, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2936, "s": 2875, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Cognizant Interview Experience for GenC (On-Campus 2021)
30 Dec, 2020 Cognizant Technology Solutions visited our campus virtually this time, due to the ongoing pandemic situation. The entire hiring process consisted of 2 rounds which I will be explaining in detail below. The eligibility criteria were 60% in Classes 10 & 12 and 7.0 CGPA in B.Tech along with 0 no. of arrears at the time of appearing for the process. The total number of eligible candidates who appeared from college was 250+. Since it was an on campus drive, we were also offered a 3-6 month full-time internship at Cognizant before permanent employment which was the most attractive part of this recruitment process. Round 1(Online Aptitude & Code Debugging Assessment): The test was held on AMCAT, an AI-enabled auto-proctored platform with a webcam enabled throughout the test. The level of the test was from medium to hard level. It was an adaptive test means the level of the next question will depend based on the answer you submit for the current one. The test consisted of the following sections: Quantitative Aptitude: 24 Questions (35 mins) Logical Reasoning: 25 Questions (35 mins) Automata Fix: 7 Questions (20 mins) Essay Writing(200 words): 1 Question (30 mins) P.S: This time they removed the verbal aptitude portion from their test pattern. N.B: The Automata Fix section was mandatory for CS/IT students. For other branches, they relaxed that portion while shortlisting for the next round. Tips: Practicing daily for the aptitude, you are surely going to crack it. Taking up courses on various platforms is of no use. Your hard work and determination will determine your progress. Round 2(Technical Interview): Here comes one of the most nervous situations in a student’s life. Due to the pandemic, this time the interviews were held virtually on the Aspiring Minds Smart Meet platform. There was only one person in the panel in my case. The interviewer was not that strict, and he started by asking me to send my Resume through the chat option. Then he fired his questions(entirely based on what I mentioned in my Resume): Introduce Yourself.Tell me about the internship you did. What projects did you work on in that internship? [I did an internship based on Arduino at Kesowa Infinite Ventures LLP]Difference between Arrays and Linked List.Difference between Linear and Non-Linear Data Structures.Then he asked two true/false statements based on pointers in C. [I was able to answer one correctly]Explain OOPs concept and the four principles.Then he gave the below snippet to answer Introduce Yourself. Tell me about the internship you did. What projects did you work on in that internship? [I did an internship based on Arduino at Kesowa Infinite Ventures LLP] Difference between Arrays and Linked List. Difference between Linear and Non-Linear Data Structures. Then he asked two true/false statements based on pointers in C. [I was able to answer one correctly] Explain OOPs concept and the four principles. Then he gave the below snippet to answer Java class Outer { int outer_x=100; void test() { Inner inner = new Inner(); inner.display(); } class Inner { void display() { System.out.println(outer_x); } }} class InnerClassDemo { public static void main (String[] args) { Outer outer = new Outer(); outer.test(); }} I answered this one correctly after 1 min of thinking. Then he gave me 3 quantitative aptitude problems to solve, out of which one answer was given wrong from his side. But I was able to explain successfully what was wrong with his solution. (Maybe he was testing my level of confidence) At last, he asked me whether I had anything for him to ask. That’s it. Tips: Prepare very well with what you are going to say to the interviewer and be firm and confident in what you say. The interviewer will catch you easily if you try to fool him and it will definitely create a very bad impression at the beginning itself. At the end, I was able to crack all the rounds and got placed in the prestigious company. I hope, the above information will clear most of the doubts and will help the readers reading this moving ahead. Thank You. Good Luck!!! Cognizant Cognizant-interview-experience Marketing On-Campus Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Dec, 2020" }, { "code": null, "e": 669, "s": 53, "text": "Cognizant Technology Solutions visited our campus virtually this time, due to the ongoing pandemic situation. The entire hiring process consisted of 2 rounds which I will be explaining in detail below. The eligibility criteria were 60% in Classes 10 & 12 and 7.0 CGPA in B.Tech along with 0 no. of arrears at the time of appearing for the process. The total number of eligible candidates who appeared from college was 250+. Since it was an on campus drive, we were also offered a 3-6 month full-time internship at Cognizant before permanent employment which was the most attractive part of this recruitment process." }, { "code": null, "e": 1056, "s": 669, "text": "Round 1(Online Aptitude & Code Debugging Assessment): The test was held on AMCAT, an AI-enabled auto-proctored platform with a webcam enabled throughout the test. The level of the test was from medium to hard level. It was an adaptive test means the level of the next question will depend based on the answer you submit for the current one. The test consisted of the following sections:" }, { "code": null, "e": 1102, "s": 1056, "text": "Quantitative Aptitude: 24 Questions (35 mins)" }, { "code": null, "e": 1144, "s": 1102, "text": "Logical Reasoning: 25 Questions (35 mins)" }, { "code": null, "e": 1180, "s": 1144, "text": "Automata Fix: 7 Questions (20 mins)" }, { "code": null, "e": 1227, "s": 1180, "text": "Essay Writing(200 words): 1 Question (30 mins)" }, { "code": null, "e": 1308, "s": 1227, "text": "P.S: This time they removed the verbal aptitude portion from their test pattern." }, { "code": null, "e": 1457, "s": 1308, "text": "N.B: The Automata Fix section was mandatory for CS/IT students. For other branches, they relaxed that portion while shortlisting for the next round." }, { "code": null, "e": 1648, "s": 1457, "text": "Tips: Practicing daily for the aptitude, you are surely going to crack it. Taking up courses on various platforms is of no use. Your hard work and determination will determine your progress." }, { "code": null, "e": 2091, "s": 1648, "text": "Round 2(Technical Interview): Here comes one of the most nervous situations in a student’s life. Due to the pandemic, this time the interviews were held virtually on the Aspiring Minds Smart Meet platform. There was only one person in the panel in my case. The interviewer was not that strict, and he started by asking me to send my Resume through the chat option. Then he fired his questions(entirely based on what I mentioned in my Resume):" }, { "code": null, "e": 2553, "s": 2091, "text": "Introduce Yourself.Tell me about the internship you did. What projects did you work on in that internship? [I did an internship based on Arduino at Kesowa Infinite Ventures LLP]Difference between Arrays and Linked List.Difference between Linear and Non-Linear Data Structures.Then he asked two true/false statements based on pointers in C. [I was able to answer one correctly]Explain OOPs concept and the four principles.Then he gave the below snippet to answer" }, { "code": null, "e": 2573, "s": 2553, "text": "Introduce Yourself." }, { "code": null, "e": 2732, "s": 2573, "text": "Tell me about the internship you did. What projects did you work on in that internship? [I did an internship based on Arduino at Kesowa Infinite Ventures LLP]" }, { "code": null, "e": 2775, "s": 2732, "text": "Difference between Arrays and Linked List." }, { "code": null, "e": 2833, "s": 2775, "text": "Difference between Linear and Non-Linear Data Structures." }, { "code": null, "e": 2934, "s": 2833, "text": "Then he asked two true/false statements based on pointers in C. [I was able to answer one correctly]" }, { "code": null, "e": 2980, "s": 2934, "text": "Explain OOPs concept and the four principles." }, { "code": null, "e": 3021, "s": 2980, "text": "Then he gave the below snippet to answer" }, { "code": null, "e": 3026, "s": 3021, "text": "Java" }, { "code": "class Outer { int outer_x=100; void test() { Inner inner = new Inner(); inner.display(); } class Inner { void display() { System.out.println(outer_x); } }} class InnerClassDemo { public static void main (String[] args) { Outer outer = new Outer(); outer.test(); }}", "e": 3329, "s": 3026, "text": null }, { "code": null, "e": 3384, "s": 3329, "text": "I answered this one correctly after 1 min of thinking." }, { "code": null, "e": 3617, "s": 3384, "text": "Then he gave me 3 quantitative aptitude problems to solve, out of which one answer was given wrong from his side. But I was able to explain successfully what was wrong with his solution. (Maybe he was testing my level of confidence)" }, { "code": null, "e": 3688, "s": 3617, "text": "At last, he asked me whether I had anything for him to ask. That’s it." }, { "code": null, "e": 3943, "s": 3688, "text": "Tips: Prepare very well with what you are going to say to the interviewer and be firm and confident in what you say. The interviewer will catch you easily if you try to fool him and it will definitely create a very bad impression at the beginning itself." }, { "code": null, "e": 4146, "s": 3943, "text": "At the end, I was able to crack all the rounds and got placed in the prestigious company. I hope, the above information will clear most of the doubts and will help the readers reading this moving ahead." }, { "code": null, "e": 4157, "s": 4146, "text": "Thank You." }, { "code": null, "e": 4170, "s": 4157, "text": "Good Luck!!!" }, { "code": null, "e": 4180, "s": 4170, "text": "Cognizant" }, { "code": null, "e": 4211, "s": 4180, "text": "Cognizant-interview-experience" }, { "code": null, "e": 4221, "s": 4211, "text": "Marketing" }, { "code": null, "e": 4231, "s": 4221, "text": "On-Campus" }, { "code": null, "e": 4253, "s": 4231, "text": "Interview Experiences" } ]
Binary Search Tree | Set 2 (Delete)
23 Jun, 2022 We have discussed BST search and insert operations. In this post, the delete operation is discussed. When we delete a node, three possibilities arise. 1) Node to be deleted is the leaf: Simply remove from the tree. 50 50 / \ delete(20) / \ 30 70 ---------> 30 70 / \ / \ \ / \ 20 40 60 80 40 60 80 2) Node to be deleted has only one child: Copy the child to the node and delete the child 50 50 / \ delete(30) / \ 30 70 ---------> 40 70 \ / \ / \ 40 60 80 60 80 3) Node to be deleted has two children: Find inorder successor of the node. Copy contents of the inorder successor to the node and delete the inorder successor. Note that inorder predecessor can also be used. 50 60 / \ delete(50) / \ 40 70 ---------> 40 70 / \ \ 60 80 80 The important thing to note is, inorder successor is needed only when the right child is not empty. In this particular case, inorder successor can be obtained by finding the minimum value in the right child of the node. 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. Implementation: C++ C Java Python3 C# Javascript // C++ program to demonstrate// delete operation in binary// search tree#include <bits/stdc++.h>using namespace std; struct node { int key; struct node *left, *right;}; // A utility function to create a new BST nodestruct node* newNode(int item){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to do// inorder traversal of BSTvoid inorder(struct node* root){ if (root != NULL) { inorder(root->left); cout << root->key; inorder(root->right); }} /* A utility function toinsert a new node with given key in * BST */struct node* insert(struct node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, return the nodewith minimum key value found in that tree. Note that theentire tree does not need to be searched. */struct node* minValueNode(struct node* node){ struct node* current = node; /* loop down to find the leftmost leaf */ while (current && current->left != NULL) current = current->left; return current;} /* Given a binary search tree and a key, this functiondeletes the key and returns the new root */struct node* deleteNode(struct node* root, int key){ // base case if (root == NULL) return root; // If the key to be deleted is // smaller than the root's // key, then it lies in left subtree if (key < root->key) root->left = deleteNode(root->left, key); // If the key to be deleted is // greater than the root's // key, then it lies in right subtree else if (key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key, then This is the node // to be deleted else { // node has no child if (root->left==NULL and root->right==NULL) return NULL; // node with only one child or no child else if (root->left == NULL) { struct node* temp = root->right; free(root); return temp; } else if (root->right == NULL) { struct node* temp = root->left; free(root); return temp; } // node with two children: Get the inorder successor // (smallest in the right subtree) struct node* temp = minValueNode(root->right); // Copy the inorder successor's content to this node root->key = temp->key; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } return root;} // Driver Codeint main(){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ struct node* root = NULL; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); cout << "Inorder traversal of the given tree \n"; inorder(root); cout << "\nDelete 20\n"; root = deleteNode(root, 20); cout << "Inorder traversal of the modified tree \n"; inorder(root); cout << "\nDelete 30\n"; root = deleteNode(root, 30); cout << "Inorder traversal of the modified tree \n"; inorder(root); cout << "\nDelete 50\n"; root = deleteNode(root, 50); cout << "Inorder traversal of the modified tree \n"; inorder(root); return 0;} // This code is contributed by shivanisinghss2110 // C program to demonstrate// delete operation in binary// search tree#include <stdio.h>#include <stdlib.h> struct node { int key; struct node *left, *right;}; // A utility function to create a new BST nodestruct node* newNode(int item){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to do inorder traversal of BSTvoid inorder(struct node* root){ if (root != NULL) { inorder(root->left); printf("%d ", root->key); inorder(root->right); }} /* A utility function to insert a new node with given key in * BST */struct node* insert(struct node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */struct node* minValueNode(struct node* node){ struct node* current = node; /* loop down to find the leftmost leaf */ while (current && current->left != NULL) current = current->left; return current;} /* Given a binary search tree and a key, this function deletes the key and returns the new root */struct node* deleteNode(struct node* root, int key){ // base case if (root == NULL) return root; // If the key to be deleted // is smaller than the root's // key, then it lies in left subtree if (key < root->key) root->left = deleteNode(root->left, key); // If the key to be deleted // is greater than the root's // key, then it lies in right subtree else if (key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key, // then This is the node // to be deleted else { // node with only one child or no child if (root->left == NULL) { struct node* temp = root->right; free(root); return temp; } else if (root->right == NULL) { struct node* temp = root->left; free(root); return temp; } // node with two children: // Get the inorder successor // (smallest in the right subtree) struct node* temp = minValueNode(root->right); // Copy the inorder // successor's content to this node root->key = temp->key; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } return root;} // Driver Codeint main(){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ struct node* root = NULL; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); printf("Inorder traversal of the given tree \n"); inorder(root); printf("\nDelete 20\n"); root = deleteNode(root, 20); printf("Inorder traversal of the modified tree \n"); inorder(root); printf("\nDelete 30\n"); root = deleteNode(root, 30); printf("Inorder traversal of the modified tree \n"); inorder(root); printf("\nDelete 50\n"); root = deleteNode(root, 50); printf("Inorder traversal of the modified tree \n"); inorder(root); return 0;} // Java program to demonstrate// delete operation in binary// search treeclass BinarySearchTree { /* Class containing left and right child of current node * and key value*/ class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; } } // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // This method mainly calls deleteRec() void deleteKey(int key) { root = deleteRec(root, key); } /* A recursive function to delete an existing key in BST */ Node deleteRec(Node root, int key) { /* Base Case: If the tree is empty */ if (root == null) return root; /* Otherwise, recur down the tree */ if (key < root.key) root.left = deleteRec(root.left, key); else if (key > root.key) root.right = deleteRec(root.right, key); // if key is same as root's // key, then This is the // node to be deleted else { // node with only one child or no child if (root.left == null) return root.right; else if (root.right == null) return root.left; // node with two children: Get the inorder // successor (smallest in the right subtree) root.key = minValue(root.right); // Delete the inorder successor root.right = deleteRec(root.right, root.key); } return root; } int minValue(Node root) { int minv = root.key; while (root.left != null) { minv = root.left.key; root = root.left; } return minv; } // This method mainly calls insertRec() void insert(int key) { root = insertRec(root, key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root, int key) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise, recur down the tree */ if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); /* return the (unchanged) node pointer */ return root; } // This method mainly calls InorderRec() void inorder() { inorderRec(root); } // A utility function to do inorder traversal of BST void inorderRec(Node root) { if (root != null) { inorderRec(root.left); System.out.print(root.key + " "); inorderRec(root.right); } } // Driver Code public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ tree.insert(50); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(70); tree.insert(60); tree.insert(80); System.out.println( "Inorder traversal of the given tree"); tree.inorder(); System.out.println("\nDelete 20"); tree.deleteKey(20); System.out.println( "Inorder traversal of the modified tree"); tree.inorder(); System.out.println("\nDelete 30"); tree.deleteKey(30); System.out.println( "Inorder traversal of the modified tree"); tree.inorder(); System.out.println("\nDelete 50"); tree.deleteKey(50); System.out.println( "Inorder traversal of the modified tree"); tree.inorder(); }} # Python program to demonstrate delete operation# in binary search tree # A Binary Tree Node class Node: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to do inorder traversal of BSTdef inorder(root): if root is not None: inorder(root.left) print (root.key,end=" ") inorder(root.right) # A utility function to insert a# new node with given key in BSTdef insert(node, key): # If the tree is empty, return a new node if node is None: return Node(key) # Otherwise recur down the tree if key < node.key: node.left = insert(node.left, key) else: node.right = insert(node.right, key) # return the (unchanged) node pointer return node # Given a non-empty binary# search tree, return the node# with minimum key value# found in that tree. Note that the# entire tree does not need to be searched def minValueNode(node): current = node # loop down to find the leftmost leaf while(current.left is not None): current = current.left return current # Given a binary search tree and a key, this function# delete the key and returns the new root def deleteNode(root, key): # Base Case if root is None: return root # If the key to be deleted # is smaller than the root's # key then it lies in left subtree if key < root.key: root.left = deleteNode(root.left, key) # If the kye to be delete # is greater than the root's key # then it lies in right subtree elif(key > root.key): root.right = deleteNode(root.right, key) # If key is same as root's key, then this is the node # to be deleted else: # Node with only one child or no child if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp # Node with two children: # Get the inorder successor # (smallest in the right subtree) temp = minValueNode(root.right) # Copy the inorder successor's # content to this node root.key = temp.key # Delete the inorder successor root.right = deleteNode(root.right, temp.key) return root # Driver code""" Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 """ root = Noneroot = insert(root, 50)root = insert(root, 30)root = insert(root, 20)root = insert(root, 40)root = insert(root, 70)root = insert(root, 60)root = insert(root, 80) print ("Inorder traversal of the given tree")inorder(root) print ("\nDelete 20")root = deleteNode(root, 20)print ("Inorder traversal of the modified tree")inorder(root) print ("\nDelete 30")root = deleteNode(root, 30)print ("Inorder traversal of the modified tree")inorder(root) print ("\nDelete 50")root = deleteNode(root, 50)print ("Inorder traversal of the modified tree")inorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to demonstrate delete// operation in binary search treeusing System; public class BinarySearchTree { /* Class containing left and right child of current node and key value*/ class Node { public int key; public Node left, right; public Node(int item) { key = item; left = right = null; } } // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // This method mainly calls deleteRec() void deleteKey(int key) { root = deleteRec(root, key); } /* A recursive function to delete an existing key in BST */ Node deleteRec(Node root, int key) { /* Base Case: If the tree is empty */ if (root == null) return root; /* Otherwise, recur down the tree */ if (key < root.key) root.left = deleteRec(root.left, key); else if (key > root.key) root.right = deleteRec(root.right, key); // if key is same as root's key, then This is the // node to be deleted else { // node with only one child or no child if (root.left == null) return root.right; else if (root.right == null) return root.left; // node with two children: Get the // inorder successor (smallest // in the right subtree) root.key = minValue(root.right); // Delete the inorder successor root.right = deleteRec(root.right, root.key); } return root; } int minValue(Node root) { int minv = root.key; while (root.left != null) { minv = root.left.key; root = root.left; } return minv; } // This method mainly calls insertRec() void insert(int key) { root = insertRec(root, key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root, int key) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise, recur down the tree */ if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); /* return the (unchanged) node pointer */ return root; } // This method mainly calls InorderRec() void inorder() { inorderRec(root); } // A utility function to do inorder traversal of BST void inorderRec(Node root) { if (root != null) { inorderRec(root.left); Console.Write(root.key + " "); inorderRec(root.right); } } // Driver code public static void Main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ tree.insert(50); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(70); tree.insert(60); tree.insert(80); Console.WriteLine( "Inorder traversal of the given tree"); tree.inorder(); Console.WriteLine("\nDelete 20"); tree.deleteKey(20); Console.WriteLine( "Inorder traversal of the modified tree"); tree.inorder(); Console.WriteLine("\nDelete 30"); tree.deleteKey(30); Console.WriteLine( "Inorder traversal of the modified tree"); tree.inorder(); Console.WriteLine("\nDelete 50"); tree.deleteKey(50); Console.WriteLine( "Inorder traversal of the modified tree"); tree.inorder(); }} // This code has been contributed// by PrinciRaj1992 <script>// Javascript program to demonstrate// delete operation in binary// search treeclass Node{ constructor(item) { this.key = item; this.left = this.right = null; }} // Root of BSTlet root=null; // This method mainly calls deleteRec()function deleteKey(key){ root = deleteRec(root, key);} /* A recursive function to delete an existing key in BST */function deleteRec(root,key){ /* Base Case: If the tree is empty */ if (root == null) return root; /* Otherwise, recur down the tree */ if (key < root.key) root.left = deleteRec(root.left, key); else if (key > root.key) root.right = deleteRec(root.right, key); // if key is same as root's // key, then This is the // node to be deleted else { // node with only one child or no child if (root.left == null) return root.right; else if (root.right == null) return root.left; // node with two children: Get the inorder // successor (smallest in the right subtree) root.key = minValue(root.right); // Delete the inorder successor root.right = deleteRec(root.right, root.key); } return root;} function minValue(root){ let minv = root.key; while (root.left != null) { minv = root.left.key; root = root.left; } return minv;} // This method mainly calls insertRec()function insert(key){ root = insertRec(root, key);} /* A recursive function to insert a new key in BST */function insertRec(root,key){ /* If the tree is empty, return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise, recur down the tree */ if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); /* return the (unchanged) node pointer */ return root;} // This method mainly calls InorderRec()function inorder(){ inorderRec(root);} // A utility function to do inorder traversal of BSTfunction inorderRec(root){ if (root != null) { inorderRec(root.left); document.write(root.key + " "); inorderRec(root.right); }} // Driver Code/* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */insert(50);insert(30);insert(20);insert(40);insert(70);insert(60);insert(80); document.write("Inorder traversal of the given tree<br>");inorder(); document.write("<br>Delete 20<br>");deleteKey(20);document.write("Inorder traversal of the modified tree<br>");inorder(); document.write("<br>Delete 30<br>");deleteKey(30);document.write("Inorder traversal of the modified tree<br>");inorder(); document.write("<br>Delete 50<br>");deleteKey(50);document.write("Inorder traversal of the modified tree<br>");inorder(); // This code is contributed by avanitrachhadiya2155</script> Inorder traversal of the given tree 20304050607080 Delete 20 Inorder traversal of the modified tree 304050607080 Delete 30 Inorder traversal of the modified tree 4050607080 Delete 50 Inorder traversal of the modified tree 40607080 Illustration: Time Complexity: The worst case time complexity of delete operation is O(h) where h is the height of the Binary Search Tree. In worst case, we may have to travel from the root to the deepest leaf node. The height of a skewed tree may become n and the time complexity of delete operation may become O(n) Optimization to above code for two children case : In the above recursive code, we recursively call delete() for the successor. We can avoid recursive calls by keeping track of the parent node of the successor so that we can simply remove the successor by making the child of a parent NULL. We know that the successor would always be a leaf node. Implementation: C++ Java C# Python3 Javascript // C++ program to implement optimized delete in BST.#include <bits/stdc++.h>using namespace std; struct Node { int key; struct Node *left, *right;}; // A utility function to create a new BST nodeNode* newNode(int item){ Node* temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to do inorder traversal of BSTvoid inorder(Node* root){ if (root != NULL) { inorder(root->left); printf("%d ", root->key); inorder(root->right); }} /* A utility function to insert a new node with given key in * BST */Node* insert(Node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} /* Given a binary search tree and a key, this function deletes the key and returns the new root */Node* deleteNode(Node* root, int k){ // Base case if (root == NULL) return root; // Recursive calls for ancestors of // node to be deleted if (root->key > k) { root->left = deleteNode(root->left, k); return root; } else if (root->key < k) { root->right = deleteNode(root->right, k); return root; } // We reach here when root is the node // to be deleted. // If one of the children is empty if (root->left == NULL) { Node* temp = root->right; delete root; return temp; } else if (root->right == NULL) { Node* temp = root->left; delete root; return temp; } // If both children exist else { Node* succParent = root; // Find successor Node* succ = root->right; while (succ->left != NULL) { succParent = succ; succ = succ->left; } // Delete successor. Since successor // is always left child of its parent // we can safely make successor's right // right child as left of its parent. // If there is no succ, then assign // succ->right to succParent->right if (succParent != root) succParent->left = succ->right; else succParent->right = succ->right; // Copy Successor Data to root root->key = succ->key; // Delete Successor and return root delete succ; return root; }} // Driver Codeint main(){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node* root = NULL; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); printf("Inorder traversal of the given tree \n"); inorder(root); printf("\nDelete 20\n"); root = deleteNode(root, 20); printf("Inorder traversal of the modified tree \n"); inorder(root); printf("\nDelete 30\n"); root = deleteNode(root, 30); printf("Inorder traversal of the modified tree \n"); inorder(root); printf("\nDelete 50\n"); root = deleteNode(root, 50); printf("Inorder traversal of the modified tree \n"); inorder(root); return 0;} // Java program to implement optimized delete in BST.import java.util.*; class GFG{ static class Node{ int key; Node left, right;} // A utility function to create a new BST nodestatic Node newNode(int item){ Node temp = new Node(); temp.key = item; temp.left = temp.right = null; return temp;} // A utility function to do inorder traversal of BSTstatic void inorder(Node root){ if (root != null) { inorder(root.left); System.out.print(root.key + " "); inorder(root.right); }} // A utility function to insert a new node// with given key in BSTstatic Node insert(Node node, int key){ // If the tree is empty, return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); // Return the (unchanged) node pointer return node;} // Given a binary search tree and a key, this// function deletes the key and returns the// new rootstatic Node deleteNode(Node root, int k){ // Base case if (root == null) return root; // Recursive calls for ancestors of // node to be deleted if (root.key > k) { root.left = deleteNode(root.left, k); return root; } else if (root.key < k) { root.right = deleteNode(root.right, k); return root; } // We reach here when root is the node // to be deleted. // If one of the children is empty if (root.left == null) { Node temp = root.right; return temp; } else if (root.right == null) { Node temp = root.left; return temp; } // If both children exist else { Node succParent = root; // Find successor Node succ = root.right; while (succ.left != null) { succParent = succ; succ = succ.left; } // Delete successor. Since successor // is always left child of its parent // we can safely make successor's right // right child as left of its parent. // If there is no succ, then assign // succ->right to succParent->right if (succParent != root) succParent.left = succ.right; else succParent.right = succ.right; // Copy Successor Data to root root.key = succ.key; return root; }} // Driver Codepublic static void main(String args[]){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node root = null; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); System.out.println("Inorder traversal of the " + "given tree"); inorder(root); System.out.println("\nDelete 20\n"); root = deleteNode(root, 20); System.out.println("Inorder traversal of the " + "modified tree"); inorder(root); System.out.println("\nDelete 30\n"); root = deleteNode(root, 30); System.out.println("Inorder traversal of the " + "modified tree"); inorder(root); System.out.println("\nDelete 50\n"); root = deleteNode(root, 50); System.out.println("Inorder traversal of the " + "modified tree"); inorder(root);}} // This code is contributed by adityapande88 // C# program to implement optimized delete in BST.using System; class GFG{ class Node{ public int key; public Node left, right;} // A utility function to create a new BST nodestatic Node newNode(int item){ Node temp = new Node(); temp.key = item; temp.left = temp.right = null; return temp;} // A utility function to do inorder traversal of BSTstatic void inorder(Node root){ if (root != null) { inorder(root.left); Console.Write(root.key + " "); inorder(root.right); }} // A utility function to insert a new node// with given key in BSTstatic Node insert(Node node, int key){ // If the tree is empty, return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); // Return the (unchanged) node pointer return node;} // Given a binary search tree and a key, this// function deletes the key and returns the// new rootstatic Node deleteNode(Node root, int k){ // Base case if (root == null) return root; // Recursive calls for ancestors of // node to be deleted if (root.key > k) { root.left = deleteNode(root.left, k); return root; } else if (root.key < k) { root.right = deleteNode(root.right, k); return root; } // We reach here when root is the node // to be deleted. // If one of the children is empty if (root.left == null) { Node temp = root.right; return temp; } else if (root.right == null) { Node temp = root.left; return temp; } // If both children exist else { Node succParent = root; // Find successor Node succ = root.right; while (succ.left != null) { succParent = succ; succ = succ.left; } // Delete successor. Since successor // is always left child of its parent // we can safely make successor's right // right child as left of its parent. // If there is no succ, then assign // succ->right to succParent->right if (succParent != root) succParent.left = succ.right; else succParent.right = succ.right; // Copy Successor Data to root root.key = succ.key; return root; }} // Driver Codepublic static void Main(String []args){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node root = null; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); Console.WriteLine("Inorder traversal of the " + "given tree"); inorder(root); Console.WriteLine("\nDelete 20\n"); root = deleteNode(root, 20); Console.WriteLine("Inorder traversal of the " + "modified tree"); inorder(root); Console.WriteLine("\nDelete 30\n"); root = deleteNode(root, 30); Console.WriteLine("Inorder traversal of the " + "modified tree"); inorder(root); Console.WriteLine("\nDelete 50\n"); root = deleteNode(root, 50); Console.WriteLine("Inorder traversal of the " + "modified tree"); inorder(root);}} // This code is contributed by shivanisinghss2110 # Python3 program to implement# optimized delete in BST. class Node: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to do# inorder traversal of BSTdef inorder(root): if root is not None: inorder(root.left) print(root.key, end=" ") inorder(root.right) # A utility function to insert a# new node with given key in BSTdef insert(node, key): # If the tree is empty, # return a new node if node is None: return Node(key) # Otherwise recur down the tree if key < node.key: node.left = insert(node.left, key) else: node.right = insert(node.right, key) # return the (unchanged) node pointer return node # Given a binary search tree# and a key, this function# delete the key and returns the new rootdef deleteNode(root, key): # Base Case if root is None: return root # Recursive calls for ancestors of # node to be deleted if key < root.key: root.left = deleteNode(root.left, key) return root elif(key > root.key): root.right = deleteNode(root.right, key) return root # We reach here when root is the node # to be deleted. # If root node is a leaf node if root.left is None and root.right is None: return None # If one of the children is empty if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp # If both children exist succParent = root # Find Successor succ = root.right while succ.left != None: succParent = succ succ = succ.left # Delete successor.Since successor # is always left child of its parent # we can safely make successor's right # right child as left of its parent. # If there is no succ, then assign # succ->right to succParent->right if succParent != root: succParent.left = succ.right else: succParent.right = succ.right # Copy Successor Data to root root.key = succ.key return root # Driver code""" Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 """ root = Noneroot = insert(root, 50)root = insert(root, 30)root = insert(root, 20)root = insert(root, 40)root = insert(root, 70)root = insert(root, 60)root = insert(root, 80) print("Inorder traversal of the given tree")inorder(root) print("\nDelete 20")root = deleteNode(root, 20)print("Inorder traversal of the modified tree")inorder(root) print("\nDelete 30")root = deleteNode(root, 30)print("Inorder traversal of the modified tree")inorder(root) print("\nDelete 50")root = deleteNode(root, 50)print("Inorder traversal of the modified tree")inorder(root) # This code is contributed by Shivam Bhat (shivambhat45) <script>// javascript program to implement optimized delete in BST. class Node { constructor(val) { this.key = val; this.left = null; this.right = null; }} // A utility function to create a new BST node function newNode(item) {var temp = new Node(); temp.key = item; temp.left = temp.right = null; return temp; } // A utility function to do inorder traversal of BST function inorder(root) { if (root != null) { inorder(root.left); document.write(root.key + " "); inorder(root.right); } } // A utility function to insert a new node // with given key in BST function insert(node , key) { // If the tree is empty, return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); // Return the (unchanged) node pointer return node; } // Given a binary search tree and a key, this // function deletes the key and returns the // new root function deleteNode(root , k) { // Base case if (root == null) return root; // Recursive calls for ancestors of // node to be deleted if (root.key > k) { root.left = deleteNode(root.left, k); return root; } else if (root.key < k) { root.right = deleteNode(root.right, k); return root; } // We reach here when root is the node // to be deleted. // If one of the children is empty if (root.left == null) { var temp = root.right; return temp; } else if (root.right == null) { var temp = root.left; return temp; } // If both children exist else { var succParent = root; // Find successor var succ = root.right; while (succ.left != null) { succParent = succ; succ = succ.left; } // Delete successor. Since successor // is always left child of its parent // we can safely make successor's right // right child as left of its parent. // If there is no succ, then assign // succ->right to succParent->right if (succParent != root) succParent.left = succ.right; else succParent.right = succ.right; // Copy Successor Data to root root.key = succ.key; return root; } } // Driver Code /* * Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */var root = null; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); document.write("Inorder traversal of the " + "given tree<br/>"); inorder(root); document.write("<br/>Delete 20<br/>"); root = deleteNode(root, 20); document.write("Inorder traversal of the " + "modified tree<br/>"); inorder(root); document.write("<br/>Delete 30<br/>"); root = deleteNode(root, 30); document.write("Inorder traversal of the " + "modified tree<br/>"); inorder(root); document.write("<br/>Delete 50<br/>"); root = deleteNode(root, 50); document.write("Inorder traversal of the " + "modified tree<br/>"); inorder(root); // This code contributed by Rajput-Ji</script> Inorder traversal of the given tree 20 30 40 50 60 70 80 Delete 20 Inorder traversal of the modified tree 30 40 50 60 70 80 Delete 30 Inorder traversal of the modified tree 40 50 60 70 80 Delete 50 Inorder traversal of the modified tree 40 60 70 80 Thanks to wolffgang010 for suggesting the above optimization.Related Links: Binary Search Tree Introduction, Search and Insert Quiz on Binary Search Tree Coding practice on BST All Articles on BST Manoj Kumar 20 wolffgang010 princiraj1992 Sarvesh Ranjan harispartacus0 shivanisinghss2110 j9rex shivambhat45 agarwalr327 imran khan 1 adityapande88 liocat avanitrachhadiya2155 sagartomar9927 amartyaghoshgfg Rajput-Ji hardikkoriintern Accolite Amazon Qualcomm Samsung Binary Search Tree Accolite Amazon Samsung Qualcomm Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. A program to check if a binary tree is BST or not Find postorder traversal of BST from preorder traversal Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Sorted Array to Balanced BST Optimal Binary Search Tree | DP-24 Inorder Successor in Binary Search Tree Convert a normal BST to Balanced BST set vs unordered_set in C++ STL Find k-th smallest element in BST (Order Statistics in BST) Check if a given array can represent Preorder Traversal of Binary Search Tree
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 206, "s": 54, "text": "We have discussed BST search and insert operations. In this post, the delete operation is discussed. When we delete a node, three possibilities arise. " }, { "code": null, "e": 271, "s": 206, "text": "1) Node to be deleted is the leaf: Simply remove from the tree. " }, { "code": null, "e": 526, "s": 271, "text": " 50 50\n / \\ delete(20) / \\\n 30 70 ---------> 30 70 \n / \\ / \\ \\ / \\ \n 20 40 60 80 40 60 80" }, { "code": null, "e": 617, "s": 526, "text": "2) Node to be deleted has only one child: Copy the child to the node and delete the child " }, { "code": null, "e": 872, "s": 617, "text": " 50 50\n / \\ delete(30) / \\\n 30 70 ---------> 40 70 \n \\ / \\ / \\ \n 40 60 80 60 80" }, { "code": null, "e": 1082, "s": 872, "text": "3) Node to be deleted has two children: Find inorder successor of the node. Copy contents of the inorder successor to the node and delete the inorder successor. Note that inorder predecessor can also be used. " }, { "code": null, "e": 1334, "s": 1082, "text": " 50 60\n / \\ delete(50) / \\\n 40 70 ---------> 40 70 \n / \\ \\ \n 60 80 80" }, { "code": null, "e": 1554, "s": 1334, "text": "The important thing to note is, inorder successor is needed only when the right child is not empty. In this particular case, inorder successor can be obtained by finding the minimum value in the right child of the node." }, { "code": null, "e": 1563, "s": 1554, "text": "Chapters" }, { "code": null, "e": 1590, "s": 1563, "text": "descriptions off, selected" }, { "code": null, "e": 1640, "s": 1590, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1663, "s": 1640, "text": "captions off, selected" }, { "code": null, "e": 1671, "s": 1663, "text": "English" }, { "code": null, "e": 1695, "s": 1671, "text": "This is a modal window." }, { "code": null, "e": 1764, "s": 1695, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1786, "s": 1764, "text": "End of dialog window." }, { "code": null, "e": 1802, "s": 1786, "text": "Implementation:" }, { "code": null, "e": 1806, "s": 1802, "text": "C++" }, { "code": null, "e": 1808, "s": 1806, "text": "C" }, { "code": null, "e": 1813, "s": 1808, "text": "Java" }, { "code": null, "e": 1821, "s": 1813, "text": "Python3" }, { "code": null, "e": 1824, "s": 1821, "text": "C#" }, { "code": null, "e": 1835, "s": 1824, "text": "Javascript" }, { "code": "// C++ program to demonstrate// delete operation in binary// search tree#include <bits/stdc++.h>using namespace std; struct node { int key; struct node *left, *right;}; // A utility function to create a new BST nodestruct node* newNode(int item){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to do// inorder traversal of BSTvoid inorder(struct node* root){ if (root != NULL) { inorder(root->left); cout << root->key; inorder(root->right); }} /* A utility function toinsert a new node with given key in * BST */struct node* insert(struct node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, return the nodewith minimum key value found in that tree. Note that theentire tree does not need to be searched. */struct node* minValueNode(struct node* node){ struct node* current = node; /* loop down to find the leftmost leaf */ while (current && current->left != NULL) current = current->left; return current;} /* Given a binary search tree and a key, this functiondeletes the key and returns the new root */struct node* deleteNode(struct node* root, int key){ // base case if (root == NULL) return root; // If the key to be deleted is // smaller than the root's // key, then it lies in left subtree if (key < root->key) root->left = deleteNode(root->left, key); // If the key to be deleted is // greater than the root's // key, then it lies in right subtree else if (key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key, then This is the node // to be deleted else { // node has no child if (root->left==NULL and root->right==NULL) return NULL; // node with only one child or no child else if (root->left == NULL) { struct node* temp = root->right; free(root); return temp; } else if (root->right == NULL) { struct node* temp = root->left; free(root); return temp; } // node with two children: Get the inorder successor // (smallest in the right subtree) struct node* temp = minValueNode(root->right); // Copy the inorder successor's content to this node root->key = temp->key; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } return root;} // Driver Codeint main(){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ struct node* root = NULL; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); cout << \"Inorder traversal of the given tree \\n\"; inorder(root); cout << \"\\nDelete 20\\n\"; root = deleteNode(root, 20); cout << \"Inorder traversal of the modified tree \\n\"; inorder(root); cout << \"\\nDelete 30\\n\"; root = deleteNode(root, 30); cout << \"Inorder traversal of the modified tree \\n\"; inorder(root); cout << \"\\nDelete 50\\n\"; root = deleteNode(root, 50); cout << \"Inorder traversal of the modified tree \\n\"; inorder(root); return 0;} // This code is contributed by shivanisinghss2110", "e": 5620, "s": 1835, "text": null }, { "code": "// C program to demonstrate// delete operation in binary// search tree#include <stdio.h>#include <stdlib.h> struct node { int key; struct node *left, *right;}; // A utility function to create a new BST nodestruct node* newNode(int item){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to do inorder traversal of BSTvoid inorder(struct node* root){ if (root != NULL) { inorder(root->left); printf(\"%d \", root->key); inorder(root->right); }} /* A utility function to insert a new node with given key in * BST */struct node* insert(struct node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */struct node* minValueNode(struct node* node){ struct node* current = node; /* loop down to find the leftmost leaf */ while (current && current->left != NULL) current = current->left; return current;} /* Given a binary search tree and a key, this function deletes the key and returns the new root */struct node* deleteNode(struct node* root, int key){ // base case if (root == NULL) return root; // If the key to be deleted // is smaller than the root's // key, then it lies in left subtree if (key < root->key) root->left = deleteNode(root->left, key); // If the key to be deleted // is greater than the root's // key, then it lies in right subtree else if (key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key, // then This is the node // to be deleted else { // node with only one child or no child if (root->left == NULL) { struct node* temp = root->right; free(root); return temp; } else if (root->right == NULL) { struct node* temp = root->left; free(root); return temp; } // node with two children: // Get the inorder successor // (smallest in the right subtree) struct node* temp = minValueNode(root->right); // Copy the inorder // successor's content to this node root->key = temp->key; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } return root;} // Driver Codeint main(){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ struct node* root = NULL; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); printf(\"Inorder traversal of the given tree \\n\"); inorder(root); printf(\"\\nDelete 20\\n\"); root = deleteNode(root, 20); printf(\"Inorder traversal of the modified tree \\n\"); inorder(root); printf(\"\\nDelete 30\\n\"); root = deleteNode(root, 30); printf(\"Inorder traversal of the modified tree \\n\"); inorder(root); printf(\"\\nDelete 50\\n\"); root = deleteNode(root, 50); printf(\"Inorder traversal of the modified tree \\n\"); inorder(root); return 0;}", "e": 9304, "s": 5620, "text": null }, { "code": "// Java program to demonstrate// delete operation in binary// search treeclass BinarySearchTree { /* Class containing left and right child of current node * and key value*/ class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; } } // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // This method mainly calls deleteRec() void deleteKey(int key) { root = deleteRec(root, key); } /* A recursive function to delete an existing key in BST */ Node deleteRec(Node root, int key) { /* Base Case: If the tree is empty */ if (root == null) return root; /* Otherwise, recur down the tree */ if (key < root.key) root.left = deleteRec(root.left, key); else if (key > root.key) root.right = deleteRec(root.right, key); // if key is same as root's // key, then This is the // node to be deleted else { // node with only one child or no child if (root.left == null) return root.right; else if (root.right == null) return root.left; // node with two children: Get the inorder // successor (smallest in the right subtree) root.key = minValue(root.right); // Delete the inorder successor root.right = deleteRec(root.right, root.key); } return root; } int minValue(Node root) { int minv = root.key; while (root.left != null) { minv = root.left.key; root = root.left; } return minv; } // This method mainly calls insertRec() void insert(int key) { root = insertRec(root, key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root, int key) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise, recur down the tree */ if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); /* return the (unchanged) node pointer */ return root; } // This method mainly calls InorderRec() void inorder() { inorderRec(root); } // A utility function to do inorder traversal of BST void inorderRec(Node root) { if (root != null) { inorderRec(root.left); System.out.print(root.key + \" \"); inorderRec(root.right); } } // Driver Code public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ tree.insert(50); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(70); tree.insert(60); tree.insert(80); System.out.println( \"Inorder traversal of the given tree\"); tree.inorder(); System.out.println(\"\\nDelete 20\"); tree.deleteKey(20); System.out.println( \"Inorder traversal of the modified tree\"); tree.inorder(); System.out.println(\"\\nDelete 30\"); tree.deleteKey(30); System.out.println( \"Inorder traversal of the modified tree\"); tree.inorder(); System.out.println(\"\\nDelete 50\"); tree.deleteKey(50); System.out.println( \"Inorder traversal of the modified tree\"); tree.inorder(); }}", "e": 13093, "s": 9304, "text": null }, { "code": "# Python program to demonstrate delete operation# in binary search tree # A Binary Tree Node class Node: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to do inorder traversal of BSTdef inorder(root): if root is not None: inorder(root.left) print (root.key,end=\" \") inorder(root.right) # A utility function to insert a# new node with given key in BSTdef insert(node, key): # If the tree is empty, return a new node if node is None: return Node(key) # Otherwise recur down the tree if key < node.key: node.left = insert(node.left, key) else: node.right = insert(node.right, key) # return the (unchanged) node pointer return node # Given a non-empty binary# search tree, return the node# with minimum key value# found in that tree. Note that the# entire tree does not need to be searched def minValueNode(node): current = node # loop down to find the leftmost leaf while(current.left is not None): current = current.left return current # Given a binary search tree and a key, this function# delete the key and returns the new root def deleteNode(root, key): # Base Case if root is None: return root # If the key to be deleted # is smaller than the root's # key then it lies in left subtree if key < root.key: root.left = deleteNode(root.left, key) # If the kye to be delete # is greater than the root's key # then it lies in right subtree elif(key > root.key): root.right = deleteNode(root.right, key) # If key is same as root's key, then this is the node # to be deleted else: # Node with only one child or no child if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp # Node with two children: # Get the inorder successor # (smallest in the right subtree) temp = minValueNode(root.right) # Copy the inorder successor's # content to this node root.key = temp.key # Delete the inorder successor root.right = deleteNode(root.right, temp.key) return root # Driver code\"\"\" Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 \"\"\" root = Noneroot = insert(root, 50)root = insert(root, 30)root = insert(root, 20)root = insert(root, 40)root = insert(root, 70)root = insert(root, 60)root = insert(root, 80) print (\"Inorder traversal of the given tree\")inorder(root) print (\"\\nDelete 20\")root = deleteNode(root, 20)print (\"Inorder traversal of the modified tree\")inorder(root) print (\"\\nDelete 30\")root = deleteNode(root, 30)print (\"Inorder traversal of the modified tree\")inorder(root) print (\"\\nDelete 50\")root = deleteNode(root, 50)print (\"Inorder traversal of the modified tree\")inorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 16225, "s": 13093, "text": null }, { "code": "// C# program to demonstrate delete// operation in binary search treeusing System; public class BinarySearchTree { /* Class containing left and right child of current node and key value*/ class Node { public int key; public Node left, right; public Node(int item) { key = item; left = right = null; } } // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // This method mainly calls deleteRec() void deleteKey(int key) { root = deleteRec(root, key); } /* A recursive function to delete an existing key in BST */ Node deleteRec(Node root, int key) { /* Base Case: If the tree is empty */ if (root == null) return root; /* Otherwise, recur down the tree */ if (key < root.key) root.left = deleteRec(root.left, key); else if (key > root.key) root.right = deleteRec(root.right, key); // if key is same as root's key, then This is the // node to be deleted else { // node with only one child or no child if (root.left == null) return root.right; else if (root.right == null) return root.left; // node with two children: Get the // inorder successor (smallest // in the right subtree) root.key = minValue(root.right); // Delete the inorder successor root.right = deleteRec(root.right, root.key); } return root; } int minValue(Node root) { int minv = root.key; while (root.left != null) { minv = root.left.key; root = root.left; } return minv; } // This method mainly calls insertRec() void insert(int key) { root = insertRec(root, key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root, int key) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise, recur down the tree */ if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); /* return the (unchanged) node pointer */ return root; } // This method mainly calls InorderRec() void inorder() { inorderRec(root); } // A utility function to do inorder traversal of BST void inorderRec(Node root) { if (root != null) { inorderRec(root.left); Console.Write(root.key + \" \"); inorderRec(root.right); } } // Driver code public static void Main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ tree.insert(50); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(70); tree.insert(60); tree.insert(80); Console.WriteLine( \"Inorder traversal of the given tree\"); tree.inorder(); Console.WriteLine(\"\\nDelete 20\"); tree.deleteKey(20); Console.WriteLine( \"Inorder traversal of the modified tree\"); tree.inorder(); Console.WriteLine(\"\\nDelete 30\"); tree.deleteKey(30); Console.WriteLine( \"Inorder traversal of the modified tree\"); tree.inorder(); Console.WriteLine(\"\\nDelete 50\"); tree.deleteKey(50); Console.WriteLine( \"Inorder traversal of the modified tree\"); tree.inorder(); }} // This code has been contributed// by PrinciRaj1992", "e": 20036, "s": 16225, "text": null }, { "code": "<script>// Javascript program to demonstrate// delete operation in binary// search treeclass Node{ constructor(item) { this.key = item; this.left = this.right = null; }} // Root of BSTlet root=null; // This method mainly calls deleteRec()function deleteKey(key){ root = deleteRec(root, key);} /* A recursive function to delete an existing key in BST */function deleteRec(root,key){ /* Base Case: If the tree is empty */ if (root == null) return root; /* Otherwise, recur down the tree */ if (key < root.key) root.left = deleteRec(root.left, key); else if (key > root.key) root.right = deleteRec(root.right, key); // if key is same as root's // key, then This is the // node to be deleted else { // node with only one child or no child if (root.left == null) return root.right; else if (root.right == null) return root.left; // node with two children: Get the inorder // successor (smallest in the right subtree) root.key = minValue(root.right); // Delete the inorder successor root.right = deleteRec(root.right, root.key); } return root;} function minValue(root){ let minv = root.key; while (root.left != null) { minv = root.left.key; root = root.left; } return minv;} // This method mainly calls insertRec()function insert(key){ root = insertRec(root, key);} /* A recursive function to insert a new key in BST */function insertRec(root,key){ /* If the tree is empty, return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise, recur down the tree */ if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); /* return the (unchanged) node pointer */ return root;} // This method mainly calls InorderRec()function inorder(){ inorderRec(root);} // A utility function to do inorder traversal of BSTfunction inorderRec(root){ if (root != null) { inorderRec(root.left); document.write(root.key + \" \"); inorderRec(root.right); }} // Driver Code/* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */insert(50);insert(30);insert(20);insert(40);insert(70);insert(60);insert(80); document.write(\"Inorder traversal of the given tree<br>\");inorder(); document.write(\"<br>Delete 20<br>\");deleteKey(20);document.write(\"Inorder traversal of the modified tree<br>\");inorder(); document.write(\"<br>Delete 30<br>\");deleteKey(30);document.write(\"Inorder traversal of the modified tree<br>\");inorder(); document.write(\"<br>Delete 50<br>\");deleteKey(50);document.write(\"Inorder traversal of the modified tree<br>\");inorder(); // This code is contributed by avanitrachhadiya2155</script>", "e": 23171, "s": 20036, "text": null }, { "code": null, "e": 23406, "s": 23171, "text": "Inorder traversal of the given tree \n20304050607080\nDelete 20\nInorder traversal of the modified tree \n304050607080\nDelete 30\nInorder traversal of the modified tree \n4050607080\nDelete 50\nInorder traversal of the modified tree \n40607080" }, { "code": null, "e": 23421, "s": 23406, "text": "Illustration: " }, { "code": null, "e": 23726, "s": 23423, "text": "Time Complexity: The worst case time complexity of delete operation is O(h) where h is the height of the Binary Search Tree. In worst case, we may have to travel from the root to the deepest leaf node. The height of a skewed tree may become n and the time complexity of delete operation may become O(n)" }, { "code": null, "e": 24073, "s": 23726, "text": "Optimization to above code for two children case : In the above recursive code, we recursively call delete() for the successor. We can avoid recursive calls by keeping track of the parent node of the successor so that we can simply remove the successor by making the child of a parent NULL. We know that the successor would always be a leaf node." }, { "code": null, "e": 24089, "s": 24073, "text": "Implementation:" }, { "code": null, "e": 24093, "s": 24089, "text": "C++" }, { "code": null, "e": 24098, "s": 24093, "text": "Java" }, { "code": null, "e": 24101, "s": 24098, "text": "C#" }, { "code": null, "e": 24109, "s": 24101, "text": "Python3" }, { "code": null, "e": 24120, "s": 24109, "text": "Javascript" }, { "code": "// C++ program to implement optimized delete in BST.#include <bits/stdc++.h>using namespace std; struct Node { int key; struct Node *left, *right;}; // A utility function to create a new BST nodeNode* newNode(int item){ Node* temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to do inorder traversal of BSTvoid inorder(Node* root){ if (root != NULL) { inorder(root->left); printf(\"%d \", root->key); inorder(root->right); }} /* A utility function to insert a new node with given key in * BST */Node* insert(Node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} /* Given a binary search tree and a key, this function deletes the key and returns the new root */Node* deleteNode(Node* root, int k){ // Base case if (root == NULL) return root; // Recursive calls for ancestors of // node to be deleted if (root->key > k) { root->left = deleteNode(root->left, k); return root; } else if (root->key < k) { root->right = deleteNode(root->right, k); return root; } // We reach here when root is the node // to be deleted. // If one of the children is empty if (root->left == NULL) { Node* temp = root->right; delete root; return temp; } else if (root->right == NULL) { Node* temp = root->left; delete root; return temp; } // If both children exist else { Node* succParent = root; // Find successor Node* succ = root->right; while (succ->left != NULL) { succParent = succ; succ = succ->left; } // Delete successor. Since successor // is always left child of its parent // we can safely make successor's right // right child as left of its parent. // If there is no succ, then assign // succ->right to succParent->right if (succParent != root) succParent->left = succ->right; else succParent->right = succ->right; // Copy Successor Data to root root->key = succ->key; // Delete Successor and return root delete succ; return root; }} // Driver Codeint main(){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ Node* root = NULL; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); printf(\"Inorder traversal of the given tree \\n\"); inorder(root); printf(\"\\nDelete 20\\n\"); root = deleteNode(root, 20); printf(\"Inorder traversal of the modified tree \\n\"); inorder(root); printf(\"\\nDelete 30\\n\"); root = deleteNode(root, 30); printf(\"Inorder traversal of the modified tree \\n\"); inorder(root); printf(\"\\nDelete 50\\n\"); root = deleteNode(root, 50); printf(\"Inorder traversal of the modified tree \\n\"); inorder(root); return 0;}", "e": 27519, "s": 24120, "text": null }, { "code": "// Java program to implement optimized delete in BST.import java.util.*; class GFG{ static class Node{ int key; Node left, right;} // A utility function to create a new BST nodestatic Node newNode(int item){ Node temp = new Node(); temp.key = item; temp.left = temp.right = null; return temp;} // A utility function to do inorder traversal of BSTstatic void inorder(Node root){ if (root != null) { inorder(root.left); System.out.print(root.key + \" \"); inorder(root.right); }} // A utility function to insert a new node// with given key in BSTstatic Node insert(Node node, int key){ // If the tree is empty, return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); // Return the (unchanged) node pointer return node;} // Given a binary search tree and a key, this// function deletes the key and returns the// new rootstatic Node deleteNode(Node root, int k){ // Base case if (root == null) return root; // Recursive calls for ancestors of // node to be deleted if (root.key > k) { root.left = deleteNode(root.left, k); return root; } else if (root.key < k) { root.right = deleteNode(root.right, k); return root; } // We reach here when root is the node // to be deleted. // If one of the children is empty if (root.left == null) { Node temp = root.right; return temp; } else if (root.right == null) { Node temp = root.left; return temp; } // If both children exist else { Node succParent = root; // Find successor Node succ = root.right; while (succ.left != null) { succParent = succ; succ = succ.left; } // Delete successor. Since successor // is always left child of its parent // we can safely make successor's right // right child as left of its parent. // If there is no succ, then assign // succ->right to succParent->right if (succParent != root) succParent.left = succ.right; else succParent.right = succ.right; // Copy Successor Data to root root.key = succ.key; return root; }} // Driver Codepublic static void main(String args[]){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ Node root = null; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); System.out.println(\"Inorder traversal of the \" + \"given tree\"); inorder(root); System.out.println(\"\\nDelete 20\\n\"); root = deleteNode(root, 20); System.out.println(\"Inorder traversal of the \" + \"modified tree\"); inorder(root); System.out.println(\"\\nDelete 30\\n\"); root = deleteNode(root, 30); System.out.println(\"Inorder traversal of the \" + \"modified tree\"); inorder(root); System.out.println(\"\\nDelete 50\\n\"); root = deleteNode(root, 50); System.out.println(\"Inorder traversal of the \" + \"modified tree\"); inorder(root);}} // This code is contributed by adityapande88", "e": 31046, "s": 27519, "text": null }, { "code": "// C# program to implement optimized delete in BST.using System; class GFG{ class Node{ public int key; public Node left, right;} // A utility function to create a new BST nodestatic Node newNode(int item){ Node temp = new Node(); temp.key = item; temp.left = temp.right = null; return temp;} // A utility function to do inorder traversal of BSTstatic void inorder(Node root){ if (root != null) { inorder(root.left); Console.Write(root.key + \" \"); inorder(root.right); }} // A utility function to insert a new node// with given key in BSTstatic Node insert(Node node, int key){ // If the tree is empty, return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); // Return the (unchanged) node pointer return node;} // Given a binary search tree and a key, this// function deletes the key and returns the// new rootstatic Node deleteNode(Node root, int k){ // Base case if (root == null) return root; // Recursive calls for ancestors of // node to be deleted if (root.key > k) { root.left = deleteNode(root.left, k); return root; } else if (root.key < k) { root.right = deleteNode(root.right, k); return root; } // We reach here when root is the node // to be deleted. // If one of the children is empty if (root.left == null) { Node temp = root.right; return temp; } else if (root.right == null) { Node temp = root.left; return temp; } // If both children exist else { Node succParent = root; // Find successor Node succ = root.right; while (succ.left != null) { succParent = succ; succ = succ.left; } // Delete successor. Since successor // is always left child of its parent // we can safely make successor's right // right child as left of its parent. // If there is no succ, then assign // succ->right to succParent->right if (succParent != root) succParent.left = succ.right; else succParent.right = succ.right; // Copy Successor Data to root root.key = succ.key; return root; }} // Driver Codepublic static void Main(String []args){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ Node root = null; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); Console.WriteLine(\"Inorder traversal of the \" + \"given tree\"); inorder(root); Console.WriteLine(\"\\nDelete 20\\n\"); root = deleteNode(root, 20); Console.WriteLine(\"Inorder traversal of the \" + \"modified tree\"); inorder(root); Console.WriteLine(\"\\nDelete 30\\n\"); root = deleteNode(root, 30); Console.WriteLine(\"Inorder traversal of the \" + \"modified tree\"); inorder(root); Console.WriteLine(\"\\nDelete 50\\n\"); root = deleteNode(root, 50); Console.WriteLine(\"Inorder traversal of the \" + \"modified tree\"); inorder(root);}} // This code is contributed by shivanisinghss2110", "e": 34560, "s": 31046, "text": null }, { "code": "# Python3 program to implement# optimized delete in BST. class Node: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to do# inorder traversal of BSTdef inorder(root): if root is not None: inorder(root.left) print(root.key, end=\" \") inorder(root.right) # A utility function to insert a# new node with given key in BSTdef insert(node, key): # If the tree is empty, # return a new node if node is None: return Node(key) # Otherwise recur down the tree if key < node.key: node.left = insert(node.left, key) else: node.right = insert(node.right, key) # return the (unchanged) node pointer return node # Given a binary search tree# and a key, this function# delete the key and returns the new rootdef deleteNode(root, key): # Base Case if root is None: return root # Recursive calls for ancestors of # node to be deleted if key < root.key: root.left = deleteNode(root.left, key) return root elif(key > root.key): root.right = deleteNode(root.right, key) return root # We reach here when root is the node # to be deleted. # If root node is a leaf node if root.left is None and root.right is None: return None # If one of the children is empty if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp # If both children exist succParent = root # Find Successor succ = root.right while succ.left != None: succParent = succ succ = succ.left # Delete successor.Since successor # is always left child of its parent # we can safely make successor's right # right child as left of its parent. # If there is no succ, then assign # succ->right to succParent->right if succParent != root: succParent.left = succ.right else: succParent.right = succ.right # Copy Successor Data to root root.key = succ.key return root # Driver code\"\"\" Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 \"\"\" root = Noneroot = insert(root, 50)root = insert(root, 30)root = insert(root, 20)root = insert(root, 40)root = insert(root, 70)root = insert(root, 60)root = insert(root, 80) print(\"Inorder traversal of the given tree\")inorder(root) print(\"\\nDelete 20\")root = deleteNode(root, 20)print(\"Inorder traversal of the modified tree\")inorder(root) print(\"\\nDelete 30\")root = deleteNode(root, 30)print(\"Inorder traversal of the modified tree\")inorder(root) print(\"\\nDelete 50\")root = deleteNode(root, 50)print(\"Inorder traversal of the modified tree\")inorder(root) # This code is contributed by Shivam Bhat (shivambhat45)", "e": 37503, "s": 34560, "text": null }, { "code": "<script>// javascript program to implement optimized delete in BST. class Node { constructor(val) { this.key = val; this.left = null; this.right = null; }} // A utility function to create a new BST node function newNode(item) {var temp = new Node(); temp.key = item; temp.left = temp.right = null; return temp; } // A utility function to do inorder traversal of BST function inorder(root) { if (root != null) { inorder(root.left); document.write(root.key + \" \"); inorder(root.right); } } // A utility function to insert a new node // with given key in BST function insert(node , key) { // If the tree is empty, return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); // Return the (unchanged) node pointer return node; } // Given a binary search tree and a key, this // function deletes the key and returns the // new root function deleteNode(root , k) { // Base case if (root == null) return root; // Recursive calls for ancestors of // node to be deleted if (root.key > k) { root.left = deleteNode(root.left, k); return root; } else if (root.key < k) { root.right = deleteNode(root.right, k); return root; } // We reach here when root is the node // to be deleted. // If one of the children is empty if (root.left == null) { var temp = root.right; return temp; } else if (root.right == null) { var temp = root.left; return temp; } // If both children exist else { var succParent = root; // Find successor var succ = root.right; while (succ.left != null) { succParent = succ; succ = succ.left; } // Delete successor. Since successor // is always left child of its parent // we can safely make successor's right // right child as left of its parent. // If there is no succ, then assign // succ->right to succParent->right if (succParent != root) succParent.left = succ.right; else succParent.right = succ.right; // Copy Successor Data to root root.key = succ.key; return root; } } // Driver Code /* * Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */var root = null; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); document.write(\"Inorder traversal of the \" + \"given tree<br/>\"); inorder(root); document.write(\"<br/>Delete 20<br/>\"); root = deleteNode(root, 20); document.write(\"Inorder traversal of the \" + \"modified tree<br/>\"); inorder(root); document.write(\"<br/>Delete 30<br/>\"); root = deleteNode(root, 30); document.write(\"Inorder traversal of the \" + \"modified tree<br/>\"); inorder(root); document.write(\"<br/>Delete 50<br/>\"); root = deleteNode(root, 50); document.write(\"Inorder traversal of the \" + \"modified tree<br/>\"); inorder(root); // This code contributed by Rajput-Ji</script>", "e": 41243, "s": 37503, "text": null }, { "code": null, "e": 41500, "s": 41243, "text": "Inorder traversal of the given tree \n20 30 40 50 60 70 80 \nDelete 20\nInorder traversal of the modified tree \n30 40 50 60 70 80 \nDelete 30\nInorder traversal of the modified tree \n40 50 60 70 80 \nDelete 50\nInorder traversal of the modified tree \n40 60 70 80 " }, { "code": null, "e": 41577, "s": 41500, "text": "Thanks to wolffgang010 for suggesting the above optimization.Related Links: " }, { "code": null, "e": 41628, "s": 41577, "text": "Binary Search Tree Introduction, Search and Insert" }, { "code": null, "e": 41655, "s": 41628, "text": "Quiz on Binary Search Tree" }, { "code": null, "e": 41678, "s": 41655, "text": "Coding practice on BST" }, { "code": null, "e": 41698, "s": 41678, "text": "All Articles on BST" }, { "code": null, "e": 41713, "s": 41698, "text": "Manoj Kumar 20" }, { "code": null, "e": 41726, "s": 41713, "text": "wolffgang010" }, { "code": null, "e": 41740, "s": 41726, "text": "princiraj1992" }, { "code": null, "e": 41755, "s": 41740, "text": "Sarvesh Ranjan" }, { "code": null, "e": 41770, "s": 41755, "text": "harispartacus0" }, { "code": null, "e": 41789, "s": 41770, "text": "shivanisinghss2110" }, { "code": null, "e": 41795, "s": 41789, "text": "j9rex" }, { "code": null, "e": 41808, "s": 41795, "text": "shivambhat45" }, { "code": null, "e": 41820, "s": 41808, "text": "agarwalr327" }, { "code": null, "e": 41833, "s": 41820, "text": "imran khan 1" }, { "code": null, "e": 41847, "s": 41833, "text": "adityapande88" }, { "code": null, "e": 41854, "s": 41847, "text": "liocat" }, { "code": null, "e": 41875, "s": 41854, "text": "avanitrachhadiya2155" }, { "code": null, "e": 41890, "s": 41875, "text": "sagartomar9927" }, { "code": null, "e": 41906, "s": 41890, "text": "amartyaghoshgfg" }, { "code": null, "e": 41916, "s": 41906, "text": "Rajput-Ji" }, { "code": null, "e": 41933, "s": 41916, "text": "hardikkoriintern" }, { "code": null, "e": 41942, "s": 41933, "text": "Accolite" }, { "code": null, "e": 41949, "s": 41942, "text": "Amazon" }, { "code": null, "e": 41958, "s": 41949, "text": "Qualcomm" }, { "code": null, "e": 41966, "s": 41958, "text": "Samsung" }, { "code": null, "e": 41985, "s": 41966, "text": "Binary Search Tree" }, { "code": null, "e": 41994, "s": 41985, "text": "Accolite" }, { "code": null, "e": 42001, "s": 41994, "text": "Amazon" }, { "code": null, "e": 42009, "s": 42001, "text": "Samsung" }, { "code": null, "e": 42018, "s": 42009, "text": "Qualcomm" }, { "code": null, "e": 42037, "s": 42018, "text": "Binary Search Tree" }, { "code": null, "e": 42135, "s": 42037, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42185, "s": 42135, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 42241, "s": 42185, "text": "Find postorder traversal of BST from preorder traversal" }, { "code": null, "e": 42311, "s": 42241, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 42340, "s": 42311, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 42375, "s": 42340, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 42415, "s": 42375, "text": "Inorder Successor in Binary Search Tree" }, { "code": null, "e": 42452, "s": 42415, "text": "Convert a normal BST to Balanced BST" }, { "code": null, "e": 42484, "s": 42452, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 42544, "s": 42484, "text": "Find k-th smallest element in BST (Order Statistics in BST)" } ]
C++ program to create one rectangle class and calculate its area
Suppose we have taken length and breadth of two rectangles, and we want to calculate their area using class. So we can make a class called Rectangle with two attributes l and b for length and breadth respectively. And define another function called area() to calculate area of that rectangle. So, if the input is like (10,9), (8,6), then the output will be 90 and 48 as the length and breadth of first rectangle is 10 and 9, so area is 10 * 9 = 90, and for the second one, the length and breadth is 8 and 6, so area is 8 * 6 = 48. To solve this, we will follow these steps − Define rectangle class with two attributes l and b Define rectangle class with two attributes l and b define input() function to take input for l and b define input() function to take input for l and b define area() function to return l * b, which is the area of that rectangle define area() function to return l * b, which is the area of that rectangle Let us see the following implementation to get better understanding − #include <iostream> using namespace std; class Rectangle{ private: int l, b; public: void input(int len, int bre){ l = len; b = bre; } int area(){ return l * b; } }; int main(){ Rectangle r1, r2; r1.input(10, 9); r2.input(8, 6); cout << "Area of r1: " << r1.area() << endl; cout << "Area of r2: " << r2.area() << endl; } (10, 9), (8, 6) Area of r1: 90 Area of r2: 48
[ { "code": null, "e": 1355, "s": 1062, "text": "Suppose we have taken length and breadth of two rectangles, and we want to calculate their area using class. So we can make a class called Rectangle with two attributes l and b for length and breadth respectively. And define another function called area() to calculate area of that rectangle." }, { "code": null, "e": 1593, "s": 1355, "text": "So, if the input is like (10,9), (8,6), then the output will be 90 and 48 as the length and breadth of first rectangle is 10 and 9, so area is 10 * 9 = 90, and for the second one, the length and breadth is 8 and 6, so area is 8 * 6 = 48." }, { "code": null, "e": 1637, "s": 1593, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1688, "s": 1637, "text": "Define rectangle class with two attributes l and b" }, { "code": null, "e": 1739, "s": 1688, "text": "Define rectangle class with two attributes l and b" }, { "code": null, "e": 1789, "s": 1739, "text": "define input() function to take input for l and b" }, { "code": null, "e": 1839, "s": 1789, "text": "define input() function to take input for l and b" }, { "code": null, "e": 1915, "s": 1839, "text": "define area() function to return l * b, which is the area of that rectangle" }, { "code": null, "e": 1991, "s": 1915, "text": "define area() function to return l * b, which is the area of that rectangle" }, { "code": null, "e": 2061, "s": 1991, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2487, "s": 2061, "text": "#include <iostream>\nusing namespace std;\nclass Rectangle{\n private:\n int l, b;\n public:\n void input(int len, int bre){\n l = len;\n b = bre;\n }\n int area(){\n return l * b;\n }\n};\nint main(){\n Rectangle r1, r2;\n r1.input(10, 9);\n r2.input(8, 6);\n cout << \"Area of r1: \" << r1.area() << endl;\n cout << \"Area of r2: \" << r2.area() << endl;\n}\n" }, { "code": null, "e": 2503, "s": 2487, "text": "(10, 9), (8, 6)" }, { "code": null, "e": 2533, "s": 2503, "text": "Area of r1: 90\nArea of r2: 48" } ]
How to Join Strings in Golang?. There are multiple ways to join or... | by Shubham Chadokar | Towards Data Science
There are multiple ways to join or concat strings in the golang. Let’s start with the easy one. Originally published at https://schadokar.dev. package mainimport ( "fmt")func main() { str1 := "Hello" // there is a space before World str2 := " World!"fmt.Println(str1 + str2)} Output Hello World! The fmt package has Sprint, Sprintf and Sprintln function which can format the strings using the default or custom formats. All the Sprint function are variadic functions. Variadic functions can be called with any number of trailing arguments. Sprint formats using the default formats and returns the resulting string. Sprint accepts an empty interface. It means it can take n elements of any type. If no element of type string is passed then the resulting string will add a Space between the elements. package mainimport ( "fmt")func main() { num := 26 str := "Feb" boolean := true withStr := fmt.Sprint(num, str, boolean) fmt.Println("With string: ", withStr) withOutStr := fmt.Sprint(num, boolean) fmt.Println("Without string: ", withOutStr)} Output With string: 26Febtrue Without string: 26 true Sprintf formats according to a format specifier and returns the resulting string. Format Specifiers %v the value in a default format %s the uninterpreted bytes of the string or slice Check all the available format specifier in the fmt package. You can use the Sprintf function to create the connection string of the DB. For example we will create a Postgres Connection URL. Connection URL format: postgres://username:password@hostname/databasename package mainimport ( "fmt")func main() { dbname := "testdb" username := "admin" password := "test1234" hostname := "localhost" connectionURL := fmt.Sprintf("postgres://%s:%s@%v/%v", username, password, hostname, dbname) fmt.Println(connectionURL)} Output postgres://admin:test1234@localhost/testdb Sprintln formats the elements or arguments using the default formats. Spaces are added between the elements and a new line is added in the end. package mainimport ( "fmt")func main() { str1 := "Hello" str2 := "Gophers!" msg := fmt.Sprintln(str1, str2) fmt.Println(msg)} Output Hello Gophers! The golang standard library has provided a Join function in the strings package. The Join function takes an array of strings and a separator to join them. func Join(elems []string, sep string) string The example has an array of weekdays. The Join function will return a string of weekdays separated by , . Using Join you can convert an array of string to a string. package mainimport ( "fmt" "strings")func main() { weekdays := []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"} // there is a space after comma fmt.Println(strings.Join(weekdays, ", "))} Output Monday, Tuesday, Wednesday, Thursday, Friday Originally published at https://schadokar.dev. You can read my latest golang tutorial on my blog.
[ { "code": null, "e": 237, "s": 172, "text": "There are multiple ways to join or concat strings in the golang." }, { "code": null, "e": 268, "s": 237, "text": "Let’s start with the easy one." }, { "code": null, "e": 315, "s": 268, "text": "Originally published at https://schadokar.dev." }, { "code": null, "e": 448, "s": 315, "text": "package mainimport ( \"fmt\")func main() { str1 := \"Hello\" // there is a space before World str2 := \" World!\"fmt.Println(str1 + str2)}" }, { "code": null, "e": 455, "s": 448, "text": "Output" }, { "code": null, "e": 468, "s": 455, "text": "Hello World!" }, { "code": null, "e": 592, "s": 468, "text": "The fmt package has Sprint, Sprintf and Sprintln function which can format the strings using the default or custom formats." }, { "code": null, "e": 640, "s": 592, "text": "All the Sprint function are variadic functions." }, { "code": null, "e": 712, "s": 640, "text": "Variadic functions can be called with any number of trailing arguments." }, { "code": null, "e": 787, "s": 712, "text": "Sprint formats using the default formats and returns the resulting string." }, { "code": null, "e": 971, "s": 787, "text": "Sprint accepts an empty interface. It means it can take n elements of any type. If no element of type string is passed then the resulting string will add a Space between the elements." }, { "code": null, "e": 1228, "s": 971, "text": "package mainimport ( \"fmt\")func main() { num := 26 str := \"Feb\" boolean := true withStr := fmt.Sprint(num, str, boolean) fmt.Println(\"With string: \", withStr) withOutStr := fmt.Sprint(num, boolean) fmt.Println(\"Without string: \", withOutStr)}" }, { "code": null, "e": 1235, "s": 1228, "text": "Output" }, { "code": null, "e": 1282, "s": 1235, "text": "With string: 26Febtrue Without string: 26 true" }, { "code": null, "e": 1364, "s": 1282, "text": "Sprintf formats according to a format specifier and returns the resulting string." }, { "code": null, "e": 1382, "s": 1364, "text": "Format Specifiers" }, { "code": null, "e": 1465, "s": 1382, "text": "%v\tthe value in a default format %s\tthe uninterpreted bytes of the string or slice" }, { "code": null, "e": 1526, "s": 1465, "text": "Check all the available format specifier in the fmt package." }, { "code": null, "e": 1602, "s": 1526, "text": "You can use the Sprintf function to create the connection string of the DB." }, { "code": null, "e": 1656, "s": 1602, "text": "For example we will create a Postgres Connection URL." }, { "code": null, "e": 1730, "s": 1656, "text": "Connection URL format: postgres://username:password@hostname/databasename" }, { "code": null, "e": 1990, "s": 1730, "text": "package mainimport ( \"fmt\")func main() { dbname := \"testdb\" username := \"admin\" password := \"test1234\" hostname := \"localhost\" connectionURL := fmt.Sprintf(\"postgres://%s:%s@%v/%v\", username, password, hostname, dbname) fmt.Println(connectionURL)}" }, { "code": null, "e": 1997, "s": 1990, "text": "Output" }, { "code": null, "e": 2040, "s": 1997, "text": "postgres://admin:test1234@localhost/testdb" }, { "code": null, "e": 2184, "s": 2040, "text": "Sprintln formats the elements or arguments using the default formats. Spaces are added between the elements and a new line is added in the end." }, { "code": null, "e": 2310, "s": 2184, "text": "package mainimport ( \"fmt\")func main() { str1 := \"Hello\" str2 := \"Gophers!\" msg := fmt.Sprintln(str1, str2) fmt.Println(msg)}" }, { "code": null, "e": 2317, "s": 2310, "text": "Output" }, { "code": null, "e": 2332, "s": 2317, "text": "Hello Gophers!" }, { "code": null, "e": 2413, "s": 2332, "text": "The golang standard library has provided a Join function in the strings package." }, { "code": null, "e": 2487, "s": 2413, "text": "The Join function takes an array of strings and a separator to join them." }, { "code": null, "e": 2532, "s": 2487, "text": "func Join(elems []string, sep string) string" }, { "code": null, "e": 2638, "s": 2532, "text": "The example has an array of weekdays. The Join function will return a string of weekdays separated by , ." }, { "code": null, "e": 2697, "s": 2638, "text": "Using Join you can convert an array of string to a string." }, { "code": null, "e": 2909, "s": 2697, "text": "package mainimport ( \"fmt\" \"strings\")func main() { weekdays := []string{\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\"} // there is a space after comma fmt.Println(strings.Join(weekdays, \", \"))}" }, { "code": null, "e": 2916, "s": 2909, "text": "Output" }, { "code": null, "e": 2961, "s": 2916, "text": "Monday, Tuesday, Wednesday, Thursday, Friday" }, { "code": null, "e": 3008, "s": 2961, "text": "Originally published at https://schadokar.dev." } ]
Interactive Choropleth Maps With Plotly | by Benedikt Droste | Towards Data Science
Recently, I wanted to visualize data from the last federal election. I live in Duesseldorf, Germany and wanted to know in which districts which party had relative strengths.Surprisingly, it was a little harder than expected. Therefore I would like to share my experiences here. We will go through the following steps together: 0. Preparation1. Reading Data Over An Api In GeoJSON- And JSON-Format2. Extracting The Relevant Features From The GeoJSON-Data3. Customizing Our Map With Colorscales and Mouseovers4. Putting Everything Together And Adding Interactivity You can follow this tutorial with your own dataset to create your individual map. The easiest way to do this would be to have the data in GeoJSON or JSON format. Here you can take a look at the data from this tutorial: https://opendata.duesseldorf.de/api/action/datastore/search.json?resource_id=6893a12e-3d75-4b2f-bb8b-708982bea7b7 https://opendata.duesseldorf.de/sites/default/files/Stadtteile_WGS84_4326.geojson You also need a mapbox account for this tutorial. Mapbox provides a flexible geodata API. Using the Mapbox API, we can map our individual data to a scalable world map. You can create an account at www.mapbox.com. You need a individual token to use the mapbox services which be be found under the account settings: GeoJSON is open standard format for geographical features. Within this standard, storage of data follows a particular structure. Features can be points, lines, polygons or even combinations of the three types. For example, a polygon, a closed area inside a specific room, might look like this: {"type": "Polygon","coordinates": [[[35, 10], [45, 45], [15, 40], [10, 20], [35, 10]],[[20, 30], [35, 35], [30, 20], [20, 30]]]} In our example, we will also access GeoJSON data and combine it with JSON data. On the website https://opendate.duesseldorf.de there are both geodata and election data for the districts in Dusseldorf. However, the data is separated and we must merge it later. First, we import all necessary libraries: import pandas as pdimport numpy as npimport urllib.request, jsonimport requests Now we can read the contents for the URLs: url_wahl_2017 = 'https://opendata.duesseldorf.de/api/action/datastore/search.json?resource_id=6893a12e-3d75-4b2f-bb8b-708982bea7b7'url_stadtteile = 'https://opendata.duesseldorf.de/sites/default/files/Stadtteile_WGS84_4326.geojson'geo_data = requests.get(url_stadtteile).json()data_wahl = requests.get(url_wahl_2017).json() Both data sources are now available as a nested dictionary. With data_wahl['result']['records'] the election results of the individual districts can be displayed: We can now import the relevant election data from the dictionary into a pandas dataframe: df_wahl = pd.DataFrame.from_dict(data_wahl['result']['records']) Now let’s look at the geodata. For further processing with Plotly, we now extract the relevant features from the geodata request: sources=[{"type": "FeatureCollection", 'features': [feat]} for feat in geo_data['features']] The list sources contains the coordinates for all parts of the city. We will later hand over this list to the Mapbox object in order to present the respective districts.The IDs of the districts are also extracted from the geodata: tx_ids=[geo_data['features'][k]['properties']['Stadtteil'] for k in range(len(geo_data['features']))] We need the IDs later to allocate the correct colorscales for each party and each district. In order to be able to dynamically color the individual parts of the city later on, we need the range of the respective percentages for each party. The lightest shade is assigned the lowest value and the highest value the darkest shade. For this we determine for each party and each district the lowest and highest value: parties = ['Wahlsieger_proz','CDU_Proz','SPD_Proz','DIE LINKE_Proz','GRÜNE_Proz','AfD_Proz','FDP_Proz']for n in range(0,len(rate_list)):dct[rate_list[n]] = [df.loc[stadtteil, parties[n]] for stadtteil in tx_ids]dct_min[mins_list[n]] = min(dct[rate_list[n]])dct_max[maxs_list[n]] = max(dct[rate_list[n]]) Now we create for each party its own colorscale. Above all, I focused on the colors of the parties: #Winnerpl_colorscale= [[0.0, ‘rgb(255, 255, 204)’],[0.35, ‘rgb(161, 218, 180)’],[0.5, ‘rgb(65, 182, 196)’],[0.6, ‘rgb(44, 127, 184)’],[0.7, ‘rgb(8, 104, 172)’],[1.0, ‘rgb(37, 52, 148)’]]#CDUcdu_colorscale= [[0.0, ‘rgb(224, 224, 224)’],[0.35, ‘rgb(192, 192, 192)’],[0.5, ‘rgb(160, 160, 160)’],[0.6, ‘rgb(128, 128, 128)’],[0.7, ‘rgb(96, 96, 96)’],[1.0, ‘rgb(64, 64, 64)’]]#SPDspd_colorscale= [[0.0, ‘rgb(255, 153, 153)’],[0.35, ‘rgb(255, 102, 102)’],[0.5, ‘rgb(255, 51, 51)’],[0.6, ‘rgb(255, 0, 0)’],[0.7, ‘rgb(204, 0, 0)’],[1.0, ‘rgb(153, 0, 0)’]]#Die Grünengruene_colorscale= [[0.0, ‘rgb(153, 255, 204)’],[0.35, ‘rgb(102, 255, 178)’],[0.5, ‘rgb(51, 255, 153)’],[0.6, ‘rgb(0, 255, 128)’],[0.7, ‘rgb(0, 204, 102)’],[1.0, ‘rgb(0, 153, 76)’]]#Die Linkelinke_colorscale= [[0.0, ‘rgb(255, 153, 204)’],[0.35, ‘rgb(255, 102, 178)’],[0.5, ‘rgb(255, 51, 153)’],[0.6, ‘rgb(255, 0, 128)’],[0.7, ‘rgb(204, 0, 102)’],[1.0, ‘rgb(153, 0, 76)’]]#AFDafd_colorscale= [[0.0, ‘rgb(153, 255, 255)’],[0.35, ‘rgb(102, 255, 255)’],[0.5, ‘rgb(51, 255, 255)’],[0.6, ‘rgb(0, 255, 255)’],[0.7, ‘rgb(0, 204, 204)’],[1.0, ‘rgb(0, 153, 153)’]]#FDPfdp_colorscale=[[0.0, ‘rgb(255, 255, 204)’],[0.35, ‘rgb(255, 255, 153)’],[0.5, ‘rgb(255, 255, 102)’],[0.6, ‘rgb(255, 255, 51)’],[0.7, ‘rgb(255, 255, 0)’],[1.0, ‘rgb(204, 204, 0)’]] The following function I have taken from a tutorial, which is highly recommended: Now we use this function for our previously created mini- and max-dictionaries to create the individual colorscales: We want to identify the respective election winner on one card and the individual parties on the other. For this we adapt the mouseover texts: text_win=[c+’<br>Election winner was the ‘+ w + ‘ with ‘ + ‘{:0.2f}’.format(r)+’%’ for c, r, w in zip(counties, dct[rate_list[0]], wahlsieger_c)]text_cdu=[c+’<br>The CDU had ‘ + ‘{:0.2f}’.format(r)+’%’ for c, r in zip(counties, dct[rate_list[1]])]text_spd=[c+’<br>The SPD had ‘ + ‘{:0.2f}’.format(r)+’%’ for c, r in zip(counties, dct[rate_list[2]])]text_linke=[c+’<br>The Linke had ‘ + ‘{:0.2f}’.format(r)+’%’ for c, r in zip(counties, dct[rate_list[3]])]text_gruene=[c+’<br>The Grünen had ‘ + ‘{:0.2f}’.format(r)+’%’ for c, r in zip(counties, dct[rate_list[4]])]text_afd=[c+’<br>The AfD had ‘ + ‘{:0.2f}’.format(r)+’%’ for c, r in zip(counties, dct[rate_list[5]])]text_fdp=[c+’<br>The FDP had ‘ + ‘{:0.2f}’.format(r)+’%’ for c, r in zip(counties, dct[rate_list[6]])] For Plotly we must now note the following. The data includes the geodata to represent the shapes for the districts, and the mouseover texts. But we want flexible colorscales depending on the selection in the dropdown menu and relative strength of a party in each district. These colorscales are represented by the layer. The data can be assigned to a list. Depending on the selection of the dropdown, we set the visibility for individual elements from the list to True or False. For example, if we have a list of three records and want to render the first one, we give a list of the entries [True,False,False] as an argument for visible. We first create the data list. We extract the longitude and latitude elements for each district and add them to a list: The layers are also collected in a list: Now we add the drop down menu. First, we will complete the labels for the entries and the respective Visible conditions. Finally, we submit the data and layer lists: In the visible list, we define which element of the data list is displayed. In order for the colorscales to adapt accordingly, we must also define our layers list under "mapbox.layers" . If we put everything together we have the following code: If you want to run the code, you need to modify the mapbox_access_token in line 10. Your result should look like this: It’s very easy to process GeoJSON- and JSON-formats with Python. With Plotly you can create beautiful Choropleth maps from the geo information. It does get a bit trickier if you want to add interactivity using a dropdown, as you need individual colorscales for each layer. However, the args provides the needed flexibility. In a next step, it would still be nice to add an individual colorbar legend. In addition, it would be interesting to illustrate even more socio-demographic characteristics. So be creative! Notebook:https://github.com/bd317/geodata/blob/master/API-Duesseldorf-Github%20(1).ipynb General documentation for choropleth Plotly maps: https://plot.ly/python/choropleth-maps/ A great notebook by empet as introduction to Plotly choropleth maps: plot.ly An update of the same user for the new Plotly trace-type choroplethmapbox: plot.ly If you enjoy Medium and Towards Data Science and didn’t sign up yet, feel free to use my referral link to join the community.
[ { "code": null, "e": 499, "s": 172, "text": "Recently, I wanted to visualize data from the last federal election. I live in Duesseldorf, Germany and wanted to know in which districts which party had relative strengths.Surprisingly, it was a little harder than expected. Therefore I would like to share my experiences here. We will go through the following steps together:" }, { "code": null, "e": 735, "s": 499, "text": "0. Preparation1. Reading Data Over An Api In GeoJSON- And JSON-Format2. Extracting The Relevant Features From The GeoJSON-Data3. Customizing Our Map With Colorscales and Mouseovers4. Putting Everything Together And Adding Interactivity" }, { "code": null, "e": 954, "s": 735, "text": "You can follow this tutorial with your own dataset to create your individual map. The easiest way to do this would be to have the data in GeoJSON or JSON format. Here you can take a look at the data from this tutorial:" }, { "code": null, "e": 1068, "s": 954, "text": "https://opendata.duesseldorf.de/api/action/datastore/search.json?resource_id=6893a12e-3d75-4b2f-bb8b-708982bea7b7" }, { "code": null, "e": 1150, "s": 1068, "text": "https://opendata.duesseldorf.de/sites/default/files/Stadtteile_WGS84_4326.geojson" }, { "code": null, "e": 1464, "s": 1150, "text": "You also need a mapbox account for this tutorial. Mapbox provides a flexible geodata API. Using the Mapbox API, we can map our individual data to a scalable world map. You can create an account at www.mapbox.com. You need a individual token to use the mapbox services which be be found under the account settings:" }, { "code": null, "e": 1758, "s": 1464, "text": "GeoJSON is open standard format for geographical features. Within this standard, storage of data follows a particular structure. Features can be points, lines, polygons or even combinations of the three types. For example, a polygon, a closed area inside a specific room, might look like this:" }, { "code": null, "e": 1887, "s": 1758, "text": "{\"type\": \"Polygon\",\"coordinates\": [[[35, 10], [45, 45], [15, 40], [10, 20], [35, 10]],[[20, 30], [35, 35], [30, 20], [20, 30]]]}" }, { "code": null, "e": 2147, "s": 1887, "text": "In our example, we will also access GeoJSON data and combine it with JSON data. On the website https://opendate.duesseldorf.de there are both geodata and election data for the districts in Dusseldorf. However, the data is separated and we must merge it later." }, { "code": null, "e": 2189, "s": 2147, "text": "First, we import all necessary libraries:" }, { "code": null, "e": 2269, "s": 2189, "text": "import pandas as pdimport numpy as npimport urllib.request, jsonimport requests" }, { "code": null, "e": 2312, "s": 2269, "text": "Now we can read the contents for the URLs:" }, { "code": null, "e": 2636, "s": 2312, "text": "url_wahl_2017 = 'https://opendata.duesseldorf.de/api/action/datastore/search.json?resource_id=6893a12e-3d75-4b2f-bb8b-708982bea7b7'url_stadtteile = 'https://opendata.duesseldorf.de/sites/default/files/Stadtteile_WGS84_4326.geojson'geo_data = requests.get(url_stadtteile).json()data_wahl = requests.get(url_wahl_2017).json()" }, { "code": null, "e": 2799, "s": 2636, "text": "Both data sources are now available as a nested dictionary. With data_wahl['result']['records'] the election results of the individual districts can be displayed:" }, { "code": null, "e": 2889, "s": 2799, "text": "We can now import the relevant election data from the dictionary into a pandas dataframe:" }, { "code": null, "e": 2954, "s": 2889, "text": "df_wahl = pd.DataFrame.from_dict(data_wahl['result']['records'])" }, { "code": null, "e": 3084, "s": 2954, "text": "Now let’s look at the geodata. For further processing with Plotly, we now extract the relevant features from the geodata request:" }, { "code": null, "e": 3177, "s": 3084, "text": "sources=[{\"type\": \"FeatureCollection\", 'features': [feat]} for feat in geo_data['features']]" }, { "code": null, "e": 3408, "s": 3177, "text": "The list sources contains the coordinates for all parts of the city. We will later hand over this list to the Mapbox object in order to present the respective districts.The IDs of the districts are also extracted from the geodata:" }, { "code": null, "e": 3510, "s": 3408, "text": "tx_ids=[geo_data['features'][k]['properties']['Stadtteil'] for k in range(len(geo_data['features']))]" }, { "code": null, "e": 3602, "s": 3510, "text": "We need the IDs later to allocate the correct colorscales for each party and each district." }, { "code": null, "e": 3924, "s": 3602, "text": "In order to be able to dynamically color the individual parts of the city later on, we need the range of the respective percentages for each party. The lightest shade is assigned the lowest value and the highest value the darkest shade. For this we determine for each party and each district the lowest and highest value:" }, { "code": null, "e": 4229, "s": 3924, "text": "parties = ['Wahlsieger_proz','CDU_Proz','SPD_Proz','DIE LINKE_Proz','GRÜNE_Proz','AfD_Proz','FDP_Proz']for n in range(0,len(rate_list)):dct[rate_list[n]] = [df.loc[stadtteil, parties[n]] for stadtteil in tx_ids]dct_min[mins_list[n]] = min(dct[rate_list[n]])dct_max[maxs_list[n]] = max(dct[rate_list[n]])" }, { "code": null, "e": 4329, "s": 4229, "text": "Now we create for each party its own colorscale. Above all, I focused on the colors of the parties:" }, { "code": null, "e": 5626, "s": 4329, "text": "#Winnerpl_colorscale= [[0.0, ‘rgb(255, 255, 204)’],[0.35, ‘rgb(161, 218, 180)’],[0.5, ‘rgb(65, 182, 196)’],[0.6, ‘rgb(44, 127, 184)’],[0.7, ‘rgb(8, 104, 172)’],[1.0, ‘rgb(37, 52, 148)’]]#CDUcdu_colorscale= [[0.0, ‘rgb(224, 224, 224)’],[0.35, ‘rgb(192, 192, 192)’],[0.5, ‘rgb(160, 160, 160)’],[0.6, ‘rgb(128, 128, 128)’],[0.7, ‘rgb(96, 96, 96)’],[1.0, ‘rgb(64, 64, 64)’]]#SPDspd_colorscale= [[0.0, ‘rgb(255, 153, 153)’],[0.35, ‘rgb(255, 102, 102)’],[0.5, ‘rgb(255, 51, 51)’],[0.6, ‘rgb(255, 0, 0)’],[0.7, ‘rgb(204, 0, 0)’],[1.0, ‘rgb(153, 0, 0)’]]#Die Grünengruene_colorscale= [[0.0, ‘rgb(153, 255, 204)’],[0.35, ‘rgb(102, 255, 178)’],[0.5, ‘rgb(51, 255, 153)’],[0.6, ‘rgb(0, 255, 128)’],[0.7, ‘rgb(0, 204, 102)’],[1.0, ‘rgb(0, 153, 76)’]]#Die Linkelinke_colorscale= [[0.0, ‘rgb(255, 153, 204)’],[0.35, ‘rgb(255, 102, 178)’],[0.5, ‘rgb(255, 51, 153)’],[0.6, ‘rgb(255, 0, 128)’],[0.7, ‘rgb(204, 0, 102)’],[1.0, ‘rgb(153, 0, 76)’]]#AFDafd_colorscale= [[0.0, ‘rgb(153, 255, 255)’],[0.35, ‘rgb(102, 255, 255)’],[0.5, ‘rgb(51, 255, 255)’],[0.6, ‘rgb(0, 255, 255)’],[0.7, ‘rgb(0, 204, 204)’],[1.0, ‘rgb(0, 153, 153)’]]#FDPfdp_colorscale=[[0.0, ‘rgb(255, 255, 204)’],[0.35, ‘rgb(255, 255, 153)’],[0.5, ‘rgb(255, 255, 102)’],[0.6, ‘rgb(255, 255, 51)’],[0.7, ‘rgb(255, 255, 0)’],[1.0, ‘rgb(204, 204, 0)’]]" }, { "code": null, "e": 5708, "s": 5626, "text": "The following function I have taken from a tutorial, which is highly recommended:" }, { "code": null, "e": 5825, "s": 5708, "text": "Now we use this function for our previously created mini- and max-dictionaries to create the individual colorscales:" }, { "code": null, "e": 5968, "s": 5825, "text": "We want to identify the respective election winner on one card and the individual parties on the other. For this we adapt the mouseover texts:" }, { "code": null, "e": 6737, "s": 5968, "text": "text_win=[c+’<br>Election winner was the ‘+ w + ‘ with ‘ + ‘{:0.2f}’.format(r)+’%’ for c, r, w in zip(counties, dct[rate_list[0]], wahlsieger_c)]text_cdu=[c+’<br>The CDU had ‘ + ‘{:0.2f}’.format(r)+’%’ for c, r in zip(counties, dct[rate_list[1]])]text_spd=[c+’<br>The SPD had ‘ + ‘{:0.2f}’.format(r)+’%’ for c, r in zip(counties, dct[rate_list[2]])]text_linke=[c+’<br>The Linke had ‘ + ‘{:0.2f}’.format(r)+’%’ for c, r in zip(counties, dct[rate_list[3]])]text_gruene=[c+’<br>The Grünen had ‘ + ‘{:0.2f}’.format(r)+’%’ for c, r in zip(counties, dct[rate_list[4]])]text_afd=[c+’<br>The AfD had ‘ + ‘{:0.2f}’.format(r)+’%’ for c, r in zip(counties, dct[rate_list[5]])]text_fdp=[c+’<br>The FDP had ‘ + ‘{:0.2f}’.format(r)+’%’ for c, r in zip(counties, dct[rate_list[6]])]" }, { "code": null, "e": 7375, "s": 6737, "text": "For Plotly we must now note the following. The data includes the geodata to represent the shapes for the districts, and the mouseover texts. But we want flexible colorscales depending on the selection in the dropdown menu and relative strength of a party in each district. These colorscales are represented by the layer. The data can be assigned to a list. Depending on the selection of the dropdown, we set the visibility for individual elements from the list to True or False. For example, if we have a list of three records and want to render the first one, we give a list of the entries [True,False,False] as an argument for visible." }, { "code": null, "e": 7495, "s": 7375, "text": "We first create the data list. We extract the longitude and latitude elements for each district and add them to a list:" }, { "code": null, "e": 7536, "s": 7495, "text": "The layers are also collected in a list:" }, { "code": null, "e": 7702, "s": 7536, "text": "Now we add the drop down menu. First, we will complete the labels for the entries and the respective Visible conditions. Finally, we submit the data and layer lists:" }, { "code": null, "e": 7889, "s": 7702, "text": "In the visible list, we define which element of the data list is displayed. In order for the colorscales to adapt accordingly, we must also define our layers list under \"mapbox.layers\" ." }, { "code": null, "e": 7947, "s": 7889, "text": "If we put everything together we have the following code:" }, { "code": null, "e": 8031, "s": 7947, "text": "If you want to run the code, you need to modify the mapbox_access_token in line 10." }, { "code": null, "e": 8066, "s": 8031, "text": "Your result should look like this:" }, { "code": null, "e": 8579, "s": 8066, "text": "It’s very easy to process GeoJSON- and JSON-formats with Python. With Plotly you can create beautiful Choropleth maps from the geo information. It does get a bit trickier if you want to add interactivity using a dropdown, as you need individual colorscales for each layer. However, the args provides the needed flexibility. In a next step, it would still be nice to add an individual colorbar legend. In addition, it would be interesting to illustrate even more socio-demographic characteristics. So be creative!" }, { "code": null, "e": 8668, "s": 8579, "text": "Notebook:https://github.com/bd317/geodata/blob/master/API-Duesseldorf-Github%20(1).ipynb" }, { "code": null, "e": 8718, "s": 8668, "text": "General documentation for choropleth Plotly maps:" }, { "code": null, "e": 8758, "s": 8718, "text": "https://plot.ly/python/choropleth-maps/" }, { "code": null, "e": 8827, "s": 8758, "text": "A great notebook by empet as introduction to Plotly choropleth maps:" }, { "code": null, "e": 8835, "s": 8827, "text": "plot.ly" }, { "code": null, "e": 8910, "s": 8835, "text": "An update of the same user for the new Plotly trace-type choroplethmapbox:" }, { "code": null, "e": 8918, "s": 8910, "text": "plot.ly" } ]
Do Not Use Print For Debugging In Python Anymore | by Christopher Tao | Towards Data Science
What is the most frequently used function in Python? Well, probably in most of the programming languages, it has to be the print() function. I believe most of the developers like me, would use it to print messages into the console many times during the development. Of course, there is no alternative that can completely replace the print() function. However, when we want to output something for debugging purposes, there are definitely better ways of doing so. In this article, I’m going to introduce a very interesting 3rd party library in Python called “Ice Cream”. It could create lots of conveniences for quick and easy debugging. Let’s start with a relatively bad example. Suppose we have defined a function and we want to see whether it works as expected. def square_of(num): return num*num This function simply returns the square of the number passed in as an argument. We may want to test it multiple times as follows. print(square_of(2))print(square_of(3))print(square_of(4)) This is OK for now. However, we will have much more lines of code in practice. Also, there could be many print() functions that print different things into the output area. In this case, sometimes we may be confused about which output is generated by which print() function. Therefore, it is a good manner to add some brief description to the content of the print() function to remind us what it is about. print('square of 2:', square_of(2))print('square of 3:', square_of(3))print('square of 4:', square_of(4)) It is much better now, but it is too tiring to do this every time. Also, when we finish the development, very likely have to remove most of the debugging prints. Let’s have a look at the Ice Cream library. How it solves the problems that were mentioned above? First of all, we need to install it from the PyPI repository simply using pip. pip install icecream Then, let’s import the library as follows. from icecream import ic Now, we can use it for everything we want to print as debug information. We can directly use ice cream to print a function just like what we have done using the print() function previously. ic(square_of(2))ic(square_of(3))ic(square_of(4)) Great! We never specify anything in the ic() function, but it automatically outputs the function name and argument together with the outcome. So, we don’t have to manually add the “brief description” anymore. Not only calling a function, but Ice Cream can also output everything verbose that is convenient for debugging purpose, such as accessing a key-value pair of a dictionary. my_dict = { 'name': 'Chris', 'age': 33}ic(my_dict['name']) In this example, I have defined a dictionary and try to access a value in it from its key. The Ice Cream output both the variable name of the dictionary and the key that I was accessing. One more example, let’s define a class and instantiate an object from it. class Dog(): num_legs = 4 tail = Truedog = Dog() Now, let’s use Ice Cream to output an attribute of it. ic(dog.tail) The Ice Cream library is not only useful for inspecting a variable, but also in a control statement such as an if-condition. For example, let’s write a simple if-else condition as follows. input = 'Chris'if input == 'Chris': ic()else: ic() We just put the Ice Cream function in the if and else blocks, see what happen. Although the if-else statement does nothing at the moment, the ic() function still tells us where and when it has been called, as well as the line number. BTW, I’m using Python Notebooks for this demo. If this is running in a “.py” file, it will also tell us the file name that it was called from. Let’s consider a more practical usage as follows. def check_user(username): if username == 'Chris': # do something ic() else: # do something else ic()check_user('Chris')check_user('Jade') The function will do something for different user. For debugging purposes, we always want to know which is the current user. Then, the ic() function will always tell us that. This cool feature of the Ice Cream library needs to be highlighted in my opinion. That is, the ic() function will not only output the verbose information but also pass the value through so that it can be a wrap of anything. In other words, we can put the ic() function to anything in our code without affecting it. Let’s keep using the sqaure_of() function that we defined in the previous section. num = 2square_of_num = square_of(ic(num)) In this example, suppose we have a variable num and we want to calculate its square. Instead of square_of(num), I put the ic() function out of the variable num. Therefore, the value of the variable num is printed, and the result assigned to square_of_num will not be affected. We can test the result as follows. if ic(square_of_num) == pow(num, 2): ic('Correct!') Therefore, square_of_num equals to the square of the variable num. Also, in this if-condition, I also used the ic() function without affecting the purpose, but the variable square_of_num is printed for debugging! One of the biggest issue when using the print() function for debugging is that there are too many of them. It is very common that we have them everywhere when we finished the development. Then, it would be a disaster if we want to clean our code to remove them. If we’re using the Ice Cream library for debugging, what we need to do is simply disable it. ic.disable() After that, all the ic() function will stop output anything. For example, the code below will output nothing. You may ask that how about the variable square_of_num? Will it still be passed through if we disabled the Ice Cream function? Don’t worry, the disabling feature will only disable the output, we don’t need to worry about any other features. if ic(square_of_num) == pow(num, 2): print('Correct!') If we change the output back to the print() function, it still can be output. That means the ic(square_of_num) still equivalent to square_of_num. Of course, if we want to go back to the debug mode, the Ice Cream can be re-enabled. ic.enable() The Ice Cream can also be customised for its output. The most commonly used customisation would be changing the prefix. You may have noticed that the default output always has the prefix ic | . Yes, we can customise it. For example, we can change it to Debug | which makes more sense for its debugging purpose. ic.configureOutput(prefix='Debug | ')ic('test') In fact, rather than a static string, the prefix can also be set to a function. For example, let’s define a function that returns the current timestamp in a formatted string. from datetime import datetimedef now(): return f'[{datetime.now()}] ' Then, we can set that function as the Ice Cream prefix. ic.configureOutput(prefix=now)ic('test') In this article, I have introduced an awesome 3rd party library for Python called “Ice Cream”. It enhanced the regular print() function of Python with verbose output. Therefore, it makes debugging very convenient. The Ice Cream library will never replace the print() function, because it is designed for debugging purposes. Also, it does not mean to replace the logging system as well. In my opinion, it is in between these two. Check out and try it out! medium.com If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
[ { "code": null, "e": 438, "s": 172, "text": "What is the most frequently used function in Python? Well, probably in most of the programming languages, it has to be the print() function. I believe most of the developers like me, would use it to print messages into the console many times during the development." }, { "code": null, "e": 809, "s": 438, "text": "Of course, there is no alternative that can completely replace the print() function. However, when we want to output something for debugging purposes, there are definitely better ways of doing so. In this article, I’m going to introduce a very interesting 3rd party library in Python called “Ice Cream”. It could create lots of conveniences for quick and easy debugging." }, { "code": null, "e": 936, "s": 809, "text": "Let’s start with a relatively bad example. Suppose we have defined a function and we want to see whether it works as expected." }, { "code": null, "e": 974, "s": 936, "text": "def square_of(num): return num*num" }, { "code": null, "e": 1104, "s": 974, "text": "This function simply returns the square of the number passed in as an argument. We may want to test it multiple times as follows." }, { "code": null, "e": 1162, "s": 1104, "text": "print(square_of(2))print(square_of(3))print(square_of(4))" }, { "code": null, "e": 1437, "s": 1162, "text": "This is OK for now. However, we will have much more lines of code in practice. Also, there could be many print() functions that print different things into the output area. In this case, sometimes we may be confused about which output is generated by which print() function." }, { "code": null, "e": 1568, "s": 1437, "text": "Therefore, it is a good manner to add some brief description to the content of the print() function to remind us what it is about." }, { "code": null, "e": 1674, "s": 1568, "text": "print('square of 2:', square_of(2))print('square of 3:', square_of(3))print('square of 4:', square_of(4))" }, { "code": null, "e": 1836, "s": 1674, "text": "It is much better now, but it is too tiring to do this every time. Also, when we finish the development, very likely have to remove most of the debugging prints." }, { "code": null, "e": 1934, "s": 1836, "text": "Let’s have a look at the Ice Cream library. How it solves the problems that were mentioned above?" }, { "code": null, "e": 2013, "s": 1934, "text": "First of all, we need to install it from the PyPI repository simply using pip." }, { "code": null, "e": 2034, "s": 2013, "text": "pip install icecream" }, { "code": null, "e": 2077, "s": 2034, "text": "Then, let’s import the library as follows." }, { "code": null, "e": 2101, "s": 2077, "text": "from icecream import ic" }, { "code": null, "e": 2174, "s": 2101, "text": "Now, we can use it for everything we want to print as debug information." }, { "code": null, "e": 2291, "s": 2174, "text": "We can directly use ice cream to print a function just like what we have done using the print() function previously." }, { "code": null, "e": 2340, "s": 2291, "text": "ic(square_of(2))ic(square_of(3))ic(square_of(4))" }, { "code": null, "e": 2549, "s": 2340, "text": "Great! We never specify anything in the ic() function, but it automatically outputs the function name and argument together with the outcome. So, we don’t have to manually add the “brief description” anymore." }, { "code": null, "e": 2721, "s": 2549, "text": "Not only calling a function, but Ice Cream can also output everything verbose that is convenient for debugging purpose, such as accessing a key-value pair of a dictionary." }, { "code": null, "e": 2786, "s": 2721, "text": "my_dict = { 'name': 'Chris', 'age': 33}ic(my_dict['name'])" }, { "code": null, "e": 2973, "s": 2786, "text": "In this example, I have defined a dictionary and try to access a value in it from its key. The Ice Cream output both the variable name of the dictionary and the key that I was accessing." }, { "code": null, "e": 3047, "s": 2973, "text": "One more example, let’s define a class and instantiate an object from it." }, { "code": null, "e": 3102, "s": 3047, "text": "class Dog(): num_legs = 4 tail = Truedog = Dog()" }, { "code": null, "e": 3157, "s": 3102, "text": "Now, let’s use Ice Cream to output an attribute of it." }, { "code": null, "e": 3170, "s": 3157, "text": "ic(dog.tail)" }, { "code": null, "e": 3359, "s": 3170, "text": "The Ice Cream library is not only useful for inspecting a variable, but also in a control statement such as an if-condition. For example, let’s write a simple if-else condition as follows." }, { "code": null, "e": 3416, "s": 3359, "text": "input = 'Chris'if input == 'Chris': ic()else: ic()" }, { "code": null, "e": 3495, "s": 3416, "text": "We just put the Ice Cream function in the if and else blocks, see what happen." }, { "code": null, "e": 3650, "s": 3495, "text": "Although the if-else statement does nothing at the moment, the ic() function still tells us where and when it has been called, as well as the line number." }, { "code": null, "e": 3793, "s": 3650, "text": "BTW, I’m using Python Notebooks for this demo. If this is running in a “.py” file, it will also tell us the file name that it was called from." }, { "code": null, "e": 3843, "s": 3793, "text": "Let’s consider a more practical usage as follows." }, { "code": null, "e": 4015, "s": 3843, "text": "def check_user(username): if username == 'Chris': # do something ic() else: # do something else ic()check_user('Chris')check_user('Jade')" }, { "code": null, "e": 4190, "s": 4015, "text": "The function will do something for different user. For debugging purposes, we always want to know which is the current user. Then, the ic() function will always tell us that." }, { "code": null, "e": 4505, "s": 4190, "text": "This cool feature of the Ice Cream library needs to be highlighted in my opinion. That is, the ic() function will not only output the verbose information but also pass the value through so that it can be a wrap of anything. In other words, we can put the ic() function to anything in our code without affecting it." }, { "code": null, "e": 4588, "s": 4505, "text": "Let’s keep using the sqaure_of() function that we defined in the previous section." }, { "code": null, "e": 4630, "s": 4588, "text": "num = 2square_of_num = square_of(ic(num))" }, { "code": null, "e": 4907, "s": 4630, "text": "In this example, suppose we have a variable num and we want to calculate its square. Instead of square_of(num), I put the ic() function out of the variable num. Therefore, the value of the variable num is printed, and the result assigned to square_of_num will not be affected." }, { "code": null, "e": 4942, "s": 4907, "text": "We can test the result as follows." }, { "code": null, "e": 4997, "s": 4942, "text": "if ic(square_of_num) == pow(num, 2): ic('Correct!')" }, { "code": null, "e": 5210, "s": 4997, "text": "Therefore, square_of_num equals to the square of the variable num. Also, in this if-condition, I also used the ic() function without affecting the purpose, but the variable square_of_num is printed for debugging!" }, { "code": null, "e": 5472, "s": 5210, "text": "One of the biggest issue when using the print() function for debugging is that there are too many of them. It is very common that we have them everywhere when we finished the development. Then, it would be a disaster if we want to clean our code to remove them." }, { "code": null, "e": 5565, "s": 5472, "text": "If we’re using the Ice Cream library for debugging, what we need to do is simply disable it." }, { "code": null, "e": 5578, "s": 5565, "text": "ic.disable()" }, { "code": null, "e": 5688, "s": 5578, "text": "After that, all the ic() function will stop output anything. For example, the code below will output nothing." }, { "code": null, "e": 5928, "s": 5688, "text": "You may ask that how about the variable square_of_num? Will it still be passed through if we disabled the Ice Cream function? Don’t worry, the disabling feature will only disable the output, we don’t need to worry about any other features." }, { "code": null, "e": 5986, "s": 5928, "text": "if ic(square_of_num) == pow(num, 2): print('Correct!')" }, { "code": null, "e": 6132, "s": 5986, "text": "If we change the output back to the print() function, it still can be output. That means the ic(square_of_num) still equivalent to square_of_num." }, { "code": null, "e": 6217, "s": 6132, "text": "Of course, if we want to go back to the debug mode, the Ice Cream can be re-enabled." }, { "code": null, "e": 6229, "s": 6217, "text": "ic.enable()" }, { "code": null, "e": 6449, "s": 6229, "text": "The Ice Cream can also be customised for its output. The most commonly used customisation would be changing the prefix. You may have noticed that the default output always has the prefix ic | . Yes, we can customise it." }, { "code": null, "e": 6540, "s": 6449, "text": "For example, we can change it to Debug | which makes more sense for its debugging purpose." }, { "code": null, "e": 6588, "s": 6540, "text": "ic.configureOutput(prefix='Debug | ')ic('test')" }, { "code": null, "e": 6763, "s": 6588, "text": "In fact, rather than a static string, the prefix can also be set to a function. For example, let’s define a function that returns the current timestamp in a formatted string." }, { "code": null, "e": 6836, "s": 6763, "text": "from datetime import datetimedef now(): return f'[{datetime.now()}] '" }, { "code": null, "e": 6892, "s": 6836, "text": "Then, we can set that function as the Ice Cream prefix." }, { "code": null, "e": 6933, "s": 6892, "text": "ic.configureOutput(prefix=now)ic('test')" }, { "code": null, "e": 7147, "s": 6933, "text": "In this article, I have introduced an awesome 3rd party library for Python called “Ice Cream”. It enhanced the regular print() function of Python with verbose output. Therefore, it makes debugging very convenient." }, { "code": null, "e": 7388, "s": 7147, "text": "The Ice Cream library will never replace the print() function, because it is designed for debugging purposes. Also, it does not mean to replace the logging system as well. In my opinion, it is in between these two. Check out and try it out!" }, { "code": null, "e": 7399, "s": 7388, "text": "medium.com" } ]
Find the number of positive integers less than or equal to N that have an odd number of digits - GeeksforGeeks
10 May, 2021 Given an integer N where 1 ≤ N ≤ 105, the task is to find the number of positive integers less than or equal to N that have an odd number of digits without leading zeros.Examples: Input: N = 11 Output: 9 1, 2, 3, ..., 8 and 9 are the numbers ≤ 11 with odd number of digits.Input: N = 893 Output: 803 Naive approach: Traverse from 1 to N and for each number check if it contains odd digits or not.Efficient approach: For the values: When N < 10 then the count of valid numbers will be N. When N / 10 < 10 then 9. When N / 100 < 10 then 9 + N – 99. When N / 1000 < 10 then 9 + 900. When N / 10000 < 10 then 909 + N – 9999. Otherwise 90909. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of// positive integers less than or equal// to N that have odd number of digitsint odd_digits(int n){ if (n < 10) return n; else if (n / 10 < 10) return 9; else if (n / 100 < 10) return 9 + n - 99; else if (n / 1000 < 10) return 9 + 900; else if (n / 10000 < 10) return 909 + n - 9999; else return 90909;} // Driver codeint main(){ int n = 893; cout << odd_digits(n); return 0;} // Java implementation of the approachclass GFG{ // Function to return the number of// positive integers less than or equal// to N that have odd number of digitsstatic int odd_digits(int n){ if (n < 10) return n; else if (n / 10 < 10) return 9; else if (n / 100 < 10) return 9 + n - 99; else if (n / 1000 < 10) return 9 + 900; else if (n / 10000 < 10) return 909 + n - 9999; else return 90909;} // Driver codepublic static void main(String []args){ int n = 893; System.out.println(odd_digits(n));}} // This code is contributed by 29AjayKumar # Python3 implementation of the approach # Function to return the number of# positive integers less than or equal# to N that have odd number of digitsdef odd_digits(n) : if (n < 10) : return n; elif (n / 10 < 10) : return 9; elif (n / 100 < 10) : return 9 + n - 99; elif (n / 1000 < 10) : return 9 + 900; elif (n / 10000 < 10) : return 909 + n - 9999; else : return 90909; # Driver codeif __name__ == "__main__" : n = 893; print(odd_digits(n)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ // Function to return the number of// positive integers less than or equal// to N that have odd number of digitsstatic int odd_digits(int n){ if (n < 10) return n; else if (n / 10 < 10) return 9; else if (n / 100 < 10) return 9 + n - 99; else if (n / 1000 < 10) return 9 + 900; else if (n / 10000 < 10) return 909 + n - 9999; else return 90909;} // Driver codepublic static void Main(String []args){ int n = 893; Console.WriteLine(odd_digits(n));}} // This code is contributed by 29AjayKumar <script>// Java script implementation of the approach // Function to return the number of// positive integers less than or equal// to N that have odd number of digitsfunction odd_digits( n){ if (n < 10) return n; else if (n / 10 < 10) return 9; else if (n / 100 < 10) return 9 + n - 99; else if (n / 1000 < 10) return 9 + 900; else if (n / 10000 < 10) return 909 + n - 9999; else return 90909;} // Driver codelet n = 893; document.write(odd_digits(n)); // This code is contributed by sravan kumar Gottumukkala</script> 803 ankthon 29AjayKumar sravankumar8128 Constructive Algorithms number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Fizz Buzz Implementation Program to multiply two matrices Program to add two binary strings Find Union and Intersection of two unsorted arrays Count ways to reach the n'th stair Add two numbers without using arithmetic operators Program to convert a given number to words
[ { "code": null, "e": 24326, "s": 24298, "text": "\n10 May, 2021" }, { "code": null, "e": 24508, "s": 24326, "text": "Given an integer N where 1 ≤ N ≤ 105, the task is to find the number of positive integers less than or equal to N that have an odd number of digits without leading zeros.Examples: " }, { "code": null, "e": 24630, "s": 24508, "text": "Input: N = 11 Output: 9 1, 2, 3, ..., 8 and 9 are the numbers ≤ 11 with odd number of digits.Input: N = 893 Output: 803 " }, { "code": null, "e": 24766, "s": 24632, "text": "Naive approach: Traverse from 1 to N and for each number check if it contains odd digits or not.Efficient approach: For the values: " }, { "code": null, "e": 24821, "s": 24766, "text": "When N < 10 then the count of valid numbers will be N." }, { "code": null, "e": 24846, "s": 24821, "text": "When N / 10 < 10 then 9." }, { "code": null, "e": 24881, "s": 24846, "text": "When N / 100 < 10 then 9 + N – 99." }, { "code": null, "e": 24914, "s": 24881, "text": "When N / 1000 < 10 then 9 + 900." }, { "code": null, "e": 24955, "s": 24914, "text": "When N / 10000 < 10 then 909 + N – 9999." }, { "code": null, "e": 24972, "s": 24955, "text": "Otherwise 90909." }, { "code": null, "e": 25025, "s": 24972, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25029, "s": 25025, "text": "C++" }, { "code": null, "e": 25034, "s": 25029, "text": "Java" }, { "code": null, "e": 25042, "s": 25034, "text": "Python3" }, { "code": null, "e": 25045, "s": 25042, "text": "C#" }, { "code": null, "e": 25056, "s": 25045, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of// positive integers less than or equal// to N that have odd number of digitsint odd_digits(int n){ if (n < 10) return n; else if (n / 10 < 10) return 9; else if (n / 100 < 10) return 9 + n - 99; else if (n / 1000 < 10) return 9 + 900; else if (n / 10000 < 10) return 909 + n - 9999; else return 90909;} // Driver codeint main(){ int n = 893; cout << odd_digits(n); return 0;}", "e": 25621, "s": 25056, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the number of// positive integers less than or equal// to N that have odd number of digitsstatic int odd_digits(int n){ if (n < 10) return n; else if (n / 10 < 10) return 9; else if (n / 100 < 10) return 9 + n - 99; else if (n / 1000 < 10) return 9 + 900; else if (n / 10000 < 10) return 909 + n - 9999; else return 90909;} // Driver codepublic static void main(String []args){ int n = 893; System.out.println(odd_digits(n));}} // This code is contributed by 29AjayKumar", "e": 26230, "s": 25621, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the number of# positive integers less than or equal# to N that have odd number of digitsdef odd_digits(n) : if (n < 10) : return n; elif (n / 10 < 10) : return 9; elif (n / 100 < 10) : return 9 + n - 99; elif (n / 1000 < 10) : return 9 + 900; elif (n / 10000 < 10) : return 909 + n - 9999; else : return 90909; # Driver codeif __name__ == \"__main__\" : n = 893; print(odd_digits(n)); # This code is contributed by AnkitRai01", "e": 26785, "s": 26230, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the number of// positive integers less than or equal// to N that have odd number of digitsstatic int odd_digits(int n){ if (n < 10) return n; else if (n / 10 < 10) return 9; else if (n / 100 < 10) return 9 + n - 99; else if (n / 1000 < 10) return 9 + 900; else if (n / 10000 < 10) return 909 + n - 9999; else return 90909;} // Driver codepublic static void Main(String []args){ int n = 893; Console.WriteLine(odd_digits(n));}} // This code is contributed by 29AjayKumar", "e": 27425, "s": 26785, "text": null }, { "code": "<script>// Java script implementation of the approach // Function to return the number of// positive integers less than or equal// to N that have odd number of digitsfunction odd_digits( n){ if (n < 10) return n; else if (n / 10 < 10) return 9; else if (n / 100 < 10) return 9 + n - 99; else if (n / 1000 < 10) return 9 + 900; else if (n / 10000 < 10) return 909 + n - 9999; else return 90909;} // Driver codelet n = 893; document.write(odd_digits(n)); // This code is contributed by sravan kumar Gottumukkala</script>", "e": 28010, "s": 27425, "text": null }, { "code": null, "e": 28014, "s": 28010, "text": "803" }, { "code": null, "e": 28024, "s": 28016, "text": "ankthon" }, { "code": null, "e": 28036, "s": 28024, "text": "29AjayKumar" }, { "code": null, "e": 28052, "s": 28036, "text": "sravankumar8128" }, { "code": null, "e": 28076, "s": 28052, "text": "Constructive Algorithms" }, { "code": null, "e": 28090, "s": 28076, "text": "number-digits" }, { "code": null, "e": 28103, "s": 28090, "text": "Mathematical" }, { "code": null, "e": 28116, "s": 28103, "text": "Mathematical" }, { "code": null, "e": 28214, "s": 28116, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28223, "s": 28214, "text": "Comments" }, { "code": null, "e": 28236, "s": 28223, "text": "Old Comments" }, { "code": null, "e": 28281, "s": 28236, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 28313, "s": 28281, "text": "Check if a number is Palindrome" }, { "code": null, "e": 28357, "s": 28313, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 28382, "s": 28357, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 28415, "s": 28382, "text": "Program to multiply two matrices" }, { "code": null, "e": 28449, "s": 28415, "text": "Program to add two binary strings" }, { "code": null, "e": 28500, "s": 28449, "text": "Find Union and Intersection of two unsorted arrays" }, { "code": null, "e": 28535, "s": 28500, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 28586, "s": 28535, "text": "Add two numbers without using arithmetic operators" } ]
SimRank: Similarity Analysis Explanation and Python Implementation from Scratch | by Chonyy | Towards Data Science
Measuring similarity is a problem needed in all kinds of fields. SimRank is an intuitive and general approach in the similarity measure. It is applicable in any domain with object-to-object relationships, measuring the similarity of an object based on the relationship with other objects. The key of SimRank is Two objects are considered to be similar if they are referenced by similar objects. We will briefly introduce the algorithm and walkthrough the Python implementation from scratch. Feel free to check out the well-commented source code. It could really help to understand the whole algorithm. github.com The algorithm steps are listed below Initialize the SimRank of every pair of the nodes following if(node1 == node2): SimRank(node1, node2) = 1else: SimRank(node1, node2) = 0 For each iteration, update the SimRank of every pair of nodes in the graph If both nodes are the same, SimRank(a, b) = 1 If one of the nodes has no in-neighbors, SimRank(a,b) = 0 Else, the new SimRank follows the equation We calculate the new SimRank based on the SimRank from the previous iteration (Defined recursively but computed iteratively) We initialize the SimRank in the Similarity class constructor. Please note that the initial values are stored in old_sim. We retain the new_sim to save the updated SimRank from the next iteration. The initializing rule is just like what we mentioned above. SimRank = 1 if both are the same, else SimRank = 0. This is the SimRank main function. We iterate every pair of nodes in the graph and update the SimRank. After getting all the new SimRank values, we replace the old values with the values from the current iteration. If both nodes are the same, value = 1 If one of the nodes has no in-neighbor, value = 0 SimRank_sum = the sum of SimRank value of all in-neighbor pairs (SimRank value is from the previous iteration) Calculate the scale with decay factor Calculate the new SimRank with SimRank_sum and scale Take the calculated new SimRank value and assign it to new_sim. Replace the value from the previous iteration with the values from the current iteration. https://gist.github.com/9395c9aea14e4086ce2611809084f9a0 Let’s test our implementation on the dataset in the repo. We set decay_factor = 0.9 in all the results. Result The result follows the order of node value, which is 1, 2, 3, 4, 5, 6 on the row and 1, 2, 3, 4, 5, 6 on the column. From the matrix, we could see that the diagonal is always full of 1s. The SimRank of two same nodes is always 1. Recall the SimRank equation explained above, having a common parent or not matters a lot in the calculation. From the graph, we could see that there’s no pair of nodes have a common parent. Thus, all the SimRank is 0. Result Similarly, none of the nodes has a common parent. So the SimRank are all 0. Result From the result matrix, there’s one interesting observation. SimRank[1][3] = SimRank[3][1] Let’s take a look at the pairs that SimRank != 0. (node1, node3), (node2, node4) all have a common parent, and that makes their SimRank not equals to zero. Result Let’s look at pair (node6, node4), (node7, node4). The common node in these two pairs is node4. Node4 has two parents, node1 and node5. Node1 is the only in-neighbor of node7 Node5 is the only in-neighbor of node6 As you can see, this kind of relationship makes them got the same SimRank = 0.695. Result The result follows the node value order, which is 2076, 2564, 4785, 5016, 5793, 6338, 6395, 9484, 9994 in row and column respectively. You might be wondering why (node4785, node5016) has a single and common parent, but the SimRank is not 1. This is why we need the decay factor, to separate the difference between extremely high similarity and totally identical. Now we all knew that after enough iterations, SimRank will always converge to a specific value. Why don’t we plot it out to check how fast it’s converging? Testing the convergence on graph_4.txt There are two important observations here. The first one is that just like how we expected, the value started at 0 and gradually increased to a certain value and stop changing. The second one is that the curve is smoother than the plot we got from HITS or PageRank algorithm. Please note that it may not always take only this few iterations to complete the calculation. For example, if we test this SimRank algorithm on graph_6 in the repo, which has 1228 nodes and 5220 edges, even 500 iteration is not enough for the SimRank to converge. And the computation takes forever long due to a large number of edges. We run 100 iterations with a different number of total edges in order to spot the relation between total edges and computation time. As you can see, the inference of edges number on the computation time is increasing faster than linear. So the calculation will be extremely slow if there are too many edges. Please note that the reason it’s not a perfect curve is the way the edges link to each other will also affect the computation time a little.
[ { "code": null, "e": 460, "s": 171, "text": "Measuring similarity is a problem needed in all kinds of fields. SimRank is an intuitive and general approach in the similarity measure. It is applicable in any domain with object-to-object relationships, measuring the similarity of an object based on the relationship with other objects." }, { "code": null, "e": 482, "s": 460, "text": "The key of SimRank is" }, { "code": null, "e": 566, "s": 482, "text": "Two objects are considered to be similar if they are referenced by similar objects." }, { "code": null, "e": 662, "s": 566, "text": "We will briefly introduce the algorithm and walkthrough the Python implementation from scratch." }, { "code": null, "e": 773, "s": 662, "text": "Feel free to check out the well-commented source code. It could really help to understand the whole algorithm." }, { "code": null, "e": 784, "s": 773, "text": "github.com" }, { "code": null, "e": 821, "s": 784, "text": "The algorithm steps are listed below" }, { "code": null, "e": 881, "s": 821, "text": "Initialize the SimRank of every pair of the nodes following" }, { "code": null, "e": 960, "s": 881, "text": "if(node1 == node2): SimRank(node1, node2) = 1else: SimRank(node1, node2) = 0" }, { "code": null, "e": 1035, "s": 960, "text": "For each iteration, update the SimRank of every pair of nodes in the graph" }, { "code": null, "e": 1081, "s": 1035, "text": "If both nodes are the same, SimRank(a, b) = 1" }, { "code": null, "e": 1139, "s": 1081, "text": "If one of the nodes has no in-neighbors, SimRank(a,b) = 0" }, { "code": null, "e": 1182, "s": 1139, "text": "Else, the new SimRank follows the equation" }, { "code": null, "e": 1307, "s": 1182, "text": "We calculate the new SimRank based on the SimRank from the previous iteration (Defined recursively but computed iteratively)" }, { "code": null, "e": 1504, "s": 1307, "text": "We initialize the SimRank in the Similarity class constructor. Please note that the initial values are stored in old_sim. We retain the new_sim to save the updated SimRank from the next iteration." }, { "code": null, "e": 1616, "s": 1504, "text": "The initializing rule is just like what we mentioned above. SimRank = 1 if both are the same, else SimRank = 0." }, { "code": null, "e": 1831, "s": 1616, "text": "This is the SimRank main function. We iterate every pair of nodes in the graph and update the SimRank. After getting all the new SimRank values, we replace the old values with the values from the current iteration." }, { "code": null, "e": 1869, "s": 1831, "text": "If both nodes are the same, value = 1" }, { "code": null, "e": 1919, "s": 1869, "text": "If one of the nodes has no in-neighbor, value = 0" }, { "code": null, "e": 2030, "s": 1919, "text": "SimRank_sum = the sum of SimRank value of all in-neighbor pairs (SimRank value is from the previous iteration)" }, { "code": null, "e": 2068, "s": 2030, "text": "Calculate the scale with decay factor" }, { "code": null, "e": 2121, "s": 2068, "text": "Calculate the new SimRank with SimRank_sum and scale" }, { "code": null, "e": 2185, "s": 2121, "text": "Take the calculated new SimRank value and assign it to new_sim." }, { "code": null, "e": 2275, "s": 2185, "text": "Replace the value from the previous iteration with the values from the current iteration." }, { "code": null, "e": 2332, "s": 2275, "text": "https://gist.github.com/9395c9aea14e4086ce2611809084f9a0" }, { "code": null, "e": 2436, "s": 2332, "text": "Let’s test our implementation on the dataset in the repo. We set decay_factor = 0.9 in all the results." }, { "code": null, "e": 2443, "s": 2436, "text": "Result" }, { "code": null, "e": 2673, "s": 2443, "text": "The result follows the order of node value, which is 1, 2, 3, 4, 5, 6 on the row and 1, 2, 3, 4, 5, 6 on the column. From the matrix, we could see that the diagonal is always full of 1s. The SimRank of two same nodes is always 1." }, { "code": null, "e": 2891, "s": 2673, "text": "Recall the SimRank equation explained above, having a common parent or not matters a lot in the calculation. From the graph, we could see that there’s no pair of nodes have a common parent. Thus, all the SimRank is 0." }, { "code": null, "e": 2898, "s": 2891, "text": "Result" }, { "code": null, "e": 2974, "s": 2898, "text": "Similarly, none of the nodes has a common parent. So the SimRank are all 0." }, { "code": null, "e": 2981, "s": 2974, "text": "Result" }, { "code": null, "e": 3042, "s": 2981, "text": "From the result matrix, there’s one interesting observation." }, { "code": null, "e": 3072, "s": 3042, "text": "SimRank[1][3] = SimRank[3][1]" }, { "code": null, "e": 3228, "s": 3072, "text": "Let’s take a look at the pairs that SimRank != 0. (node1, node3), (node2, node4) all have a common parent, and that makes their SimRank not equals to zero." }, { "code": null, "e": 3235, "s": 3228, "text": "Result" }, { "code": null, "e": 3371, "s": 3235, "text": "Let’s look at pair (node6, node4), (node7, node4). The common node in these two pairs is node4. Node4 has two parents, node1 and node5." }, { "code": null, "e": 3410, "s": 3371, "text": "Node1 is the only in-neighbor of node7" }, { "code": null, "e": 3449, "s": 3410, "text": "Node5 is the only in-neighbor of node6" }, { "code": null, "e": 3532, "s": 3449, "text": "As you can see, this kind of relationship makes them got the same SimRank = 0.695." }, { "code": null, "e": 3539, "s": 3532, "text": "Result" }, { "code": null, "e": 3674, "s": 3539, "text": "The result follows the node value order, which is 2076, 2564, 4785, 5016, 5793, 6338, 6395, 9484, 9994 in row and column respectively." }, { "code": null, "e": 3902, "s": 3674, "text": "You might be wondering why (node4785, node5016) has a single and common parent, but the SimRank is not 1. This is why we need the decay factor, to separate the difference between extremely high similarity and totally identical." }, { "code": null, "e": 4058, "s": 3902, "text": "Now we all knew that after enough iterations, SimRank will always converge to a specific value. Why don’t we plot it out to check how fast it’s converging?" }, { "code": null, "e": 4097, "s": 4058, "text": "Testing the convergence on graph_4.txt" }, { "code": null, "e": 4373, "s": 4097, "text": "There are two important observations here. The first one is that just like how we expected, the value started at 0 and gradually increased to a certain value and stop changing. The second one is that the curve is smoother than the plot we got from HITS or PageRank algorithm." }, { "code": null, "e": 4708, "s": 4373, "text": "Please note that it may not always take only this few iterations to complete the calculation. For example, if we test this SimRank algorithm on graph_6 in the repo, which has 1228 nodes and 5220 edges, even 500 iteration is not enough for the SimRank to converge. And the computation takes forever long due to a large number of edges." }, { "code": null, "e": 5016, "s": 4708, "text": "We run 100 iterations with a different number of total edges in order to spot the relation between total edges and computation time. As you can see, the inference of edges number on the computation time is increasing faster than linear. So the calculation will be extremely slow if there are too many edges." } ]
Find the quadratic equation from the given roots - GeeksforGeeks
10 Mar, 2022 Given the roots of a quadratic equation A and B, the task is to find the equation.Note: The given roots are integral. Examples: Input: A = 2, B = 3 Output: x^2 – (5x) + (6) = 0 x2 – 5x + 6 = 0 x2 -3x -2x + 6 = 0 x(x – 3) – 2(x – 3) = 0 (x – 3) (x – 2) = 0 x = 2, 3 Input: A = 5, B = 10 Output: x^2 – (15x) + (50) = 0 Approach: If the roots of a quadratic equation ax2 + bx + c = 0 are A and B then it known that A + B = – b / a and A * B = c * a. Now, ax2 + bx + c = 0 can be written as x2 + (b / a)x + (c / a) = 0 (Since, a != 0) x2 – (A + B)x + (A * B) = 0, [Since, A + B = -b * a and A * B = c * a] i.e. x2 – (Sum of the roots)x + Product of the roots = 0 Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the quadratic// equation whose roots are a and bvoid findEquation(int a, int b){ int sum = (a + b); int product = (a * b); cout << "x^2 - (" << sum << "x) + (" << product << ") = 0";} // Driver codeint main(){ int a = 2, b = 3; findEquation(a, b); return 0;} // Java implementation of the above approachclass GFG{ // Function to find the quadratic // equation whose roots are a and b static void findEquation(int a, int b) { int sum = (a + b); int product = (a * b); System.out.println("x^2 - (" + sum + "x) + (" + product + ") = 0"); } // Driver code public static void main(String args[]) { int a = 2, b = 3; findEquation(a, b); }} // This code is contributed by AnkitRai01 # Python3 implementation of the approach # Function to find the quadratic# equation whose roots are a and bdef findEquation(a, b): summ = (a + b) product = (a * b) print("x^2 - (", summ, "x) + (", product, ") = 0") # Driver codea = 2b = 3 findEquation(a, b) # This code is contributed by Mohit Kumar // C# implementation of the above approachusing System;class GFG{ // Function to find the quadratic // equation whose roots are a and b static void findEquation(int a, int b) { int sum = (a + b); int product = (a * b); Console.WriteLine("x^2 - (" + sum + "x) + (" + product + ") = 0"); } // Driver code public static void Main() { int a = 2, b = 3; findEquation(a, b); }} // This code is contributed by CodeMech. <script> // Javascript implementation of the above approach // Function to find the quadratic// equation whose roots are a and bfunction findEquation(a, b){ var sum = (a + b); var product = (a * b); document.write("x^2 - (" + sum + "x) + (" + product + ") = 0");} // Driver Codevar a = 2, b = 3; findEquation(a, b); // This code is contributed by Ankita saini </script> x^2 - (5x) + (6) = 0 Time Complexity: O(1) Auxiliary Space: O(1) mohit kumar 29 ankthon Code_Mech imaryan20 ankita_saini subham348 series Mathematical Mathematical series 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 Complexity Analysis of Binary Search Check if a number is Palindrome Find Union and Intersection of two unsorted arrays Count ways to reach the n'th stair Find first and last digits of a number
[ { "code": null, "e": 24692, "s": 24664, "text": "\n10 Mar, 2022" }, { "code": null, "e": 24810, "s": 24692, "text": "Given the roots of a quadratic equation A and B, the task is to find the equation.Note: The given roots are integral." }, { "code": null, "e": 24821, "s": 24810, "text": "Examples: " }, { "code": null, "e": 24958, "s": 24821, "text": "Input: A = 2, B = 3 Output: x^2 – (5x) + (6) = 0 x2 – 5x + 6 = 0 x2 -3x -2x + 6 = 0 x(x – 3) – 2(x – 3) = 0 (x – 3) (x – 2) = 0 x = 2, 3" }, { "code": null, "e": 25011, "s": 24958, "text": "Input: A = 5, B = 10 Output: x^2 – (15x) + (50) = 0 " }, { "code": null, "e": 25353, "s": 25011, "text": "Approach: If the roots of a quadratic equation ax2 + bx + c = 0 are A and B then it known that A + B = – b / a and A * B = c * a. Now, ax2 + bx + c = 0 can be written as x2 + (b / a)x + (c / a) = 0 (Since, a != 0) x2 – (A + B)x + (A * B) = 0, [Since, A + B = -b * a and A * B = c * a] i.e. x2 – (Sum of the roots)x + Product of the roots = 0" }, { "code": null, "e": 25405, "s": 25353, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25409, "s": 25405, "text": "C++" }, { "code": null, "e": 25414, "s": 25409, "text": "Java" }, { "code": null, "e": 25422, "s": 25414, "text": "Python3" }, { "code": null, "e": 25425, "s": 25422, "text": "C#" }, { "code": null, "e": 25436, "s": 25425, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the quadratic// equation whose roots are a and bvoid findEquation(int a, int b){ int sum = (a + b); int product = (a * b); cout << \"x^2 - (\" << sum << \"x) + (\" << product << \") = 0\";} // Driver codeint main(){ int a = 2, b = 3; findEquation(a, b); return 0;}", "e": 25825, "s": 25436, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ // Function to find the quadratic // equation whose roots are a and b static void findEquation(int a, int b) { int sum = (a + b); int product = (a * b); System.out.println(\"x^2 - (\" + sum + \"x) + (\" + product + \") = 0\"); } // Driver code public static void main(String args[]) { int a = 2, b = 3; findEquation(a, b); }} // This code is contributed by AnkitRai01", "e": 26345, "s": 25825, "text": null }, { "code": "# Python3 implementation of the approach # Function to find the quadratic# equation whose roots are a and bdef findEquation(a, b): summ = (a + b) product = (a * b) print(\"x^2 - (\", summ, \"x) + (\", product, \") = 0\") # Driver codea = 2b = 3 findEquation(a, b) # This code is contributed by Mohit Kumar", "e": 26663, "s": 26345, "text": null }, { "code": "// C# implementation of the above approachusing System;class GFG{ // Function to find the quadratic // equation whose roots are a and b static void findEquation(int a, int b) { int sum = (a + b); int product = (a * b); Console.WriteLine(\"x^2 - (\" + sum + \"x) + (\" + product + \") = 0\"); } // Driver code public static void Main() { int a = 2, b = 3; findEquation(a, b); }} // This code is contributed by CodeMech.", "e": 27178, "s": 26663, "text": null }, { "code": "<script> // Javascript implementation of the above approach // Function to find the quadratic// equation whose roots are a and bfunction findEquation(a, b){ var sum = (a + b); var product = (a * b); document.write(\"x^2 - (\" + sum + \"x) + (\" + product + \") = 0\");} // Driver Codevar a = 2, b = 3; findEquation(a, b); // This code is contributed by Ankita saini </script>", "e": 27599, "s": 27178, "text": null }, { "code": null, "e": 27620, "s": 27599, "text": "x^2 - (5x) + (6) = 0" }, { "code": null, "e": 27644, "s": 27622, "text": "Time Complexity: O(1)" }, { "code": null, "e": 27666, "s": 27644, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 27681, "s": 27666, "text": "mohit kumar 29" }, { "code": null, "e": 27689, "s": 27681, "text": "ankthon" }, { "code": null, "e": 27699, "s": 27689, "text": "Code_Mech" }, { "code": null, "e": 27709, "s": 27699, "text": "imaryan20" }, { "code": null, "e": 27722, "s": 27709, "text": "ankita_saini" }, { "code": null, "e": 27732, "s": 27722, "text": "subham348" }, { "code": null, "e": 27739, "s": 27732, "text": "series" }, { "code": null, "e": 27752, "s": 27739, "text": "Mathematical" }, { "code": null, "e": 27765, "s": 27752, "text": "Mathematical" }, { "code": null, "e": 27772, "s": 27765, "text": "series" }, { "code": null, "e": 27870, "s": 27772, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27902, "s": 27870, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 27946, "s": 27902, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 27979, "s": 27946, "text": "Program to multiply two matrices" }, { "code": null, "e": 28004, "s": 27979, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 28035, "s": 28004, "text": "Modular multiplicative inverse" }, { "code": null, "e": 28072, "s": 28035, "text": "Complexity Analysis of Binary Search" }, { "code": null, "e": 28104, "s": 28072, "text": "Check if a number is Palindrome" }, { "code": null, "e": 28155, "s": 28104, "text": "Find Union and Intersection of two unsorted arrays" }, { "code": null, "e": 28190, "s": 28155, "text": "Count ways to reach the n'th stair" } ]
AWT MouseListener Interface
The class which processes the MouseEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addMouseListener() method. Following is the declaration for java.awt.event.MouseListener interface: public interface MouseListener extends EventListener void mouseClicked(MouseEvent e) Invoked when the mouse button has been clicked (pressed and released) on a component. void mouseEntered(MouseEvent e) Invoked when the mouse enters a component. void mouseExited(MouseEvent e) Invoked when the mouse exits a component. void mousePressed(MouseEvent e) Invoked when a mouse button has been pressed on a component. void mouseReleased(MouseEvent e) Invoked when a mouse button has been released on a component. This interface inherits methods from the following interfaces: java.awt.EventListener java.awt.EventListener Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AwtListenerDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; public AwtListenerDemo(){ prepareGUI(); } public static void main(String[] args){ AwtListenerDemo awtListenerDemo = new AwtListenerDemo(); awtListenerDemo.showMouseListenerDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showMouseListenerDemo(){ headerLabel.setText("Listener in action: MouseListener"); Panel panel = new Panel(); panel.setBackground(Color.magenta); panel.setLayout(new FlowLayout()); panel.addMouseListener(new CustomMouseListener()); Label msglabel = new Label(); msglabel.setAlignment(Label.CENTER); msglabel.setText("Welcome to TutorialsPoint AWT Tutorial."); msglabel.addMouseListener(new CustomMouseListener()); panel.add(msglabel); controlPanel.add(panel); mainFrame.setVisible(true); } class CustomMouseListener implements MouseListener{ public void mouseClicked(MouseEvent e) { statusLabel.setText("Mouse Clicked: (" +e.getX()+", "+e.getY() +")"); } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1949, "s": 1747, "text": "The class which processes the MouseEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addMouseListener() method. " }, { "code": null, "e": 2022, "s": 1949, "text": "Following is the declaration for java.awt.event.MouseListener interface:" }, { "code": null, "e": 2078, "s": 2022, "text": "public interface MouseListener\n extends EventListener" }, { "code": null, "e": 2111, "s": 2078, "text": "void mouseClicked(MouseEvent e) " }, { "code": null, "e": 2197, "s": 2111, "text": "Invoked when the mouse button has been clicked (pressed and released) on a component." }, { "code": null, "e": 2230, "s": 2197, "text": "void mouseEntered(MouseEvent e) " }, { "code": null, "e": 2273, "s": 2230, "text": "Invoked when the mouse enters a component." }, { "code": null, "e": 2305, "s": 2273, "text": "void mouseExited(MouseEvent e) " }, { "code": null, "e": 2347, "s": 2305, "text": "Invoked when the mouse exits a component." }, { "code": null, "e": 2380, "s": 2347, "text": "void mousePressed(MouseEvent e) " }, { "code": null, "e": 2441, "s": 2380, "text": "Invoked when a mouse button has been pressed on a component." }, { "code": null, "e": 2474, "s": 2441, "text": "void mouseReleased(MouseEvent e)" }, { "code": null, "e": 2537, "s": 2474, "text": " Invoked when a mouse button has been released on a component." }, { "code": null, "e": 2600, "s": 2537, "text": "This interface inherits methods from the following interfaces:" }, { "code": null, "e": 2623, "s": 2600, "text": "java.awt.EventListener" }, { "code": null, "e": 2646, "s": 2623, "text": "java.awt.EventListener" }, { "code": null, "e": 2760, "s": 2646, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 5024, "s": 2760, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtListenerDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AwtListenerDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtListenerDemo awtListenerDemo = new AwtListenerDemo(); \n awtListenerDemo.showMouseListenerDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showMouseListenerDemo(){\n headerLabel.setText(\"Listener in action: MouseListener\"); \n\n Panel panel = new Panel(); \n panel.setBackground(Color.magenta);\n panel.setLayout(new FlowLayout()); \n panel.addMouseListener(new CustomMouseListener());\n\n Label msglabel = new Label();\n msglabel.setAlignment(Label.CENTER);\n msglabel.setText(\"Welcome to TutorialsPoint AWT Tutorial.\");\n\n msglabel.addMouseListener(new CustomMouseListener());\n panel.add(msglabel);\n\n controlPanel.add(panel);\n\n mainFrame.setVisible(true); \n }\n\n class CustomMouseListener implements MouseListener{\n\n public void mouseClicked(MouseEvent e) {\n statusLabel.setText(\"Mouse Clicked: (\"\n +e.getX()+\", \"+e.getY() +\")\");\n } \n\n public void mousePressed(MouseEvent e) {\n }\n\n public void mouseReleased(MouseEvent e) {\n }\n\n public void mouseEntered(MouseEvent e) {\n }\n\n public void mouseExited(MouseEvent e) {\n }\n }\n}" }, { "code": null, "e": 5115, "s": 5024, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 5172, "s": 5115, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtListenerDemo.java" }, { "code": null, "e": 5269, "s": 5172, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 5320, "s": 5269, "text": "D:\\AWT>java com.tutorialspoint.gui.AwtListenerDemo" }, { "code": null, "e": 5348, "s": 5320, "text": "Verify the following output" }, { "code": null, "e": 5381, "s": 5348, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 5389, "s": 5381, "text": " EduOLC" }, { "code": null, "e": 5396, "s": 5389, "text": " Print" }, { "code": null, "e": 5407, "s": 5396, "text": " Add Notes" } ]
Design counter for given sequence - GeeksforGeeks
11 Dec, 2020 Prerequisite – CountersProblem – Design synchronous counter for sequence: 0 → 1 → 3 → 4 → 5 → 7 → 0, using T flip-flop. Explanation – For given sequence, state transition diagram as following below: State transition table logic: State transition table for given sequence: T flip-flop – If value of Q changes either from 0 to 1 or from 1 to 0 then input for T flip-flop is 1 else input value is 0. Draw input table of all T flip-flops by using the excitation table of T flip-flop. As nature of T flip-flop is toggle in nature. Here, Q3 as Most significant bit and Q1 as least significant bit. Find value of T3, T2, T1 in terms of Q3, Q2, Q1 using K-Map (Karnaugh Map): Therefore, T3 = Q2 Therefore, T2 = Q1 Therefore, T1 = Q2’ Now, you can design required circuit using expressions of K-maps: sachinsinghbisht5 Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 4-bit binary Adder-Subtractor IEEE Standard 754 Floating Point Numbers Difference between RAM and ROM Difference between Unipolar, Polar and Bipolar Line Coding Schemes Analog to Digital Conversion Layers of OSI Model ACID Properties in DBMS Normal Forms in DBMS Types of Operating Systems
[ { "code": null, "e": 26836, "s": 26808, "text": "\n11 Dec, 2020" }, { "code": null, "e": 26956, "s": 26836, "text": "Prerequisite – CountersProblem – Design synchronous counter for sequence: 0 → 1 → 3 → 4 → 5 → 7 → 0, using T flip-flop." }, { "code": null, "e": 27035, "s": 26956, "text": "Explanation – For given sequence, state transition diagram as following below:" }, { "code": null, "e": 27065, "s": 27035, "text": "State transition table logic:" }, { "code": null, "e": 27108, "s": 27065, "text": "State transition table for given sequence:" }, { "code": null, "e": 27233, "s": 27108, "text": "T flip-flop – If value of Q changes either from 0 to 1 or from 1 to 0 then input for T flip-flop is 1 else input value is 0." }, { "code": null, "e": 27428, "s": 27233, "text": "Draw input table of all T flip-flops by using the excitation table of T flip-flop. As nature of T flip-flop is toggle in nature. Here, Q3 as Most significant bit and Q1 as least significant bit." }, { "code": null, "e": 27504, "s": 27428, "text": "Find value of T3, T2, T1 in terms of Q3, Q2, Q1 using K-Map (Karnaugh Map):" }, { "code": null, "e": 27515, "s": 27504, "text": "Therefore," }, { "code": null, "e": 27524, "s": 27515, "text": "T3 = Q2 " }, { "code": null, "e": 27535, "s": 27524, "text": "Therefore," }, { "code": null, "e": 27544, "s": 27535, "text": "T2 = Q1 " }, { "code": null, "e": 27555, "s": 27544, "text": "Therefore," }, { "code": null, "e": 27565, "s": 27555, "text": "T1 = Q2’ " }, { "code": null, "e": 27631, "s": 27565, "text": "Now, you can design required circuit using expressions of K-maps:" }, { "code": null, "e": 27649, "s": 27631, "text": "sachinsinghbisht5" }, { "code": null, "e": 27684, "s": 27649, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 27692, "s": 27684, "text": "GATE CS" }, { "code": null, "e": 27790, "s": 27692, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27799, "s": 27790, "text": "Comments" }, { "code": null, "e": 27812, "s": 27799, "text": "Old Comments" }, { "code": null, "e": 27842, "s": 27812, "text": "4-bit binary Adder-Subtractor" }, { "code": null, "e": 27883, "s": 27842, "text": "IEEE Standard 754 Floating Point Numbers" }, { "code": null, "e": 27914, "s": 27883, "text": "Difference between RAM and ROM" }, { "code": null, "e": 27981, "s": 27914, "text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes" }, { "code": null, "e": 28010, "s": 27981, "text": "Analog to Digital Conversion" }, { "code": null, "e": 28030, "s": 28010, "text": "Layers of OSI Model" }, { "code": null, "e": 28054, "s": 28030, "text": "ACID Properties in DBMS" }, { "code": null, "e": 28075, "s": 28054, "text": "Normal Forms in DBMS" } ]
S3 class in R Programming - GeeksforGeeks
28 Jan, 2022 All things in the R language are considered objects. Objects have attributes and the most common attribute related to an object is class. The command class is used to define a class of an object or learn about the classes of an object. Class is a vector and this property allows two things: Objects are allowed to inherit from numerous classes Order of inheritance can be specified for complex classes Example: Checking the class of an object Python3 # Creating a vector x consisting of type of gendersx<-c("female", "male", "male", "female") # Using the command <code>class()</code># to check the class of the vectorclass(x) Output: [1] "character" Example: Appending the class of an object Python3 # Creating a vector x consisting of type of gendersx<-c("female", "male", "male", "female") # Using the command <code>class()</code># to append the class of the vectorclass(x)<-append(class(x), "Gender")class(x) Output: [1] "character" "Gender" While doing object-oriented programming the programmer can have doubts about which class to use- S3 OR S4? When comparing both the classes, S4 has a more structured approach while S3 is considered a flexible class.Memory environments are responsible for flexibility in S3 classes. An environment is like a local scope and has a variable set associated with it. These variables are accessible if ‘ID’ associated with the environment is known.To know or set the values of a variable in an environment, commands like assign and get are used.Example: Assigning and getting values of a variable within the environment Python3 # Creating a vector x consisting of type of genders# Creating a vector for ageage<-c(12, 10, 09) # The command environment() can be used# to bring the pointer to current environmente <- environment()e # Setting the value of the variableassign("age", 3, e)ls() # Getting the values of the variableget("age", e) Output: [1] "age" "e" "x" [1] 3 Environments can be easily created. They can also be embedded in other environments. An S3 class is the most prevalent and used class in R programming. It is easy to implement this class and most of the predefined classes are of this type. An S3 object is basically a list with its class attributes assigned some names. And the member variable of the object created is the components of the list.For creating an S3 object there are two main steps: Create a list(say x) with the required components Then the class can be formed by command class(x) and a name should be assigned to this class Examples: An S3 object of bank account details can be created easily. Python3 x <- list(name ="Arjun", account_no = 1234, saving = 1500, withdrawn = 234)class(x)<-"bank"x Output: $name [1] "Arjun" $account_no [1] 1234 $saving [1] 1500 $withdrawn [1] 234 attr(, "class") [1] "bank" Examples: An S3 object of a person’s resume can be created easily. Python3 x <- list(name ="Arjun", percentage = 95, school_name ="ST Xavier")class(x)<-"resume"x Output: $name [1] "Arjun" $percentage [1] 95 $school_name [1] "ST Xavier" attr(, "class") [1] "resume" Other languages like- Python, Java, C++, etc have a proper definition for class and the objects have proper defined methods and attributes. But in the R language in the S3 class system, it is flexible and you can even modify or convert them (object of the same class can be different).The S3 system in R language consists of three main components Generic function method attributes R uses print() function very often. If you type the name of the class, its internals will be printed or you can use the command print(name of the class). But the same function print() is used to print dissimilar things like – vectors, data frames, matrices, etc. The function print() is a generic function and hence is a collection of methods. These methods can further be checked by typing the command methods(print). Python3 methods(print) Output: [1] print.AES* [2] print.Arima* [3] print.AsIs [4] print.Bibtex* [5] print.CRAN_package_reverse_dependencies_and_views* [6] print.DLLInfo [7] print.DLLInfoList [8] print.DLLRegisteredRoutines [9] print.Date [10] print.Dlist [11] print.HoltWinters* [12] print.LaTeX* [13] print.Latex* [14] print.MethodsFunction* [15] print.NativeRoutineList [16] print.PDF_Array* [17] print.PDF_Dictionary* [18] print.PDF_Indirect_Reference* [19] print.PDF_Keyword* [20] print.PDF_Name* [21] print.PDF_Stream* [22] print.PDF_String* [23] print.POSIXct [24] print.POSIXlt [25] print.R6* [26] print.R6ClassGenerator* [27] print.RGBcolorConverter* [28] print.Rcpp_stack_trace* [29] print.Rd* [30] print.SOCK0node* [31] print.SOCKcluster* [32] print.SOCKnode* [33] print.State* [34] print.StructTS* [35] print.TukeyHSD* [36] print.acf* [37] print.anova* [38] print.aov* [39] print.aovlist* [40] print.ar* [41] print.arima0* [42] print.aspell* [43] print.aspell_inspect_context* [44] print.bibentry* [45] print.browseVignettes* [46] print.by [47] print.bytes* [48] print.changedFiles* [49] print.checkDocFiles* [50] print.checkDocStyle* [51] print.checkFF* [52] print.checkRd* [53] print.checkReplaceFuns* [54] print.checkS3methods* [55] print.checkTnF* [56] print.checkVignettes* [57] print.check_Rd_contents* [58] print.check_Rd_line_widths* [59] print.check_Rd_metadata* [60] print.check_Rd_xrefs* [61] print.check_RegSym_calls* [62] print.check_T_and_F* [63] print.check_code_usage_in_package* [64] print.check_compiled_code* [65] print.check_demo_index* [66] print.check_depdef* [67] print.check_details* [68] print.check_details_changes* [69] print.check_doi_db* [70] print.check_dotInternal* [71] print.check_make_vars* [72] print.check_nonAPI_calls* [73] print.check_package_CRAN_incoming* [74] print.check_package_code_assign_to_globalenv* [75] print.check_package_code_attach* [76] print.check_package_code_data_into_globalenv* [77] print.check_package_code_startup_functions* [78] print.check_package_code_syntax* [79] print.check_package_code_unload_functions* [80] print.check_package_compact_datasets* [81] print.check_package_datasets* [82] print.check_package_depends* [83] print.check_package_description* [84] print.check_package_description_encoding* [85] print.check_package_license* [86] print.check_packages_in_dir* [87] print.check_packages_used* [88] print.check_po_files* [89] print.check_so_symbols* [90] print.check_url_db* [91] print.check_vignette_index* [92] print.citation* [93] print.codoc* [94] print.codocClasses* [95] print.codocData* [96] print.colorConverter* [97] print.compactPDF* [98] print.condition [99] print.connection [100] print.data.frame [101] print.default [102] print.dendrogram* [103] print.density* [104] print.difftime [105] print.dist* [106] print.dummy_coef* [107] print.dummy_coef_list* [108] print.ecdf* [109] print.eigen [110] print.factanal* [111] print.factor [112] print.family* [113] print.fileSnapshot* [114] print.findLineNumResult* [115] print.formula* [116] print.fseq* [117] print.ftable* [118] print.function [119] print.getAnywhere* [120] print.glm* [121] print.hclust* [122] print.help_files_with_topic* [123] print.hexmode [124] print.hsearch* [125] print.hsearch_db* [126] print.htest* [127] print.html* [128] print.html_dependency* [129] print.htmlwidget* [130] print.infl* [131] print.integrate* [132] print.isoreg* [133] print.kmeans* [134] print.libraryIQR [135] print.listof [136] print.lm* [137] print.loadings* [138] print.loess* [139] print.logLik* [140] print.ls_str* [141] print.medpolish* [142] print.mtable* [143] print.news_db* [144] print.nls* [145] print.noquote [146] print.numeric_version [147] print.object_size* [148] print.octmode [149] print.packageDescription* [150] print.packageIQR* [151] print.packageInfo [152] print.packageStatus* [153] print.pairwise.htest* [154] print.pdf_doc* [155] print.pdf_fonts* [156] print.pdf_info* [157] print.person* [158] print.power.htest* [159] print.ppr* [160] print.prcomp* [161] print.princomp* [162] print.proc_time [163] print.raster* [164] print.recordedplot* [165] print.restart [166] print.rle [167] print.roman* [168] print.sessionInfo* [169] print.shiny.tag* [170] print.shiny.tag.list* [171] print.simple.list [172] print.smooth.spline* [173] print.socket* [174] print.srcfile [175] print.srcref [176] print.stepfun* [177] print.stl* [178] print.subdir_tests* [179] print.summarize_CRAN_check_status* [180] print.summary.aov* [181] print.summary.aovlist* [182] print.summary.ecdf* [183] print.summary.glm* [184] print.summary.lm* [185] print.summary.loess* [186] print.summary.manova* [187] print.summary.nls* [188] print.summary.packageStatus* [189] print.summary.ppr* [190] print.summary.prcomp* [191] print.summary.princomp* [192] print.summary.table [193] print.summaryDefault [194] print.suppress_viewer* [195] print.table [196] print.tables_aov* [197] print.terms* [198] print.ts* [199] print.tskernel* [200] print.tukeyline* [201] print.tukeysmooth* [202] print.undoc* [203] print.vignette* [204] print.warnings [205] print.xgettext* [206] print.xngettext* [207] print.xtabs* In the above long list there are important methods like print.factor(). When we print a factor through function print(), the call would automatically dispatch to print.factor()The class created as – bank, would search for a method named print.bank(), and since no such method exists print.default() is used. Generic functions have a default method which is used when no match is available. Creating your own method is possible. Now if the class – ‘bank’ searches for print.bank(), it will find this method and use it if we have already created it. Python3 x <- list(name ="Arjun", account_no = 1234, saving = 1500, withdrawn = 234)class(x)<-"bank"print.bank<-function(obj){ cat("Name is ", obj$name, "\n") cat(obj$account_no, " is the Acc no of the holder\n ") cat(obj$saving, " is the amount of saving in the account \n ") cat(obj$withdrawn, " is the withdrawn amount\n")}x Output: Name is Arjun 1234 is the Acc no of the holder 1500 is the amount of saving in the account 234 is the withdrawn amount In a general way creating methods can be now easily defined and understood. Firstly define a function(in a generic way) existing out of the class. Secondly, defining the function specifics to a given class. Based on the class names of an argument to the function and the suffix written in the names of the associated functions, The R environments determine which function to use. Python3 # Defining a functionindian <- function(eatslunch = TRUE, myFavorite ="daal"){ me <- list(haslunch = eatslunch, favoritelunch = myFavorite) # Set the name for the class class(me) <- append(class(me), "indian") return(me)} # Reserving the name of the function and# by using the command <code>UseMethod</code># R will search for the appropriate function.setHaslunch <- function(e, newValue){ print("Calling the base setHaslunch function") UseMethod("setHaslunch", e) print(" this is not executed")} setHaslunch.default <- function(e, newValue){ print("This objects is unable to be handled.") return(e)} setHaslunch.indian <- function(e, newValue){ print("R is in setHaslunch.indian and is setting the value") e$haslunch <- newValue return(e)} # objects calling functionsfoodie <- indian()foodie$haslunchfoodie <- setHaslunch(foodie, FALSE)foodie$haslunch Output: [1] TRUE [1] "Calling the base setHaslunch function" [1] "R is in setHaslunch.indian and is setting the value" [1] FALSE Attributes of an object do not affect the value of an object, but they are a piece of extra information which is used to handle the objects. The function attributes() can be used to view the attributes of an object. Examples:An S3 object is created and its attributes are displayed. Python3 # Defining a functionx <- list(name ="Arjun", percentage = 95, school_name ="ST Xavier")attributes(x) Output: $names [1] "name" "percentage" "school_name" $class [1] "resume" Also, you can add attributes to an object by using attr. Python3 # Defining a functionx <- list(name ="Arju", percentage = 95, school_name ="ST Xavie")attr(x, "age")<-c(18)attributes(x) Output: $names [1] "name" "percentage" "school_name" $age [1] 18 The S3 has been named so as it originated in the third version of S language. S is a programming language that later modified into R and S plus. clintra sumitgumber28 R-OOPs R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Convert Factor to Numeric and Numeric to Factor in R Programming Group by function in R using Dplyr How to Change Axis Scales in R Plots?
[ { "code": null, "e": 30313, "s": 30285, "text": "\n28 Jan, 2022" }, { "code": null, "e": 30606, "s": 30313, "text": "All things in the R language are considered objects. Objects have attributes and the most common attribute related to an object is class. The command class is used to define a class of an object or learn about the classes of an object. Class is a vector and this property allows two things: " }, { "code": null, "e": 30659, "s": 30606, "text": "Objects are allowed to inherit from numerous classes" }, { "code": null, "e": 30717, "s": 30659, "text": "Order of inheritance can be specified for complex classes" }, { "code": null, "e": 30760, "s": 30717, "text": "Example: Checking the class of an object " }, { "code": null, "e": 30768, "s": 30760, "text": "Python3" }, { "code": "# Creating a vector x consisting of type of gendersx<-c(\"female\", \"male\", \"male\", \"female\") # Using the command <code>class()</code># to check the class of the vectorclass(x)", "e": 30943, "s": 30768, "text": null }, { "code": null, "e": 30953, "s": 30943, "text": "Output: " }, { "code": null, "e": 30969, "s": 30953, "text": "[1] \"character\"" }, { "code": null, "e": 31013, "s": 30969, "text": "Example: Appending the class of an object " }, { "code": null, "e": 31021, "s": 31013, "text": "Python3" }, { "code": "# Creating a vector x consisting of type of gendersx<-c(\"female\", \"male\", \"male\", \"female\") # Using the command <code>class()</code># to append the class of the vectorclass(x)<-append(class(x), \"Gender\")class(x)", "e": 31233, "s": 31021, "text": null }, { "code": null, "e": 31243, "s": 31233, "text": "Output: " }, { "code": null, "e": 31271, "s": 31243, "text": "[1] \"character\" \"Gender\" " }, { "code": null, "e": 31888, "s": 31273, "text": "While doing object-oriented programming the programmer can have doubts about which class to use- S3 OR S4? When comparing both the classes, S4 has a more structured approach while S3 is considered a flexible class.Memory environments are responsible for flexibility in S3 classes. An environment is like a local scope and has a variable set associated with it. These variables are accessible if ‘ID’ associated with the environment is known.To know or set the values of a variable in an environment, commands like assign and get are used.Example: Assigning and getting values of a variable within the environment " }, { "code": null, "e": 31896, "s": 31888, "text": "Python3" }, { "code": "# Creating a vector x consisting of type of genders# Creating a vector for ageage<-c(12, 10, 09) # The command environment() can be used# to bring the pointer to current environmente <- environment()e # Setting the value of the variableassign(\"age\", 3, e)ls() # Getting the values of the variableget(\"age\", e)", "e": 32206, "s": 31896, "text": null }, { "code": null, "e": 32216, "s": 32206, "text": "Output: " }, { "code": null, "e": 32247, "s": 32216, "text": "[1] \"age\" \"e\" \"x\" \n[1] 3 " }, { "code": null, "e": 32334, "s": 32247, "text": "Environments can be easily created. They can also be embedded in other environments. " }, { "code": null, "e": 32699, "s": 32334, "text": "An S3 class is the most prevalent and used class in R programming. It is easy to implement this class and most of the predefined classes are of this type. An S3 object is basically a list with its class attributes assigned some names. And the member variable of the object created is the components of the list.For creating an S3 object there are two main steps: " }, { "code": null, "e": 32749, "s": 32699, "text": "Create a list(say x) with the required components" }, { "code": null, "e": 32842, "s": 32749, "text": "Then the class can be formed by command class(x) and a name should be assigned to this class" }, { "code": null, "e": 32914, "s": 32842, "text": "Examples: An S3 object of bank account details can be created easily. " }, { "code": null, "e": 32922, "s": 32914, "text": "Python3" }, { "code": "x <- list(name =\"Arjun\", account_no = 1234, saving = 1500, withdrawn = 234)class(x)<-\"bank\"x", "e": 33024, "s": 32922, "text": null }, { "code": null, "e": 33139, "s": 33024, "text": "Output: \n$name\n[1] \"Arjun\"\n\n$account_no\n[1] 1234\n\n$saving\n[1] 1500\n\n$withdrawn\n[1] 234\n\nattr(, \"class\")\n[1] \"bank\"" }, { "code": null, "e": 33207, "s": 33139, "text": "Examples: An S3 object of a person’s resume can be created easily. " }, { "code": null, "e": 33215, "s": 33207, "text": "Python3" }, { "code": "x <- list(name =\"Arjun\", percentage = 95, school_name =\"ST Xavier\")class(x)<-\"resume\"x", "e": 33311, "s": 33215, "text": null }, { "code": null, "e": 33321, "s": 33311, "text": "Output: " }, { "code": null, "e": 33419, "s": 33321, "text": "$name\n[1] \"Arjun\"\n\n$percentage\n[1] 95\n\n$school_name\n[1] \"ST Xavier\"\n\nattr(, \"class\")\n[1] \"resume\"" }, { "code": null, "e": 33768, "s": 33419, "text": "Other languages like- Python, Java, C++, etc have a proper definition for class and the objects have proper defined methods and attributes. But in the R language in the S3 class system, it is flexible and you can even modify or convert them (object of the same class can be different).The S3 system in R language consists of three main components " }, { "code": null, "e": 33785, "s": 33768, "text": "Generic function" }, { "code": null, "e": 33792, "s": 33785, "text": "method" }, { "code": null, "e": 33803, "s": 33792, "text": "attributes" }, { "code": null, "e": 34070, "s": 33805, "text": "R uses print() function very often. If you type the name of the class, its internals will be printed or you can use the command print(name of the class). But the same function print() is used to print dissimilar things like – vectors, data frames, matrices, etc. " }, { "code": null, "e": 34227, "s": 34070, "text": "The function print() is a generic function and hence is a collection of methods. These methods can further be checked by typing the command methods(print). " }, { "code": null, "e": 34235, "s": 34227, "text": "Python3" }, { "code": "methods(print)", "e": 34250, "s": 34235, "text": null }, { "code": null, "e": 34260, "s": 34250, "text": "Output: " }, { "code": null, "e": 46061, "s": 34260, "text": " \n [1] print.AES* \n [2] print.Arima* \n [3] print.AsIs \n [4] print.Bibtex* \n [5] print.CRAN_package_reverse_dependencies_and_views*\n [6] print.DLLInfo \n [7] print.DLLInfoList \n [8] print.DLLRegisteredRoutines \n [9] print.Date \n [10] print.Dlist \n [11] print.HoltWinters* \n [12] print.LaTeX* \n [13] print.Latex* \n [14] print.MethodsFunction* \n [15] print.NativeRoutineList \n [16] print.PDF_Array* \n [17] print.PDF_Dictionary* \n [18] print.PDF_Indirect_Reference* \n [19] print.PDF_Keyword* \n [20] print.PDF_Name* \n [21] print.PDF_Stream* \n [22] print.PDF_String* \n [23] print.POSIXct \n [24] print.POSIXlt \n [25] print.R6* \n [26] print.R6ClassGenerator* \n [27] print.RGBcolorConverter* \n [28] print.Rcpp_stack_trace* \n [29] print.Rd* \n [30] print.SOCK0node* \n [31] print.SOCKcluster* \n [32] print.SOCKnode* \n [33] print.State* \n [34] print.StructTS* \n [35] print.TukeyHSD* \n [36] print.acf* \n [37] print.anova* \n [38] print.aov* \n [39] print.aovlist* \n [40] print.ar* \n [41] print.arima0* \n [42] print.aspell* \n [43] print.aspell_inspect_context* \n [44] print.bibentry* \n [45] print.browseVignettes* \n [46] print.by \n [47] print.bytes* \n [48] print.changedFiles* \n [49] print.checkDocFiles* \n [50] print.checkDocStyle* \n [51] print.checkFF* \n [52] print.checkRd* \n [53] print.checkReplaceFuns* \n [54] print.checkS3methods* \n [55] print.checkTnF* \n [56] print.checkVignettes* \n [57] print.check_Rd_contents* \n [58] print.check_Rd_line_widths* \n [59] print.check_Rd_metadata* \n [60] print.check_Rd_xrefs* \n [61] print.check_RegSym_calls* \n [62] print.check_T_and_F* \n [63] print.check_code_usage_in_package* \n [64] print.check_compiled_code* \n [65] print.check_demo_index* \n [66] print.check_depdef* \n [67] print.check_details* \n [68] print.check_details_changes* \n [69] print.check_doi_db* \n [70] print.check_dotInternal* \n [71] print.check_make_vars* \n [72] print.check_nonAPI_calls* \n [73] print.check_package_CRAN_incoming* \n [74] print.check_package_code_assign_to_globalenv* \n [75] print.check_package_code_attach* \n [76] print.check_package_code_data_into_globalenv* \n [77] print.check_package_code_startup_functions* \n [78] print.check_package_code_syntax* \n [79] print.check_package_code_unload_functions* \n [80] print.check_package_compact_datasets* \n [81] print.check_package_datasets* \n [82] print.check_package_depends* \n [83] print.check_package_description* \n [84] print.check_package_description_encoding* \n [85] print.check_package_license* \n [86] print.check_packages_in_dir* \n [87] print.check_packages_used* \n [88] print.check_po_files* \n [89] print.check_so_symbols* \n [90] print.check_url_db* \n [91] print.check_vignette_index* \n [92] print.citation* \n [93] print.codoc* \n [94] print.codocClasses* \n [95] print.codocData* \n [96] print.colorConverter* \n [97] print.compactPDF* \n [98] print.condition \n [99] print.connection \n[100] print.data.frame \n[101] print.default \n[102] print.dendrogram* \n[103] print.density* \n[104] print.difftime \n[105] print.dist* \n[106] print.dummy_coef* \n[107] print.dummy_coef_list* \n[108] print.ecdf* \n[109] print.eigen \n[110] print.factanal* \n[111] print.factor \n[112] print.family* \n[113] print.fileSnapshot* \n[114] print.findLineNumResult* \n[115] print.formula* \n[116] print.fseq* \n[117] print.ftable* \n[118] print.function \n[119] print.getAnywhere* \n[120] print.glm* \n[121] print.hclust* \n[122] print.help_files_with_topic* \n[123] print.hexmode \n[124] print.hsearch* \n[125] print.hsearch_db* \n[126] print.htest* \n[127] print.html* \n[128] print.html_dependency* \n[129] print.htmlwidget* \n[130] print.infl* \n[131] print.integrate* \n[132] print.isoreg* \n[133] print.kmeans* \n[134] print.libraryIQR \n[135] print.listof \n[136] print.lm* \n[137] print.loadings* \n[138] print.loess* \n[139] print.logLik* \n[140] print.ls_str* \n[141] print.medpolish* \n[142] print.mtable* \n[143] print.news_db* \n[144] print.nls* \n[145] print.noquote \n[146] print.numeric_version \n[147] print.object_size* \n[148] print.octmode \n[149] print.packageDescription* \n[150] print.packageIQR* \n[151] print.packageInfo \n[152] print.packageStatus* \n[153] print.pairwise.htest* \n[154] print.pdf_doc* \n[155] print.pdf_fonts* \n[156] print.pdf_info* \n[157] print.person* \n[158] print.power.htest* \n[159] print.ppr* \n[160] print.prcomp* \n[161] print.princomp* \n[162] print.proc_time \n[163] print.raster* \n[164] print.recordedplot* \n[165] print.restart \n[166] print.rle \n[167] print.roman* \n[168] print.sessionInfo* \n[169] print.shiny.tag* \n[170] print.shiny.tag.list* \n[171] print.simple.list \n[172] print.smooth.spline* \n[173] print.socket* \n[174] print.srcfile \n[175] print.srcref \n[176] print.stepfun* \n[177] print.stl* \n[178] print.subdir_tests* \n[179] print.summarize_CRAN_check_status* \n[180] print.summary.aov* \n[181] print.summary.aovlist* \n[182] print.summary.ecdf* \n[183] print.summary.glm* \n[184] print.summary.lm* \n[185] print.summary.loess* \n[186] print.summary.manova* \n[187] print.summary.nls* \n[188] print.summary.packageStatus* \n[189] print.summary.ppr* \n[190] print.summary.prcomp* \n[191] print.summary.princomp* \n[192] print.summary.table \n[193] print.summaryDefault \n[194] print.suppress_viewer* \n[195] print.table \n[196] print.tables_aov* \n[197] print.terms* \n[198] print.ts* \n[199] print.tskernel* \n[200] print.tukeyline* \n[201] print.tukeysmooth* \n[202] print.undoc* \n[203] print.vignette* \n[204] print.warnings \n[205] print.xgettext* \n[206] print.xngettext* \n[207] print.xtabs* " }, { "code": null, "e": 46452, "s": 46061, "text": "In the above long list there are important methods like print.factor(). When we print a factor through function print(), the call would automatically dispatch to print.factor()The class created as – bank, would search for a method named print.bank(), and since no such method exists print.default() is used. Generic functions have a default method which is used when no match is available. " }, { "code": null, "e": 46612, "s": 46452, "text": "Creating your own method is possible. Now if the class – ‘bank’ searches for print.bank(), it will find this method and use it if we have already created it. " }, { "code": null, "e": 46620, "s": 46612, "text": "Python3" }, { "code": "x <- list(name =\"Arjun\", account_no = 1234, saving = 1500, withdrawn = 234)class(x)<-\"bank\"print.bank<-function(obj){ cat(\"Name is \", obj$name, \"\\n\") cat(obj$account_no, \" is the Acc no of the holder\\n \") cat(obj$saving, \" is the amount of saving in the account \\n \") cat(obj$withdrawn, \" is the withdrawn amount\\n\")}x", "e": 46960, "s": 46620, "text": null }, { "code": null, "e": 46970, "s": 46960, "text": "Output: " }, { "code": null, "e": 47095, "s": 46970, "text": "Name is Arjun \n1234 is the Acc no of the holder\n1500 is the amount of saving in the account \n234 is the withdrawn amount" }, { "code": null, "e": 47173, "s": 47095, "text": "In a general way creating methods can be now easily defined and understood. " }, { "code": null, "e": 47244, "s": 47173, "text": "Firstly define a function(in a generic way) existing out of the class." }, { "code": null, "e": 47304, "s": 47244, "text": "Secondly, defining the function specifics to a given class." }, { "code": null, "e": 47479, "s": 47304, "text": "Based on the class names of an argument to the function and the suffix written in the names of the associated functions, The R environments determine which function to use. " }, { "code": null, "e": 47487, "s": 47479, "text": "Python3" }, { "code": "# Defining a functionindian <- function(eatslunch = TRUE, myFavorite =\"daal\"){ me <- list(haslunch = eatslunch, favoritelunch = myFavorite) # Set the name for the class class(me) <- append(class(me), \"indian\") return(me)} # Reserving the name of the function and# by using the command <code>UseMethod</code># R will search for the appropriate function.setHaslunch <- function(e, newValue){ print(\"Calling the base setHaslunch function\") UseMethod(\"setHaslunch\", e) print(\" this is not executed\")} setHaslunch.default <- function(e, newValue){ print(\"This objects is unable to be handled.\") return(e)} setHaslunch.indian <- function(e, newValue){ print(\"R is in setHaslunch.indian and is setting the value\") e$haslunch <- newValue return(e)} # objects calling functionsfoodie <- indian()foodie$haslunchfoodie <- setHaslunch(foodie, FALSE)foodie$haslunch", "e": 48392, "s": 47487, "text": null }, { "code": null, "e": 48402, "s": 48392, "text": "Output: " }, { "code": null, "e": 48526, "s": 48402, "text": " \n[1] TRUE\n[1] \"Calling the base setHaslunch function\"\n[1] \"R is in setHaslunch.indian and is setting the value\"\n[1] FALSE " }, { "code": null, "e": 48812, "s": 48528, "text": "Attributes of an object do not affect the value of an object, but they are a piece of extra information which is used to handle the objects. The function attributes() can be used to view the attributes of an object. Examples:An S3 object is created and its attributes are displayed. " }, { "code": null, "e": 48820, "s": 48812, "text": "Python3" }, { "code": "# Defining a functionx <- list(name =\"Arjun\", percentage = 95, school_name =\"ST Xavier\")attributes(x)", "e": 48931, "s": 48820, "text": null }, { "code": null, "e": 48941, "s": 48931, "text": "Output: " }, { "code": null, "e": 49017, "s": 48941, "text": " \n$names\n[1] \"name\" \"percentage\" \"school_name\"\n\n$class\n[1] \"resume\"" }, { "code": null, "e": 49076, "s": 49017, "text": "Also, you can add attributes to an object by using attr. " }, { "code": null, "e": 49084, "s": 49076, "text": "Python3" }, { "code": "# Defining a functionx <- list(name =\"Arju\", percentage = 95, school_name =\"ST Xavie\")attr(x, \"age\")<-c(18)attributes(x)", "e": 49214, "s": 49084, "text": null }, { "code": null, "e": 49224, "s": 49214, "text": "Output: " }, { "code": null, "e": 49290, "s": 49224, "text": "$names\n[1] \"name\" \"percentage\" \"school_name\"\n\n$age\n[1] 18" }, { "code": null, "e": 49436, "s": 49290, "text": "The S3 has been named so as it originated in the third version of S language. S is a programming language that later modified into R and S plus. " }, { "code": null, "e": 49444, "s": 49436, "text": "clintra" }, { "code": null, "e": 49458, "s": 49444, "text": "sumitgumber28" }, { "code": null, "e": 49465, "s": 49458, "text": "R-OOPs" }, { "code": null, "e": 49476, "s": 49465, "text": "R Language" }, { "code": null, "e": 49574, "s": 49476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49619, "s": 49574, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 49677, "s": 49619, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 49729, "s": 49677, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 49761, "s": 49729, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 49824, "s": 49761, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 49876, "s": 49824, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 49920, "s": 49876, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 49985, "s": 49920, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 50020, "s": 49985, "text": "Group by function in R using Dplyr" } ]
map cbegin() and cend() function in C++ STL - GeeksforGeeks
29 Jun, 2018 map::cbegin() is a built-in function in C++ STL which returns a constant iterator referring to the first element in the map container. Since map container contains the element in an ordered way, cbegin() will point to that element that will come first according to the container’s sorting criterion.Syntax:map_name.cbegin() Parameters: The function does not accept any parameter.Return Value: The function returns a constant iterator referring to the first element in the map container.// C++ program to illustrate// the map::cbegin() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 4, 20 }); mp.insert({ 5, 50 }); auto ite = mp.cbegin(); cout << "The first element is: "; cout << "{" << ite->first << ", " << ite->second << "}\n"; // prints the elements cout << "\nThe map is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.cbegin(); itr != mp.cend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}Output:The first element is: {1, 40} The map is : KEY ELEMENT 1 40 2 30 3 60 4 20 5 50 map::cend() is a built-in function in C++ STL which returns a constant iterator pointing to the theoretical element that follows last element in the multimap. Since map container contains the element in an ordered way, cend() will point to that follows the last element according to the container’s sorting criterion.Syntax:map_name.cend() Parameters: The function does not accept any parameter.Return Value: The function returns a constant iterator pointing to the theoretical element that follows the last element in the map.// C++ program to illustrate// the map::cend() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 4, 20 }); mp.insert({ 5, 50 }); // print the elements cout << "\nThe map is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.cbegin(); itr != mp.cend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}Output:The map is : KEY ELEMENT 1 40 2 30 3 60 4 20 5 50 map::cbegin() is a built-in function in C++ STL which returns a constant iterator referring to the first element in the map container. Since map container contains the element in an ordered way, cbegin() will point to that element that will come first according to the container’s sorting criterion.Syntax:map_name.cbegin() Parameters: The function does not accept any parameter.Return Value: The function returns a constant iterator referring to the first element in the map container.// C++ program to illustrate// the map::cbegin() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 4, 20 }); mp.insert({ 5, 50 }); auto ite = mp.cbegin(); cout << "The first element is: "; cout << "{" << ite->first << ", " << ite->second << "}\n"; // prints the elements cout << "\nThe map is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.cbegin(); itr != mp.cend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}Output:The first element is: {1, 40} The map is : KEY ELEMENT 1 40 2 30 3 60 4 20 5 50 Syntax: map_name.cbegin() Parameters: The function does not accept any parameter. Return Value: The function returns a constant iterator referring to the first element in the map container. // C++ program to illustrate// the map::cbegin() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 4, 20 }); mp.insert({ 5, 50 }); auto ite = mp.cbegin(); cout << "The first element is: "; cout << "{" << ite->first << ", " << ite->second << "}\n"; // prints the elements cout << "\nThe map is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.cbegin(); itr != mp.cend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;} The first element is: {1, 40} The map is : KEY ELEMENT 1 40 2 30 3 60 4 20 5 50 map::cend() is a built-in function in C++ STL which returns a constant iterator pointing to the theoretical element that follows last element in the multimap. Since map container contains the element in an ordered way, cend() will point to that follows the last element according to the container’s sorting criterion.Syntax:map_name.cend() Parameters: The function does not accept any parameter.Return Value: The function returns a constant iterator pointing to the theoretical element that follows the last element in the map.// C++ program to illustrate// the map::cend() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 4, 20 }); mp.insert({ 5, 50 }); // print the elements cout << "\nThe map is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.cbegin(); itr != mp.cend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}Output:The map is : KEY ELEMENT 1 40 2 30 3 60 4 20 5 50 Syntax: map_name.cend() Parameters: The function does not accept any parameter. Return Value: The function returns a constant iterator pointing to the theoretical element that follows the last element in the map. // C++ program to illustrate// the map::cend() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 4, 20 }); mp.insert({ 5, 50 }); // print the elements cout << "\nThe map is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.cbegin(); itr != mp.cend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;} The map is : KEY ELEMENT 1 40 2 30 3 60 4 20 5 50 CPP-Functions cpp-map STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Bitwise Operators in C/C++ Virtual Function in C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ vector erase() and clear() in C++ Object Oriented Programming in C++
[ { "code": null, "e": 25756, "s": 25728, "text": "\n29 Jun, 2018" }, { "code": null, "e": 28220, "s": 25756, "text": "map::cbegin() is a built-in function in C++ STL which returns a constant iterator referring to the first element in the map container. Since map container contains the element in an ordered way, cbegin() will point to that element that will come first according to the container’s sorting criterion.Syntax:map_name.cbegin()\nParameters: The function does not accept any parameter.Return Value: The function returns a constant iterator referring to the first element in the map container.// C++ program to illustrate// the map::cbegin() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 4, 20 }); mp.insert({ 5, 50 }); auto ite = mp.cbegin(); cout << \"The first element is: \"; cout << \"{\" << ite->first << \", \" << ite->second << \"}\\n\"; // prints the elements cout << \"\\nThe map is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.cbegin(); itr != mp.cend(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } return 0;}Output:The first element is: {1, 40}\n\nThe map is : \nKEY ELEMENT\n1 40\n2 30\n3 60\n4 20\n5 50\nmap::cend() is a built-in function in C++ STL which returns a constant iterator pointing to the theoretical element that follows last element in the multimap. Since map container contains the element in an ordered way, cend() will point to that follows the last element according to the container’s sorting criterion.Syntax:map_name.cend()\nParameters: The function does not accept any parameter.Return Value: The function returns a constant iterator pointing to the theoretical element that follows the last element in the map.// C++ program to illustrate// the map::cend() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 4, 20 }); mp.insert({ 5, 50 }); // print the elements cout << \"\\nThe map is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.cbegin(); itr != mp.cend(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } return 0;}Output:The map is : \nKEY ELEMENT\n1 40\n2 30\n3 60\n4 20\n5 50\n" }, { "code": null, "e": 29518, "s": 28220, "text": "map::cbegin() is a built-in function in C++ STL which returns a constant iterator referring to the first element in the map container. Since map container contains the element in an ordered way, cbegin() will point to that element that will come first according to the container’s sorting criterion.Syntax:map_name.cbegin()\nParameters: The function does not accept any parameter.Return Value: The function returns a constant iterator referring to the first element in the map container.// C++ program to illustrate// the map::cbegin() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 4, 20 }); mp.insert({ 5, 50 }); auto ite = mp.cbegin(); cout << \"The first element is: \"; cout << \"{\" << ite->first << \", \" << ite->second << \"}\\n\"; // prints the elements cout << \"\\nThe map is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.cbegin(); itr != mp.cend(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } return 0;}Output:The first element is: {1, 40}\n\nThe map is : \nKEY ELEMENT\n1 40\n2 30\n3 60\n4 20\n5 50\n" }, { "code": null, "e": 29526, "s": 29518, "text": "Syntax:" }, { "code": null, "e": 29545, "s": 29526, "text": "map_name.cbegin()\n" }, { "code": null, "e": 29601, "s": 29545, "text": "Parameters: The function does not accept any parameter." }, { "code": null, "e": 29709, "s": 29601, "text": "Return Value: The function returns a constant iterator referring to the first element in the map container." }, { "code": "// C++ program to illustrate// the map::cbegin() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 4, 20 }); mp.insert({ 5, 50 }); auto ite = mp.cbegin(); cout << \"The first element is: \"; cout << \"{\" << ite->first << \", \" << ite->second << \"}\\n\"; // prints the elements cout << \"\\nThe map is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.cbegin(); itr != mp.cend(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } return 0;}", "e": 30414, "s": 29709, "text": null }, { "code": null, "e": 30515, "s": 30414, "text": "The first element is: {1, 40}\n\nThe map is : \nKEY ELEMENT\n1 40\n2 30\n3 60\n4 20\n5 50\n" }, { "code": null, "e": 31682, "s": 30515, "text": "map::cend() is a built-in function in C++ STL which returns a constant iterator pointing to the theoretical element that follows last element in the multimap. Since map container contains the element in an ordered way, cend() will point to that follows the last element according to the container’s sorting criterion.Syntax:map_name.cend()\nParameters: The function does not accept any parameter.Return Value: The function returns a constant iterator pointing to the theoretical element that follows the last element in the map.// C++ program to illustrate// the map::cend() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 4, 20 }); mp.insert({ 5, 50 }); // print the elements cout << \"\\nThe map is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.cbegin(); itr != mp.cend(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } return 0;}Output:The map is : \nKEY ELEMENT\n1 40\n2 30\n3 60\n4 20\n5 50\n" }, { "code": null, "e": 31690, "s": 31682, "text": "Syntax:" }, { "code": null, "e": 31707, "s": 31690, "text": "map_name.cend()\n" }, { "code": null, "e": 31763, "s": 31707, "text": "Parameters: The function does not accept any parameter." }, { "code": null, "e": 31896, "s": 31763, "text": "Return Value: The function returns a constant iterator pointing to the theoretical element that follows the last element in the map." }, { "code": "// C++ program to illustrate// the map::cend() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 4, 20 }); mp.insert({ 5, 50 }); // print the elements cout << \"\\nThe map is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.cbegin(); itr != mp.cend(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } return 0;}", "e": 32460, "s": 31896, "text": null }, { "code": null, "e": 32530, "s": 32460, "text": "The map is : \nKEY ELEMENT\n1 40\n2 30\n3 60\n4 20\n5 50\n" }, { "code": null, "e": 32544, "s": 32530, "text": "CPP-Functions" }, { "code": null, "e": 32552, "s": 32544, "text": "cpp-map" }, { "code": null, "e": 32556, "s": 32552, "text": "STL" }, { "code": null, "e": 32560, "s": 32556, "text": "C++" }, { "code": null, "e": 32564, "s": 32560, "text": "STL" }, { "code": null, "e": 32568, "s": 32564, "text": "CPP" }, { "code": null, "e": 32666, "s": 32568, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32685, "s": 32666, "text": "Inheritance in C++" }, { "code": null, "e": 32709, "s": 32685, "text": "C++ Classes and Objects" }, { "code": null, "e": 32736, "s": 32709, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 32760, "s": 32736, "text": "Virtual Function in C++" }, { "code": null, "e": 32791, "s": 32760, "text": "Templates in C++ with Examples" }, { "code": null, "e": 32811, "s": 32791, "text": "Constructors in C++" }, { "code": null, "e": 32839, "s": 32811, "text": "Operator Overloading in C++" }, { "code": null, "e": 32867, "s": 32839, "text": "Socket Programming in C/C++" }, { "code": null, "e": 32901, "s": 32867, "text": "vector erase() and clear() in C++" } ]
Numeric fields in serializers - Django REST Framework - GeeksforGeeks
07 Jan, 2022 In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField, CharField and BooleanField for storing and manipulating data through Django. Similarly, serializer also works with same principle and has fields that are used to create a serializer. This article revolves around Numeric Fields in Serializers in Django REST Framework. There are three major fields – IntegerField, FloatField and DecimalField. IntegerField is basically a integer field that validates the input against Python’s int instance.It is same as IntegerField – Django ModelsIt has the following arguments – max_value Validate that the number provided is no greater than this value. min_value Validate that the number provided is no less than this value. Syntax – field_name = serializers.IntegerField(*args, **kwargs) FloatField is basically a float field that validates the input against Python’s float instance.It is same as FloatField – Django ModelsIt has the following arguments – max_value Validate that the number provided is no greater than this value. min_value Validate that the number provided is no less than this value. Syntax – field_name = serializers.FloatField(*args, **kwargs) DecimalField is basically a decimal field that validates the input against Python’s decimal instance.It is same as DecimalField – Django ModelsIt has the following arguments – max_digits The maximum number of digits allowed in the number. It must be either None or an integer greater than or equal to decimal_places. decimal_places The number of decimal places to store with the number. max_value Validate that the number provided is no greater than this value. min_value Validate that the number provided is no less than this value. localize Set to True to enable localization of input and output based on the current locale. Syntax – field_name = serializers.DecimalField(*args, **kwargs) To explain the usage of Numeric Fields, let’s use the same project setup from – How to Create a basic API using Django Rest Framework ?. Now that you have a file called serializers in your project, let’s create a serializer with IntegerField, FloatField and DecimalField as the fields. Python3 # import serializer from rest_frameworkfrom rest_framework import serializers class Geeks(object): def __init__(self, integer, float_number, decimal_number): self.integer = integer self.float_number = float_number self.decimal_number = decimal_number # create a serializerclass GeeksSerializer(serializers.Serializer): # initialize fields integer = serializers.IntegerField() float_number = serializers.FloatField() decimal_number = serializers.DecimalField() Now let us create some objects and try serializing them and check if they are actually working, Run, – Python manage.py shell Now, run following python commands in the shell # import everything from serializers >>> from apis.serializers import * # create a object of type Geeks >>> obj = Geeks(123, 123.10, 123.123) # serialize the object >>> serializer = GeeksSerializer(obj) # print serialized data >>> serializer.data {'integer': 123, 'float_number': 123.1, 'decimal_number': '123.1230'} Here is the output of all these operations on terminal – Note that prime motto of these fields is to impart validations, such as IntegerField validates the data to Python’s int only. Let’s check if these validations are working or not – # Create a dictionary and add invalid values >>> data={} >>> data['integer'] = 10 >>> data['float_number'] = "String" >>> data['decimal_number'] = 123 # dictionary created >>> data {'integer': 10, 'float_number': 'String', 'decimal_number': 123} # deserialize the data >>> serializer = GeeksSerializer(data=data) # check if data is valid >>> serializer.is_valid() False # check the errors >>> serializer.errors {'float_number': [ErrorDetail(string='A valid number is required.', code='invalid')]} } Here is the output of these commands which clearly shows email and phone_number as invalid – Validations are part of Deserialization and not serialization. As explained earlier, serializing is process of converting already made data into another data type, so there is no requirement of these default validations out there. Deserialization requires validations as data needs to be saved to database or any more operation as specified. So if you serialize data using these fields that would work. .math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } sweetyty Django-REST Python Django rest-framework Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n07 Jan, 2022" }, { "code": null, "e": 26232, "s": 25537, "text": "In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField, CharField and BooleanField for storing and manipulating data through Django. Similarly, serializer also works with same principle and has fields that are used to create a serializer. This article revolves around Numeric Fields in Serializers in Django REST Framework. There are three major fields – IntegerField, FloatField and DecimalField. " }, { "code": null, "e": 26406, "s": 26232, "text": "IntegerField is basically a integer field that validates the input against Python’s int instance.It is same as IntegerField – Django ModelsIt has the following arguments – " }, { "code": null, "e": 26481, "s": 26406, "text": "max_value Validate that the number provided is no greater than this value." }, { "code": null, "e": 26553, "s": 26481, "text": "min_value Validate that the number provided is no less than this value." }, { "code": null, "e": 26564, "s": 26553, "text": "Syntax – " }, { "code": null, "e": 26619, "s": 26564, "text": "field_name = serializers.IntegerField(*args, **kwargs)" }, { "code": null, "e": 26791, "s": 26621, "text": "FloatField is basically a float field that validates the input against Python’s float instance.It is same as FloatField – Django ModelsIt has the following arguments – " }, { "code": null, "e": 26866, "s": 26791, "text": "max_value Validate that the number provided is no greater than this value." }, { "code": null, "e": 26938, "s": 26866, "text": "min_value Validate that the number provided is no less than this value." }, { "code": null, "e": 26949, "s": 26938, "text": "Syntax – " }, { "code": null, "e": 27002, "s": 26949, "text": "field_name = serializers.FloatField(*args, **kwargs)" }, { "code": null, "e": 27182, "s": 27004, "text": "DecimalField is basically a decimal field that validates the input against Python’s decimal instance.It is same as DecimalField – Django ModelsIt has the following arguments – " }, { "code": null, "e": 27323, "s": 27182, "text": "max_digits The maximum number of digits allowed in the number. It must be either None or an integer greater than or equal to decimal_places." }, { "code": null, "e": 27393, "s": 27323, "text": "decimal_places The number of decimal places to store with the number." }, { "code": null, "e": 27468, "s": 27393, "text": "max_value Validate that the number provided is no greater than this value." }, { "code": null, "e": 27540, "s": 27468, "text": "min_value Validate that the number provided is no less than this value." }, { "code": null, "e": 27633, "s": 27540, "text": "localize Set to True to enable localization of input and output based on the current locale." }, { "code": null, "e": 27644, "s": 27633, "text": "Syntax – " }, { "code": null, "e": 27699, "s": 27644, "text": "field_name = serializers.DecimalField(*args, **kwargs)" }, { "code": null, "e": 27989, "s": 27701, "text": "To explain the usage of Numeric Fields, let’s use the same project setup from – How to Create a basic API using Django Rest Framework ?. Now that you have a file called serializers in your project, let’s create a serializer with IntegerField, FloatField and DecimalField as the fields. " }, { "code": null, "e": 27997, "s": 27989, "text": "Python3" }, { "code": "# import serializer from rest_frameworkfrom rest_framework import serializers class Geeks(object): def __init__(self, integer, float_number, decimal_number): self.integer = integer self.float_number = float_number self.decimal_number = decimal_number # create a serializerclass GeeksSerializer(serializers.Serializer): # initialize fields integer = serializers.IntegerField() float_number = serializers.FloatField() decimal_number = serializers.DecimalField()", "e": 28493, "s": 27997, "text": null }, { "code": null, "e": 28598, "s": 28493, "text": "Now let us create some objects and try serializing them and check if they are actually working, Run, – " }, { "code": null, "e": 28621, "s": 28598, "text": "Python manage.py shell" }, { "code": null, "e": 28671, "s": 28621, "text": "Now, run following python commands in the shell " }, { "code": null, "e": 28991, "s": 28671, "text": "# import everything from serializers\n>>> from apis.serializers import *\n\n# create a object of type Geeks\n>>> obj = Geeks(123, 123.10, 123.123)\n\n# serialize the object\n>>> serializer = GeeksSerializer(obj)\n\n# print serialized data\n>>> serializer.data\n{'integer': 123, 'float_number': 123.1, 'decimal_number': '123.1230'}" }, { "code": null, "e": 29050, "s": 28991, "text": "Here is the output of all these operations on terminal – " }, { "code": null, "e": 29234, "s": 29052, "text": "Note that prime motto of these fields is to impart validations, such as IntegerField validates the data to Python’s int only. Let’s check if these validations are working or not – " }, { "code": null, "e": 29738, "s": 29234, "text": "# Create a dictionary and add invalid values\n>>> data={}\n>>> data['integer'] = 10\n>>> data['float_number'] = \"String\"\n>>> data['decimal_number'] = 123\n\n# dictionary created\n>>> data\n{'integer': 10, 'float_number': 'String', 'decimal_number': 123}\n\n# deserialize the data\n>>> serializer = GeeksSerializer(data=data)\n\n# check if data is valid\n>>> serializer.is_valid()\nFalse\n\n# check the errors\n>>> serializer.errors\n{'float_number': [ErrorDetail(string='A valid number is required.', \ncode='invalid')]}\n}" }, { "code": null, "e": 29833, "s": 29738, "text": "Here is the output of these commands which clearly shows email and phone_number as invalid – " }, { "code": null, "e": 30239, "s": 29835, "text": "Validations are part of Deserialization and not serialization. As explained earlier, serializing is process of converting already made data into another data type, so there is no requirement of these default validations out there. Deserialization requires validations as data needs to be saved to database or any more operation as specified. So if you serialize data using these fields that would work. " }, { "code": null, "e": 30580, "s": 30241, "text": ".math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } " }, { "code": null, "e": 30593, "s": 30584, "text": "sweetyty" }, { "code": null, "e": 30605, "s": 30593, "text": "Django-REST" }, { "code": null, "e": 30619, "s": 30605, "text": "Python Django" }, { "code": null, "e": 30634, "s": 30619, "text": "rest-framework" }, { "code": null, "e": 30641, "s": 30634, "text": "Python" }, { "code": null, "e": 30739, "s": 30641, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30771, "s": 30739, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30813, "s": 30771, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30855, "s": 30813, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30911, "s": 30855, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30938, "s": 30911, "text": "Python Classes and Objects" }, { "code": null, "e": 30977, "s": 30938, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31008, "s": 30977, "text": "Python | os.path.join() method" }, { "code": null, "e": 31037, "s": 31008, "text": "Create a directory in Python" }, { "code": null, "e": 31059, "s": 31037, "text": "Defaultdict in Python" } ]
time.Time.MarshalJSON() Function in Golang with Examples - GeeksforGeeks
28 Apr, 2020 In Go language, time packages supplies functionality for determining as well as viewing time. The MarshalJSON() function in Go language is used to implement the json.Marshaler interface. And the time here is a quoted-string which is in RFC 3339 format along with the sub-second precision attached if available. 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 (t Time) MarshalJSON() ([]byte, error) Here, “t” is the stated time and two values of type “byte” and “error” are returned as output in this method. Return value: It returns a byte slice that represents JSON encoding and it also returns an error occurred but if there are no errors then “nil” is returned. Example 1: // Golang program to illustrate the usage of// Time.MarshalJSON() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Defining t for MarshalJSON method t := time.Date(2014, 11, 10, 14, 30, 12, 05, time.UTC) // Calling MarshalJSON() method encoding, error := t.MarshalJSON() // Prints JSON's encoding fmt.Printf("JSON's encoding: %v\n", encoding) // Prints error fmt.Printf("Error occurred: %v\n", error)} Output: JSON’s encoding: [34 50 48 49 52 45 49 49 45 49 48 84 49 52 58 51 48 58 49 50 46 48 48 48 48 48 48 48 48 53 90 34]Error occurred: <nil> Example 2: // Golang program to illustrate the usage of// Time.MarshalJSON() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Defining t for MarshalJSON method t := time.Date(2022, 45, 67, 88, 67, 76, 903, time.UTC) // Calling MarshalJSON() method encoding, error := t.MarshalJSON() // Prints JSON's encoding fmt.Printf("JSON's encoding: %v\n", encoding) // Prints error fmt.Printf("Error occurred: %v\n", error)} Output: JSON’s encoding: [34 50 48 50 53 45 49 49 45 48 57 84 49 55 58 48 56 58 49 54 46 48 48 48 48 48 48 57 48 51 90 34]Error occurred: <nil> Here, the “t” stated in the above code has values that are outside usual range but they are normalized while conversion. GoLang-time Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language How to Parse JSON in Golang? Time Durations in Golang Strings in Golang Structures in Golang How to iterate over an Array using for loop in Golang? Rune in Golang Defer Keyword in Golang Loops in Go Language Class and Object in Golang
[ { "code": null, "e": 25703, "s": 25675, "text": "\n28 Apr, 2020" }, { "code": null, "e": 26150, "s": 25703, "text": "In Go language, time packages supplies functionality for determining as well as viewing time. The MarshalJSON() function in Go language is used to implement the json.Marshaler interface. And the time here is a quoted-string which is in RFC 3339 format along with the sub-second precision attached if available. 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": 26158, "s": 26150, "text": "Syntax:" }, { "code": null, "e": 26203, "s": 26158, "text": "func (t Time) MarshalJSON() ([]byte, error)\n" }, { "code": null, "e": 26313, "s": 26203, "text": "Here, “t” is the stated time and two values of type “byte” and “error” are returned as output in this method." }, { "code": null, "e": 26470, "s": 26313, "text": "Return value: It returns a byte slice that represents JSON encoding and it also returns an error occurred but if there are no errors then “nil” is returned." }, { "code": null, "e": 26481, "s": 26470, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// Time.MarshalJSON() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Defining t for MarshalJSON method t := time.Date(2014, 11, 10, 14, 30, 12, 05, time.UTC) // Calling MarshalJSON() method encoding, error := t.MarshalJSON() // Prints JSON's encoding fmt.Printf(\"JSON's encoding: %v\\n\", encoding) // Prints error fmt.Printf(\"Error occurred: %v\\n\", error)}", "e": 26999, "s": 26481, "text": null }, { "code": null, "e": 27007, "s": 26999, "text": "Output:" }, { "code": null, "e": 27143, "s": 27007, "text": "JSON’s encoding: [34 50 48 49 52 45 49 49 45 49 48 84 49 52 58 51 48 58 49 50 46 48 48 48 48 48 48 48 48 53 90 34]Error occurred: <nil>" }, { "code": null, "e": 27154, "s": 27143, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// Time.MarshalJSON() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Defining t for MarshalJSON method t := time.Date(2022, 45, 67, 88, 67, 76, 903, time.UTC) // Calling MarshalJSON() method encoding, error := t.MarshalJSON() // Prints JSON's encoding fmt.Printf(\"JSON's encoding: %v\\n\", encoding) // Prints error fmt.Printf(\"Error occurred: %v\\n\", error)}", "e": 27673, "s": 27154, "text": null }, { "code": null, "e": 27681, "s": 27673, "text": "Output:" }, { "code": null, "e": 27817, "s": 27681, "text": "JSON’s encoding: [34 50 48 50 53 45 49 49 45 48 57 84 49 55 58 48 56 58 49 54 46 48 48 48 48 48 48 57 48 51 90 34]Error occurred: <nil>" }, { "code": null, "e": 27938, "s": 27817, "text": "Here, the “t” stated in the above code has values that are outside usual range but they are normalized while conversion." }, { "code": null, "e": 27950, "s": 27938, "text": "GoLang-time" }, { "code": null, "e": 27962, "s": 27950, "text": "Go Language" }, { "code": null, "e": 28060, "s": 27962, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28106, "s": 28060, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 28135, "s": 28106, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 28160, "s": 28135, "text": "Time Durations in Golang" }, { "code": null, "e": 28178, "s": 28160, "text": "Strings in Golang" }, { "code": null, "e": 28199, "s": 28178, "text": "Structures in Golang" }, { "code": null, "e": 28254, "s": 28199, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 28269, "s": 28254, "text": "Rune in Golang" }, { "code": null, "e": 28293, "s": 28269, "text": "Defer Keyword in Golang" }, { "code": null, "e": 28314, "s": 28293, "text": "Loops in Go Language" } ]
Don't Care (X) Conditions in K-Maps - GeeksforGeeks
27 Oct, 2021 One of the very significant and useful concepts in simplifying the output expression using K-Map is the concept of “Don’t Care”. The “Don’t Care” conditions allow us to replace the empty cell of a K-Map to form a grouping of the variables which is larger than that of forming groups without don’t care. While forming groups of cells, we can consider a “Don’t Care” cell as 1 or 0 or we can also ignore that cell. Therefore, the “Don’t Care” condition can help us to form a larger group of cells. A Don’t Care cell can be represented by a cross(X) or minus(-) or phi(Φ) in K-Maps representing an invalid combination. For example, in the Excess-3 code system, the states 0000, 0001, 0010, 1101, 1110, and 1111 are invalid or unspecified. These states are called don’t cares. A standard SOP function having don’t cares can be converted into a POS expression by keeping don’t cares as they are, and writing the missing minterms of the SOP form as the maxterm of POS form. Similarly, a POS function having don’t cares can be converted to SOP form keeping the don’t cares as they are and writing the missing maxterms of the POS expression as the minterms of SOP expression. Example-1: Minimise the following function in SOP minimal form using K-Maps: f = m(1, 5, 6, 11, 12, 13, 14) + d(4) Explanation: The SOP K-map for the given expression is: Therefore, SOP minimal is, f = BC' + BCD' + A'C'D + AB'CD Example-2: Minimise the following function in POS minimal form using K-Maps: F(A, B, C, D) = m(0, 1, 2, 3, 4, 5) + d(10, 11, 12, 13, 14, 15) Explanation: Writing the given expression in POS form: F(A, B, C, D) = M(6, 7, 8, 9) + d(12, 13, 14, 15) The POS K-map for the given expression is: Therefore, POS minimal is, F = (A'+ C)(B' + C') Example-3: Minimise the following function in SOP minimal form using K-Maps: F(A, B, C, D) = m(1, 2, 6, 7, 8, 13, 14, 15) + d(0, 3, 5, 12) Explanation: The SOP K-map for the given expression is: Therefore, f = AC'D' + A'D + A'C + AB Significance of “Don’t Care” Conditions: Don’t Care conditions has the following significance in designing of the digital circuits: Simplification of the output: These conditions denotes inputs that are invalid for a given digital circuit. Thus, they can used to further simplify the boolean output expression of a digital circuit. Reduction in number of gates required: Simplification of the expression reduces the number of gates to be used for implementing the given expression. Therefore, don’t cares make the digital circuit design more economical. Reduced Power Consumption: While grouping the terms long with don’t cares reduces switching of the states. This decreases the memory space that is required to represent a given digital circuit which in turn results in less power consumption. Represent Invalid States in Code Converters: These are used in code converters. For example- In design of 4-bit BCD-to-XS-3 code converter, the input combinations 1010, 1011, 1100, 1101, 1110, and 1111 are don’t cares. Prevention of Hazards in Digital Circuits: Don’t cares also prevents hazards in digital systems. Simplification of the output: These conditions denotes inputs that are invalid for a given digital circuit. Thus, they can used to further simplify the boolean output expression of a digital circuit. Reduction in number of gates required: Simplification of the expression reduces the number of gates to be used for implementing the given expression. Therefore, don’t cares make the digital circuit design more economical. Reduced Power Consumption: While grouping the terms long with don’t cares reduces switching of the states. This decreases the memory space that is required to represent a given digital circuit which in turn results in less power consumption. Represent Invalid States in Code Converters: These are used in code converters. For example- In design of 4-bit BCD-to-XS-3 code converter, the input combinations 1010, 1011, 1100, 1101, 1110, and 1111 are don’t cares. Prevention of Hazards in Digital Circuits: Don’t cares also prevents hazards in digital systems. vaishnavtannu arpitdixitc23 avinashdubeyg2001 Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Shift Registers in Digital Logic Difference between Unipolar, Polar and Bipolar Line Coding Schemes Flip-flop types, their Conversion and Applications Counters in Digital Logic Introduction to memory and memory units Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 25429, "s": 25401, "text": "\n27 Oct, 2021" }, { "code": null, "e": 25926, "s": 25429, "text": "One of the very significant and useful concepts in simplifying the output expression using K-Map is the concept of “Don’t Care”. The “Don’t Care” conditions allow us to replace the empty cell of a K-Map to form a grouping of the variables which is larger than that of forming groups without don’t care. While forming groups of cells, we can consider a “Don’t Care” cell as 1 or 0 or we can also ignore that cell. Therefore, the “Don’t Care” condition can help us to form a larger group of cells. " }, { "code": null, "e": 26203, "s": 25926, "text": "A Don’t Care cell can be represented by a cross(X) or minus(-) or phi(Φ) in K-Maps representing an invalid combination. For example, in the Excess-3 code system, the states 0000, 0001, 0010, 1101, 1110, and 1111 are invalid or unspecified. These states are called don’t cares." }, { "code": null, "e": 26599, "s": 26203, "text": "A standard SOP function having don’t cares can be converted into a POS expression by keeping don’t cares as they are, and writing the missing minterms of the SOP form as the maxterm of POS form. Similarly, a POS function having don’t cares can be converted to SOP form keeping the don’t cares as they are and writing the missing maxterms of the POS expression as the minterms of SOP expression. " }, { "code": null, "e": 26677, "s": 26599, "text": "Example-1: Minimise the following function in SOP minimal form using K-Maps: " }, { "code": null, "e": 26716, "s": 26677, "text": "f = m(1, 5, 6, 11, 12, 13, 14) + d(4) " }, { "code": null, "e": 26774, "s": 26716, "text": "Explanation: The SOP K-map for the given expression is: " }, { "code": null, "e": 26803, "s": 26774, "text": "Therefore, SOP minimal is, " }, { "code": null, "e": 26834, "s": 26803, "text": "f = BC' + BCD' + A'C'D + AB'CD" }, { "code": null, "e": 26912, "s": 26834, "text": "Example-2: Minimise the following function in POS minimal form using K-Maps: " }, { "code": null, "e": 26977, "s": 26912, "text": "F(A, B, C, D) = m(0, 1, 2, 3, 4, 5) + d(10, 11, 12, 13, 14, 15) " }, { "code": null, "e": 27034, "s": 26977, "text": "Explanation: Writing the given expression in POS form: " }, { "code": null, "e": 27085, "s": 27034, "text": "F(A, B, C, D) = M(6, 7, 8, 9) + d(12, 13, 14, 15) " }, { "code": null, "e": 27129, "s": 27085, "text": "The POS K-map for the given expression is: " }, { "code": null, "e": 27156, "s": 27129, "text": "Therefore, POS minimal is," }, { "code": null, "e": 27178, "s": 27156, "text": "F = (A'+ C)(B' + C') " }, { "code": null, "e": 27318, "s": 27178, "text": "Example-3: Minimise the following function in SOP minimal form using K-Maps: F(A, B, C, D) = m(1, 2, 6, 7, 8, 13, 14, 15) + d(0, 3, 5, 12) " }, { "code": null, "e": 27376, "s": 27318, "text": "Explanation: The SOP K-map for the given expression is: " }, { "code": null, "e": 27389, "s": 27376, "text": "Therefore, " }, { "code": null, "e": 27417, "s": 27389, "text": "f = AC'D' + A'D + A'C + AB " }, { "code": null, "e": 27551, "s": 27417, "text": "Significance of “Don’t Care” Conditions: Don’t Care conditions has the following significance in designing of the digital circuits: " }, { "code": null, "e": 28537, "s": 27551, "text": "Simplification of the output: These conditions denotes inputs that are invalid for a given digital circuit. Thus, they can used to further simplify the boolean output expression of a digital circuit. Reduction in number of gates required: Simplification of the expression reduces the number of gates to be used for implementing the given expression. Therefore, don’t cares make the digital circuit design more economical. Reduced Power Consumption: While grouping the terms long with don’t cares reduces switching of the states. This decreases the memory space that is required to represent a given digital circuit which in turn results in less power consumption. Represent Invalid States in Code Converters: These are used in code converters. For example- In design of 4-bit BCD-to-XS-3 code converter, the input combinations 1010, 1011, 1100, 1101, 1110, and 1111 are don’t cares. Prevention of Hazards in Digital Circuits: Don’t cares also prevents hazards in digital systems. " }, { "code": null, "e": 28739, "s": 28537, "text": "Simplification of the output: These conditions denotes inputs that are invalid for a given digital circuit. Thus, they can used to further simplify the boolean output expression of a digital circuit. " }, { "code": null, "e": 28963, "s": 28739, "text": "Reduction in number of gates required: Simplification of the expression reduces the number of gates to be used for implementing the given expression. Therefore, don’t cares make the digital circuit design more economical. " }, { "code": null, "e": 29207, "s": 28963, "text": "Reduced Power Consumption: While grouping the terms long with don’t cares reduces switching of the states. This decreases the memory space that is required to represent a given digital circuit which in turn results in less power consumption. " }, { "code": null, "e": 29428, "s": 29207, "text": "Represent Invalid States in Code Converters: These are used in code converters. For example- In design of 4-bit BCD-to-XS-3 code converter, the input combinations 1010, 1011, 1100, 1101, 1110, and 1111 are don’t cares. " }, { "code": null, "e": 29527, "s": 29428, "text": "Prevention of Hazards in Digital Circuits: Don’t cares also prevents hazards in digital systems. " }, { "code": null, "e": 29541, "s": 29527, "text": "vaishnavtannu" }, { "code": null, "e": 29555, "s": 29541, "text": "arpitdixitc23" }, { "code": null, "e": 29573, "s": 29555, "text": "avinashdubeyg2001" }, { "code": null, "e": 29608, "s": 29573, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 29616, "s": 29608, "text": "GATE CS" }, { "code": null, "e": 29714, "s": 29616, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29747, "s": 29714, "text": "Shift Registers in Digital Logic" }, { "code": null, "e": 29814, "s": 29747, "text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes" }, { "code": null, "e": 29865, "s": 29814, "text": "Flip-flop types, their Conversion and Applications" }, { "code": null, "e": 29891, "s": 29865, "text": "Counters in Digital Logic" }, { "code": null, "e": 29931, "s": 29891, "text": "Introduction to memory and memory units" }, { "code": null, "e": 29951, "s": 29931, "text": "Layers of OSI Model" }, { "code": null, "e": 29975, "s": 29951, "text": "ACID Properties in DBMS" }, { "code": null, "e": 29988, "s": 29975, "text": "TCP/IP Model" }, { "code": null, "e": 30015, "s": 29988, "text": "Types of Operating Systems" } ]
Mapping over Matrices in Julia - GeeksforGeeks
02 Jul, 2020 Julia is termed to be a fresh approach to Parallel Computing. Julia is a high-level and dynamic programming language for interactive use. Julia combines the implementation of scalar environments such as R and Python with the speed of dynamic programming languages like Java and C++ to provide a systematic solution for big data and analytics problems. As every programming language has its environment to develop dynamic models. Apparently Julia also features an interactive command shell REPL (REPL stands for read-eval-print-loop). Example: Basic functionInput: Julia> a(x) = 2x^3+1; f(x, y) = 1 + a(x)y Julia> println(“Hello World!”, “ I’m “, f(2, 1), “Welcome to Julia!”) Here, We’ve declared a(x) where x is the parameter of the function f(x, y). We have allocated an operation (2x^3+1) to a(x). Hence ” ^ ” operator performs multiplication. Now there is a function f(x, y) which gives us a result by performing a specific operation declared when parameter values are passed. Output: Hello World! I’m 18 Welcome to Julia! Mapping the matrices in Julia is nothing but performing a function or an operation to each and every element in the matrix. For example, Let us create a matrix in Julia and understand the terms in a lucid way. julia> variable = [1 2 3 4 5 6] 1×6 Array{Int64, 2}: 1 2 3 4 5 6 Here, we have created a 1×6 matrix(consists of 1 row and 6 columns). We can also create matrices of different dimensions and with varied range of datatypes(i.e float, int, double) without specifying the type while declaring the value. In the above picture, a matrix of order 3×4 of the integer data type is created. In the above picture, the code is executed in the Julia command line where I have created a matrix of order 3×3. We have performed the map function in the above picture to the matrix c. Here x is a variable which stores each and every value present in the matrix c. Let us consider the first element in the matrix ‘ c ‘ ( i.e, 1) which is now stored in x (x = 1). ( x -> x*2 ) explains us the variable x is assigning the value of x*2. Hence we explain it as (x = 1* 2) Exactly this operation is done to each individual value present in the matrix. Hence, we obtain the result after performing an operation using map function. In the above-explained examples, we have seen operations performed on a single matrix(i.e, c). Now let us understand the mapping technique by performing the operations on two different matrices. julia> f = [1 2 3; 1 2 3; 1 2 3] 3×3 Array{Int64, 2}: 1 2 3 1 2 3 1 2 3 Created a matrix ‘ f ‘of order 3×3. julia> c = [2 1 1; 1 1 2; 2 1 2] 3×3 Array{Int64, 2}: 2 1 1 1 1 2 2 1 2 Created a matrix ‘ c ‘of order 3×3. julia> map(x -> f*x*2, c) 3×3 Array{Array{Int64, 2}, 2}: [4 8 12; 4 8 12; 4 8 12] [2 4 6; 2 4 6; 2 4 6] [2 4 6; 2 4 6; 2 4 6] [2 4 6; 2 4 6; 2 4 6] [2 4 6; 2 4 6; 2 4 6] [4 8 12; 4 8 12; 4 8 12] [4 8 12; 4 8 12; 4 8 12] [2 4 6; 2 4 6; 2 4 6] [4 8 12; 4 8 12; 4 8 12] We’ve used the map function to perform an operation on the matrices(f & c). x is a variable which stores every single value of c per operation. Now let’s try to understand the logic in the above code. Consider the first value in ‘ c ‘ matrix which is considered to be ‘ 2 ‘. The integer ‘ 2 ‘ which is the first element in the matrix c is now stored in x (i.e, (x -> f*x*2 ) == (x = f*2*2) ) The very next operation is to multiply each and every element of matrix ‘ f ‘ to the above mentioned step (x = f*2*2) Here, we can see the first element in the matrix ‘ c ‘(i.e, 2) multiplied with all the values of matrix ‘ f ‘ in a row wise manner. Apparently, after multiplying the very first element in matrix ‘ c ‘(i.e, 2). Now the compiler shifts the value of ‘ x ‘ to the very next value (row wise consideration) present in matrix ‘ c ‘ (i.e, 1) Hence, (i.e, (x -> f*x*2 ) == (x = f*2*2) ) becomes (i.e, (x -> f*x*2 ) == (x = f*1*2) ). and every element in matrix ‘ f ‘ will be multiplied with value ‘ 1 ‘ The same process repeats so on and so forth. The final executed output image. Conclusion: Hence, we now got to know what is a mapping function in Julia and what operations are performed and the executed using this function in Julia. We also executed the function to map over the matrices. Julia-matrix Picked Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vectors in Julia Getting rounded value of a number in Julia - round() Method Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Storing Output on a File in Julia Formatting of Strings in Julia Creating array with repeated elements in Julia - repeat() Method Reshaping array dimensions in Julia | Array reshape() Method while loop in Julia Taking Input from Users in Julia Get array dimensions and size of a dimension in Julia - size() Method
[ { "code": null, "e": 25513, "s": 25485, "text": "\n02 Jul, 2020" }, { "code": null, "e": 25865, "s": 25513, "text": "Julia is termed to be a fresh approach to Parallel Computing. Julia is a high-level and dynamic programming language for interactive use. Julia combines the implementation of scalar environments such as R and Python with the speed of dynamic programming languages like Java and C++ to provide a systematic solution for big data and analytics problems." }, { "code": null, "e": 26047, "s": 25865, "text": "As every programming language has its environment to develop dynamic models. Apparently Julia also features an interactive command shell REPL (REPL stands for read-eval-print-loop)." }, { "code": null, "e": 26077, "s": 26047, "text": "Example: Basic functionInput:" }, { "code": null, "e": 26190, "s": 26077, "text": "Julia> a(x) = 2x^3+1; f(x, y) = 1 + a(x)y\nJulia> println(“Hello World!”, “ I’m “, f(2, 1), “Welcome to Julia!”)\n" }, { "code": null, "e": 26496, "s": 26190, "text": "Here, We’ve declared a(x) where x is the parameter of the function f(x, y). We have allocated an operation (2x^3+1) to a(x). Hence ” ^ ” operator performs multiplication. Now there is a function f(x, y) which gives us a result by performing a specific operation declared when parameter values are passed." }, { "code": null, "e": 26504, "s": 26496, "text": "Output:" }, { "code": null, "e": 26542, "s": 26504, "text": "Hello World! I’m 18 Welcome to Julia!" }, { "code": null, "e": 26666, "s": 26542, "text": "Mapping the matrices in Julia is nothing but performing a function or an operation to each and every element in the matrix." }, { "code": null, "e": 26752, "s": 26666, "text": "For example, Let us create a matrix in Julia and understand the terms in a lucid way." }, { "code": null, "e": 26823, "s": 26752, "text": "julia> variable = [1 2 3 4 5 6]\n1×6 Array{Int64, 2}:\n1 2 3 4 5 6\n" }, { "code": null, "e": 27058, "s": 26823, "text": "Here, we have created a 1×6 matrix(consists of 1 row and 6 columns). We can also create matrices of different dimensions and with varied range of datatypes(i.e float, int, double) without specifying the type while declaring the value." }, { "code": null, "e": 27139, "s": 27058, "text": "In the above picture, a matrix of order 3×4 of the integer data type is created." }, { "code": null, "e": 27252, "s": 27139, "text": "In the above picture, the code is executed in the Julia command line where I have created a matrix of order 3×3." }, { "code": null, "e": 27405, "s": 27252, "text": "We have performed the map function in the above picture to the matrix c. Here x is a variable which stores each and every value present in the matrix c." }, { "code": null, "e": 27503, "s": 27405, "text": "Let us consider the first element in the matrix ‘ c ‘ ( i.e, 1) which is now stored in x (x = 1)." }, { "code": null, "e": 27608, "s": 27503, "text": "( x -> x*2 ) explains us the variable x is assigning the value of x*2. Hence we explain it as (x = 1* 2)" }, { "code": null, "e": 27687, "s": 27608, "text": "Exactly this operation is done to each individual value present in the matrix." }, { "code": null, "e": 27765, "s": 27687, "text": "Hence, we obtain the result after performing an operation using map function." }, { "code": null, "e": 27960, "s": 27765, "text": "In the above-explained examples, we have seen operations performed on a single matrix(i.e, c). Now let us understand the mapping technique by performing the operations on two different matrices." }, { "code": null, "e": 28042, "s": 27960, "text": "julia> f = [1 2 3; 1 2 3; 1 2 3]\n3×3 Array{Int64, 2}:\n 1 2 3\n 1 2 3\n 1 2 3\n" }, { "code": null, "e": 28078, "s": 28042, "text": "Created a matrix ‘ f ‘of order 3×3." }, { "code": null, "e": 28160, "s": 28078, "text": "julia> c = [2 1 1; 1 1 2; 2 1 2]\n3×3 Array{Int64, 2}:\n 2 1 1\n 1 1 2\n 2 1 2\n" }, { "code": null, "e": 28196, "s": 28160, "text": "Created a matrix ‘ c ‘of order 3×3." }, { "code": null, "e": 28476, "s": 28196, "text": "julia> map(x -> f*x*2, c)\n3×3 Array{Array{Int64, 2}, 2}:\n [4 8 12; 4 8 12; 4 8 12] [2 4 6; 2 4 6; 2 4 6] [2 4 6; 2 4 6; 2 4 6]\n [2 4 6; 2 4 6; 2 4 6] [2 4 6; 2 4 6; 2 4 6] [4 8 12; 4 8 12; 4 8 12]\n [4 8 12; 4 8 12; 4 8 12] [2 4 6; 2 4 6; 2 4 6] [4 8 12; 4 8 12; 4 8 12]\n" }, { "code": null, "e": 28552, "s": 28476, "text": "We’ve used the map function to perform an operation on the matrices(f & c)." }, { "code": null, "e": 28620, "s": 28552, "text": "x is a variable which stores every single value of c per operation." }, { "code": null, "e": 28677, "s": 28620, "text": "Now let’s try to understand the logic in the above code." }, { "code": null, "e": 28751, "s": 28677, "text": "Consider the first value in ‘ c ‘ matrix which is considered to be ‘ 2 ‘." }, { "code": null, "e": 28868, "s": 28751, "text": "The integer ‘ 2 ‘ which is the first element in the matrix c is now stored in x (i.e, (x -> f*x*2 ) == (x = f*2*2) )" }, { "code": null, "e": 28986, "s": 28868, "text": "The very next operation is to multiply each and every element of matrix ‘ f ‘ to the above mentioned step (x = f*2*2)" }, { "code": null, "e": 29118, "s": 28986, "text": "Here, we can see the first element in the matrix ‘ c ‘(i.e, 2) multiplied with all the values of matrix ‘ f ‘ in a row wise manner." }, { "code": null, "e": 29320, "s": 29118, "text": "Apparently, after multiplying the very first element in matrix ‘ c ‘(i.e, 2). Now the compiler shifts the value of ‘ x ‘ to the very next value (row wise consideration) present in matrix ‘ c ‘ (i.e, 1)" }, { "code": null, "e": 29480, "s": 29320, "text": "Hence, (i.e, (x -> f*x*2 ) == (x = f*2*2) ) becomes (i.e, (x -> f*x*2 ) == (x = f*1*2) ). and every element in matrix ‘ f ‘ will be multiplied with value ‘ 1 ‘" }, { "code": null, "e": 29525, "s": 29480, "text": "The same process repeats so on and so forth." }, { "code": null, "e": 29558, "s": 29525, "text": "The final executed output image." }, { "code": null, "e": 29570, "s": 29558, "text": "Conclusion:" }, { "code": null, "e": 29769, "s": 29570, "text": "Hence, we now got to know what is a mapping function in Julia and what operations are performed and the executed using this function in Julia. We also executed the function to map over the matrices." }, { "code": null, "e": 29782, "s": 29769, "text": "Julia-matrix" }, { "code": null, "e": 29789, "s": 29782, "text": "Picked" }, { "code": null, "e": 29795, "s": 29789, "text": "Julia" }, { "code": null, "e": 29893, "s": 29795, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29910, "s": 29893, "text": "Vectors in Julia" }, { "code": null, "e": 29970, "s": 29910, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 30043, "s": 29970, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 30077, "s": 30043, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 30108, "s": 30077, "text": "Formatting of Strings in Julia" }, { "code": null, "e": 30173, "s": 30108, "text": "Creating array with repeated elements in Julia - repeat() Method" }, { "code": null, "e": 30234, "s": 30173, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 30254, "s": 30234, "text": "while loop in Julia" }, { "code": null, "e": 30287, "s": 30254, "text": "Taking Input from Users in Julia" } ]
Workaround to backdrop-filter in CSS - GeeksforGeeks
15 Sep, 2020 The CSS backdrop-filter property is used to apply effects to the area behind an element. This is unlike the filter property where it applies the effect to the whole element. It can be used to eliminate the use of an extra element to style the background separately. Syntax: .element { backdrop-filter: filter-function | none } Approach:Creating overlays on top of images (and videos) often entails using some sort of drop shadow effect. For example, using white icons requires a shadow to be visible against near-white backgrounds. With backdrop-filter, you can create overlays that adapt to the background color instead of using a shadow. There can be many filter functions: blur() – It is used to apply a Gaussian blur to the image.Example:<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; align-items: center; justify-content: center; height: 100px; width: 250px; } .foreground { backdrop-filter: blur(2px); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:brightness(): It is used to make the image lighter or darker (0% – darker and 100% – brighter ).<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: brightness(25%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:contrast() – It is used to set the contrast of the image (100% – original and 0% darker)<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: contrast(20%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:drop-shadow() – It is used to apply a drop shadow effect to the element.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: drop-shadow(20px 10px red); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:grayscale() – It is used to convert the colors of the image into black and white. A value of 0% indicates the original image and 100% will indicate a completely black and white image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: grayscale(75%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:hue-rotate() – It is used to apply a hue rotation to the image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: hue-rotate(180deg); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:invert() – It is used to invert the image. The default value is 0% which represents the original image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: invert(100%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:opacity() – It is used to set the opacity of the image. The default value is 0% which indicates that the image is completely transparent.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: opacity(50%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:saturate() – It is used to set the saturation of the element. The default value is 100% which indicates the original image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: saturate(50%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:sepia() – It is used to convert the image to sepia giving it a warmer appearance. A 0% value represents the original image and 100% represents a completely sepia image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: sepia(100%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: blur() – It is used to apply a Gaussian blur to the image.Example:<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; align-items: center; justify-content: center; height: 100px; width: 250px; } .foreground { backdrop-filter: blur(2px); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: <!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; align-items: center; justify-content: center; height: 100px; width: 250px; } .foreground { backdrop-filter: blur(2px); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: brightness(): It is used to make the image lighter or darker (0% – darker and 100% – brighter ).<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: brightness(25%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: <!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: brightness(25%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: contrast() – It is used to set the contrast of the image (100% – original and 0% darker)<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: contrast(20%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: <!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: contrast(20%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: drop-shadow() – It is used to apply a drop shadow effect to the element.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: drop-shadow(20px 10px red); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: <!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: drop-shadow(20px 10px red); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: grayscale() – It is used to convert the colors of the image into black and white. A value of 0% indicates the original image and 100% will indicate a completely black and white image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: grayscale(75%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: <!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: grayscale(75%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: hue-rotate() – It is used to apply a hue rotation to the image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: hue-rotate(180deg); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: <!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: hue-rotate(180deg); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: invert() – It is used to invert the image. The default value is 0% which represents the original image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: invert(100%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: <!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: invert(100%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: opacity() – It is used to set the opacity of the image. The default value is 0% which indicates that the image is completely transparent.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: opacity(50%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: <!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: opacity(50%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: saturate() – It is used to set the saturation of the element. The default value is 100% which indicates the original image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: saturate(50%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: <!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: saturate(50%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: sepia() – It is used to convert the image to sepia giving it a warmer appearance. A 0% value represents the original image and 100% represents a completely sepia image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: sepia(100%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: <!DOCTYPE html> <html> <head> <style> .container { background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: sepia(100%); padding: 2px; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT: CSS-Misc Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS How to set space between the flexbox ? Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26621, "s": 26593, "text": "\n15 Sep, 2020" }, { "code": null, "e": 26887, "s": 26621, "text": "The CSS backdrop-filter property is used to apply effects to the area behind an element. This is unlike the filter property where it applies the effect to the whole element. It can be used to eliminate the use of an extra element to style the background separately." }, { "code": null, "e": 26895, "s": 26887, "text": "Syntax:" }, { "code": null, "e": 26951, "s": 26895, "text": ".element {\n backdrop-filter: filter-function | none\n}\n" }, { "code": null, "e": 27264, "s": 26951, "text": "Approach:Creating overlays on top of images (and videos) often entails using some sort of drop shadow effect. For example, using white icons requires a shadow to be visible against near-white backgrounds. With backdrop-filter, you can create overlays that adapt to the background color instead of using a shadow." }, { "code": null, "e": 27300, "s": 27264, "text": "There can be many filter functions:" }, { "code": null, "e": 36357, "s": 27300, "text": "blur() – It is used to apply a Gaussian blur to the image.Example:<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; align-items: center; justify-content: center; height: 100px; width: 250px; } .foreground { backdrop-filter: blur(2px); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:brightness(): It is used to make the image lighter or darker (0% – darker and 100% – brighter ).<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: brightness(25%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:contrast() – It is used to set the contrast of the image (100% – original and 0% darker)<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: contrast(20%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:drop-shadow() – It is used to apply a drop shadow effect to the element.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: drop-shadow(20px 10px red); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:grayscale() – It is used to convert the colors of the image into black and white. A value of 0% indicates the original image and 100% will indicate a completely black and white image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: grayscale(75%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:hue-rotate() – It is used to apply a hue rotation to the image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: hue-rotate(180deg); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:invert() – It is used to invert the image. The default value is 0% which represents the original image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: invert(100%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:opacity() – It is used to set the opacity of the image. The default value is 0% which indicates that the image is completely transparent.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: opacity(50%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:saturate() – It is used to set the saturation of the element. The default value is 100% which indicates the original image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: saturate(50%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:sepia() – It is used to convert the image to sepia giving it a warmer appearance. A 0% value represents the original image and 100% represents a completely sepia image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: sepia(100%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:" }, { "code": null, "e": 37185, "s": 36357, "text": "blur() – It is used to apply a Gaussian blur to the image.Example:<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; align-items: center; justify-content: center; height: 100px; width: 250px; } .foreground { backdrop-filter: blur(2px); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:" }, { "code": "<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; align-items: center; justify-content: center; height: 100px; width: 250px; } .foreground { backdrop-filter: blur(2px); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> ", "e": 37940, "s": 37185, "text": null }, { "code": null, "e": 37948, "s": 37940, "text": "OUTPUT:" }, { "code": null, "e": 38851, "s": 37948, "text": "brightness(): It is used to make the image lighter or darker (0% – darker and 100% – brighter ).<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: brightness(25%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:" }, { "code": "<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: brightness(25%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> ", "e": 39651, "s": 38851, "text": null }, { "code": null, "e": 39659, "s": 39651, "text": "OUTPUT:" }, { "code": null, "e": 40545, "s": 39659, "text": "contrast() – It is used to set the contrast of the image (100% – original and 0% darker)<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: contrast(20%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:" }, { "code": "<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: contrast(20%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> ", "e": 41336, "s": 40545, "text": null }, { "code": null, "e": 41344, "s": 41336, "text": "OUTPUT:" }, { "code": null, "e": 42232, "s": 41344, "text": "drop-shadow() – It is used to apply a drop shadow effect to the element.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: drop-shadow(20px 10px red); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:" }, { "code": "<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: drop-shadow(20px 10px red); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> ", "e": 43041, "s": 42232, "text": null }, { "code": null, "e": 43049, "s": 43041, "text": "OUTPUT:" }, { "code": null, "e": 44037, "s": 43049, "text": "grayscale() – It is used to convert the colors of the image into black and white. A value of 0% indicates the original image and 100% will indicate a completely black and white image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: grayscale(75%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:" }, { "code": "<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: grayscale(75%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> ", "e": 44835, "s": 44037, "text": null }, { "code": null, "e": 44843, "s": 44835, "text": "OUTPUT:" }, { "code": null, "e": 45715, "s": 44843, "text": "hue-rotate() – It is used to apply a hue rotation to the image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: hue-rotate(180deg); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:" }, { "code": "<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: hue-rotate(180deg); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> ", "e": 46517, "s": 45715, "text": null }, { "code": null, "e": 46525, "s": 46517, "text": "OUTPUT:" }, { "code": null, "e": 47430, "s": 46525, "text": "invert() – It is used to invert the image. The default value is 0% which represents the original image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: invert(100%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:" }, { "code": "<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: invert(100%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> ", "e": 48225, "s": 47430, "text": null }, { "code": null, "e": 48233, "s": 48225, "text": "OUTPUT:" }, { "code": null, "e": 49173, "s": 48233, "text": "opacity() – It is used to set the opacity of the image. The default value is 0% which indicates that the image is completely transparent.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: opacity(50%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:" }, { "code": "<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: opacity(50%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> ", "e": 49969, "s": 49173, "text": null }, { "code": null, "e": 49977, "s": 49969, "text": "OUTPUT:" }, { "code": null, "e": 50904, "s": 49977, "text": "saturate() – It is used to set the saturation of the element. The default value is 100% which indicates the original image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: saturate(50%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:" }, { "code": "<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: saturate(50%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> ", "e": 51701, "s": 50904, "text": null }, { "code": null, "e": 51709, "s": 51701, "text": "OUTPUT:" }, { "code": null, "e": 52638, "s": 51709, "text": "sepia() – It is used to convert the image to sepia giving it a warmer appearance. A 0% value represents the original image and 100% represents a completely sepia image.<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: sepia(100%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> OUTPUT:" }, { "code": "<!DOCTYPE html> <html> <head> <style> .container { background-image: url( \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: sepia(100%); padding: 2px; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div> </body> </html> ", "e": 53392, "s": 52638, "text": null }, { "code": null, "e": 53400, "s": 53392, "text": "OUTPUT:" }, { "code": null, "e": 53409, "s": 53400, "text": "CSS-Misc" }, { "code": null, "e": 53416, "s": 53409, "text": "Picked" }, { "code": null, "e": 53420, "s": 53416, "text": "CSS" }, { "code": null, "e": 53437, "s": 53420, "text": "Web Technologies" }, { "code": null, "e": 53535, "s": 53437, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 53572, "s": 53535, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 53611, "s": 53572, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 53640, "s": 53611, "text": "Form validation using jQuery" }, { "code": null, "e": 53682, "s": 53640, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 53717, "s": 53682, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 53757, "s": 53717, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 53790, "s": 53757, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 53835, "s": 53790, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 53878, "s": 53835, "text": "How to fetch data from an API in ReactJS ?" } ]
Output of C programs | Set 57 (for loop) - GeeksforGeeks
02 Oct, 2017 Prerequisite : for loop Q.1 What is the output of this program? #include <iostream>using namespace std;int main(){ for (5; 2; 2) printf("Hello\n"); return 0;} Optionsa) compilation errorb) Helloc) infinite loopd) none of the above ans: c Explanation : Putting a non zero value in condition part makes it infinite. Q.2 What is the output of this program? #include <iostream>using namespace std;int main(){ static int i; for (i++; ++i; i++) { printf("%d ", i); if (i == 6) break; } return 0;} OptionsOptions:a) 2 4 6b) compilation errorc) garbage valued) no output ans : a Explanation : After first iteration, program looks like (0, 2, 2). It breaks when i = 6. Q.3 What is the output of this program? #include <iostream>using namespace std;int fun();int main(){ for (fun(); fun(); fun()) { printf("%d ", fun()); } return 0;}int fun(){ int static num = 10; return num--;} Optionsa) compilation errorb) can’t be predictedc) 8 5 2d) none of the above ans: c Explanation : At first iteration: for(10; 9; fun()) //condition true printf("%d", 8) //8 prints At second iteration: for(10; fun(); 7) for(7; 6 ;fun()) //condition true printf("%d", 5) //5 prints At third iteration: for(7; fun(); 4) for(4; 3; fun()) //condition true printf("%d", 2) //2 prints At fourth iteration: for(4; fun(); 1) for(1; 0; fun()) //condition false Program terminates Q.4 What is the output of this program? #include <iostream>using namespace std;int main(){ for (;;) printf("%d ", 10); return 0;} Optionsa) compilation errorb) run time errorc) 10d) Infinite loop ans : d Explanation : Since no condition is provided so loop runs infinitely. Q.5 What is the output of this program? #include <iostream>using namespace std;int main(){ char i = 0; for (; i++; printf("%d", i)) ; printf("%d", i); return 0;} Options a) 0b) 1c) Infinite loopd) compilation error ans: b Explanation : The following condition fails for first time so loop terminates and value of i is incremented to 1. for(; 0; printf("%d", i)) Q.6 What is the output of this program? #include <iostream>using namespace std;int main(){ int i; for (i = 0; i < 0, 5; i++) printf("%d ", i); return 0;} Optionsa) errorb) 1, 3c) program never endsd) none of these ans: c Explanation :-Considers two conditions:(a)i<0 fails for first iteration(b)5 in condition part makes it infinite loop as it never becomes 0. This article is contributed by Pragya Singh. 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. C-Loops & Control Statements C-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Output of Java program | Set 18 (Overriding) Output of Java Program | Set 11 Output of Java programs | Set 13 (Collections) Output of C++ programs | Set 34 (File Handling) Different ways to copy a string in C/C++ Output of Java Program | Set 3 Runtime Errors Output of Java program | Set 28 Output of Java program | Set 5 Output of Java Programs | Set 12
[ { "code": null, "e": 25811, "s": 25783, "text": "\n02 Oct, 2017" }, { "code": null, "e": 25835, "s": 25811, "text": "Prerequisite : for loop" }, { "code": null, "e": 25875, "s": 25835, "text": "Q.1 What is the output of this program?" }, { "code": "#include <iostream>using namespace std;int main(){ for (5; 2; 2) printf(\"Hello\\n\"); return 0;}", "e": 25983, "s": 25875, "text": null }, { "code": null, "e": 26055, "s": 25983, "text": "Optionsa) compilation errorb) Helloc) infinite loopd) none of the above" }, { "code": null, "e": 26062, "s": 26055, "text": "ans: c" }, { "code": null, "e": 26138, "s": 26062, "text": "Explanation : Putting a non zero value in condition part makes it infinite." }, { "code": null, "e": 26178, "s": 26138, "text": "Q.2 What is the output of this program?" }, { "code": "#include <iostream>using namespace std;int main(){ static int i; for (i++; ++i; i++) { printf(\"%d \", i); if (i == 6) break; } return 0;}", "e": 26352, "s": 26178, "text": null }, { "code": null, "e": 26424, "s": 26352, "text": "OptionsOptions:a) 2 4 6b) compilation errorc) garbage valued) no output" }, { "code": null, "e": 26432, "s": 26424, "text": "ans : a" }, { "code": null, "e": 26521, "s": 26432, "text": "Explanation : After first iteration, program looks like (0, 2, 2). It breaks when i = 6." }, { "code": null, "e": 26561, "s": 26521, "text": "Q.3 What is the output of this program?" }, { "code": "#include <iostream>using namespace std;int fun();int main(){ for (fun(); fun(); fun()) { printf(\"%d \", fun()); } return 0;}int fun(){ int static num = 10; return num--;}", "e": 26753, "s": 26561, "text": null }, { "code": null, "e": 26830, "s": 26753, "text": "Optionsa) compilation errorb) can’t be predictedc) 8 5 2d) none of the above" }, { "code": null, "e": 26837, "s": 26830, "text": "ans: c" }, { "code": null, "e": 26851, "s": 26837, "text": "Explanation :" }, { "code": null, "e": 27324, "s": 26851, "text": " At first iteration:\n for(10; 9; fun()) //condition true\n printf(\"%d\", 8) //8 prints\n At second iteration:\n for(10; fun(); 7)\n for(7; 6 ;fun()) //condition true\n printf(\"%d\", 5) //5 prints\n At third iteration:\n for(7; fun(); 4)\n for(4; 3; fun()) //condition true\n printf(\"%d\", 2) //2 prints\n At fourth iteration:\n for(4; fun(); 1)\n for(1; 0; fun()) //condition false \n Program terminates" }, { "code": null, "e": 27364, "s": 27324, "text": "Q.4 What is the output of this program?" }, { "code": "#include <iostream>using namespace std;int main(){ for (;;) printf(\"%d \", 10); return 0;}", "e": 27467, "s": 27364, "text": null }, { "code": null, "e": 27533, "s": 27467, "text": "Optionsa) compilation errorb) run time errorc) 10d) Infinite loop" }, { "code": null, "e": 27541, "s": 27533, "text": "ans : d" }, { "code": null, "e": 27611, "s": 27541, "text": "Explanation : Since no condition is provided so loop runs infinitely." }, { "code": null, "e": 27651, "s": 27611, "text": "Q.5 What is the output of this program?" }, { "code": "#include <iostream>using namespace std;int main(){ char i = 0; for (; i++; printf(\"%d\", i)) ; printf(\"%d\", i); return 0;}", "e": 27792, "s": 27651, "text": null }, { "code": null, "e": 27800, "s": 27792, "text": "Options" }, { "code": null, "e": 27845, "s": 27800, "text": "a) 0b) 1c) Infinite loopd) compilation error" }, { "code": null, "e": 27852, "s": 27845, "text": "ans: b" }, { "code": null, "e": 27966, "s": 27852, "text": "Explanation : The following condition fails for first time so loop terminates and value of i is incremented to 1." }, { "code": null, "e": 27993, "s": 27966, "text": "for(; 0; printf(\"%d\", i)) " }, { "code": null, "e": 28034, "s": 27993, "text": " Q.6 What is the output of this program?" }, { "code": "#include <iostream>using namespace std;int main(){ int i; for (i = 0; i < 0, 5; i++) printf(\"%d \", i); return 0;}", "e": 28164, "s": 28034, "text": null }, { "code": null, "e": 28224, "s": 28164, "text": "Optionsa) errorb) 1, 3c) program never endsd) none of these" }, { "code": null, "e": 28231, "s": 28224, "text": "ans: c" }, { "code": null, "e": 28371, "s": 28231, "text": "Explanation :-Considers two conditions:(a)i<0 fails for first iteration(b)5 in condition part makes it infinite loop as it never becomes 0." }, { "code": null, "e": 28671, "s": 28371, "text": "This article is contributed by Pragya Singh. 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": 28796, "s": 28671, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28825, "s": 28796, "text": "C-Loops & Control Statements" }, { "code": null, "e": 28834, "s": 28825, "text": "C-Output" }, { "code": null, "e": 28849, "s": 28834, "text": "Program Output" }, { "code": null, "e": 28947, "s": 28849, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28992, "s": 28947, "text": "Output of Java program | Set 18 (Overriding)" }, { "code": null, "e": 29024, "s": 28992, "text": "Output of Java Program | Set 11" }, { "code": null, "e": 29071, "s": 29024, "text": "Output of Java programs | Set 13 (Collections)" }, { "code": null, "e": 29119, "s": 29071, "text": "Output of C++ programs | Set 34 (File Handling)" }, { "code": null, "e": 29160, "s": 29119, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 29191, "s": 29160, "text": "Output of Java Program | Set 3" }, { "code": null, "e": 29206, "s": 29191, "text": "Runtime Errors" }, { "code": null, "e": 29238, "s": 29206, "text": "Output of Java program | Set 28" }, { "code": null, "e": 29269, "s": 29238, "text": "Output of Java program | Set 5" } ]
Plot Z-Score in R - GeeksforGeeks
24 Jun, 2021 R supports powerful tools to plot z-score according to a given p-value. Thus, to learn about the z score we should know about the p-value. p-value and z scores are called statistical parameters and are used to make statistical calculations. p-value is the probability of obtaining results at least as extreme as the observed result. Just like probability p-values lie between 0 and 1. If the Null hypothesis of a study comes out to be true then the p-value or calculated probability is the probability of finding the more extreme results. z-score describes a value’s relationship to the mean of the group values. Let us take an example to understand the concept of z-score properly: Consider a case of a class of 25 students. After the exams, the mean score of the class comes out to be 45. If we want to know whether a person who has scored 75 marks in the exam is among 10% of the scorers. In starting, it may seem to be a very tedious calculation. But by knowing the concept of z-scores it can become fairly easy. The formula for calculating z-score: Standard deviation means how far the result is from the average value. Now a z score of 1 denotes that the observation is at a distance of one standard deviation towards right from the center. Similarly, a z score of -1 tells us that the observation is one standard deviation left from the center. Approach: Create a vector and assign various values to it. Find the mean of the vector using function mean(). Find the standard deviation using function sd(). Subtract the mean value from the observation and divide the resultant with standard deviation. The vector obtained will have the required Z-score values. Now simply plot it. Example 1: R # create vectora <- c(9, 10, 12, 14, 5, 8, 9) # find meanmean(a) # find standard deviationsd(a) # calculate za.z <- (a - mean(a)) / sd(a) # plot z-scoreplot(a.z, type="o", col="green") Output: Example 2: R # create vectora <- c(7, 9, 2, 4, 25, 18, 19) # find meanmean(a) # find standard deviationsd(a) # calculate z-scorea.z <- (a - mean(a)) / sd(a) # plot z-scoreplot(a.z, type="o", col="green") Output: If we are given a p-value and our value is 0.70 then this means that it will be a point below which there are 80% of observations and 20% of observations lie above it. The easiest way for finding a z score if a p-value is given is to use qnorm() function. It takes the p-value as an argument and gives the z score as output. Syntax: qnorm(p-value) Approach: Call qnorm() function with required p-value Plot z-score with the value so obtained Example : R set <- qnorm(0.75) plot(set, type="o", col="green") Output: anikaseth98 Picked R-Charts R-Graphs R-plots R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to import an Excel File into R ? How to filter R DataFrame by values in a column? Time Series Analysis in R Logistic Regression in R Programming R - if statement
[ { "code": null, "e": 26487, "s": 26459, "text": "\n24 Jun, 2021" }, { "code": null, "e": 26728, "s": 26487, "text": "R supports powerful tools to plot z-score according to a given p-value. Thus, to learn about the z score we should know about the p-value. p-value and z scores are called statistical parameters and are used to make statistical calculations." }, { "code": null, "e": 27026, "s": 26728, "text": "p-value is the probability of obtaining results at least as extreme as the observed result. Just like probability p-values lie between 0 and 1. If the Null hypothesis of a study comes out to be true then the p-value or calculated probability is the probability of finding the more extreme results." }, { "code": null, "e": 27170, "s": 27026, "text": "z-score describes a value’s relationship to the mean of the group values. Let us take an example to understand the concept of z-score properly:" }, { "code": null, "e": 27504, "s": 27170, "text": "Consider a case of a class of 25 students. After the exams, the mean score of the class comes out to be 45. If we want to know whether a person who has scored 75 marks in the exam is among 10% of the scorers. In starting, it may seem to be a very tedious calculation. But by knowing the concept of z-scores it can become fairly easy." }, { "code": null, "e": 27541, "s": 27504, "text": "The formula for calculating z-score:" }, { "code": null, "e": 27612, "s": 27541, "text": "Standard deviation means how far the result is from the average value." }, { "code": null, "e": 27734, "s": 27612, "text": "Now a z score of 1 denotes that the observation is at a distance of one standard deviation towards right from the center." }, { "code": null, "e": 27839, "s": 27734, "text": "Similarly, a z score of -1 tells us that the observation is one standard deviation left from the center." }, { "code": null, "e": 27849, "s": 27839, "text": "Approach:" }, { "code": null, "e": 27898, "s": 27849, "text": "Create a vector and assign various values to it." }, { "code": null, "e": 27949, "s": 27898, "text": "Find the mean of the vector using function mean()." }, { "code": null, "e": 27998, "s": 27949, "text": "Find the standard deviation using function sd()." }, { "code": null, "e": 28093, "s": 27998, "text": "Subtract the mean value from the observation and divide the resultant with standard deviation." }, { "code": null, "e": 28152, "s": 28093, "text": "The vector obtained will have the required Z-score values." }, { "code": null, "e": 28172, "s": 28152, "text": "Now simply plot it." }, { "code": null, "e": 28184, "s": 28172, "text": "Example 1: " }, { "code": null, "e": 28186, "s": 28184, "text": "R" }, { "code": "# create vectora <- c(9, 10, 12, 14, 5, 8, 9) # find meanmean(a) # find standard deviationsd(a) # calculate za.z <- (a - mean(a)) / sd(a) # plot z-scoreplot(a.z, type=\"o\", col=\"green\")", "e": 28371, "s": 28186, "text": null }, { "code": null, "e": 28383, "s": 28375, "text": "Output:" }, { "code": null, "e": 28398, "s": 28387, "text": "Example 2:" }, { "code": null, "e": 28402, "s": 28400, "text": "R" }, { "code": "# create vectora <- c(7, 9, 2, 4, 25, 18, 19) # find meanmean(a) # find standard deviationsd(a) # calculate z-scorea.z <- (a - mean(a)) / sd(a) # plot z-scoreplot(a.z, type=\"o\", col=\"green\")", "e": 28593, "s": 28402, "text": null }, { "code": null, "e": 28605, "s": 28597, "text": "Output:" }, { "code": null, "e": 28934, "s": 28609, "text": "If we are given a p-value and our value is 0.70 then this means that it will be a point below which there are 80% of observations and 20% of observations lie above it. The easiest way for finding a z score if a p-value is given is to use qnorm() function. It takes the p-value as an argument and gives the z score as output." }, { "code": null, "e": 28944, "s": 28936, "text": "Syntax:" }, { "code": null, "e": 28961, "s": 28946, "text": "qnorm(p-value)" }, { "code": null, "e": 28973, "s": 28963, "text": "Approach:" }, { "code": null, "e": 29019, "s": 28975, "text": "Call qnorm() function with required p-value" }, { "code": null, "e": 29059, "s": 29019, "text": "Plot z-score with the value so obtained" }, { "code": null, "e": 29071, "s": 29061, "text": "Example :" }, { "code": null, "e": 29075, "s": 29073, "text": "R" }, { "code": "set <- qnorm(0.75) plot(set, type=\"o\", col=\"green\")", "e": 29127, "s": 29075, "text": null }, { "code": null, "e": 29139, "s": 29131, "text": "Output:" }, { "code": null, "e": 29155, "s": 29143, "text": "anikaseth98" }, { "code": null, "e": 29162, "s": 29155, "text": "Picked" }, { "code": null, "e": 29171, "s": 29162, "text": "R-Charts" }, { "code": null, "e": 29180, "s": 29171, "text": "R-Graphs" }, { "code": null, "e": 29188, "s": 29180, "text": "R-plots" }, { "code": null, "e": 29201, "s": 29188, "text": "R-Statistics" }, { "code": null, "e": 29212, "s": 29201, "text": "R Language" }, { "code": null, "e": 29310, "s": 29212, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29362, "s": 29310, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29397, "s": 29362, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29435, "s": 29397, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29493, "s": 29435, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29536, "s": 29493, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29573, "s": 29536, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29622, "s": 29573, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29648, "s": 29622, "text": "Time Series Analysis in R" }, { "code": null, "e": 29685, "s": 29648, "text": "Logistic Regression in R Programming" } ]
Data Structures | Tree Traversals | Question 4 - GeeksforGeeks
28 Jun, 2021 What does the following function do for a given binary tree? int fun(struct node *root){ if (root == NULL) return 0; if (root->left == NULL && root->right == NULL) return 0; return 1 + fun(root->left) + fun(root->right);} (A) Counts leaf nodes(B) Counts internal nodes(C) Returns height where height is defined as number of edges on the path from root to deepest node(D) Return diameter where diameter is number of edges on the longest path between any two nodes.Answer: (B)Explanation: The function counts internal nodes.1) If root is NULL or a leaf node, it returns 0.2) Otherwise returns, 1 plus count of internal nodes in left subtree, plus count of internal nodes in right subtree. See the following complete program. #include <stdio.h> struct node{ int key; struct node *left, *right;}; int fun(struct node *root){ if (root == NULL) return 0; if (root->left == NULL && root->right == NULL) return 0; return 1 + fun(root->left) + fun(root->right);} /* Helper function that allocates a new node with the given key and NULL left and right pointers. */struct node* newNode(int key){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->key = key; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above functions*/int main(){ /* Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8 */ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(8); printf("%d", fun(root)); getchar(); return 0;} Quiz of this Question Data Structures Data Structures-Tree Traversals Tree Traversals Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count number of times each Edge appears in all possible paths of a given Tree Data Structures | Linked List | Question 5 Data Structures | Linked List | Question 6 Difference between Singly linked list and Doubly linked list Advantages and Disadvantages of Linked List FIFO vs LIFO approach in Programming C program to implement Adjacency Matrix of a given Graph Data Structures | Graph | Question 9 Introduction to Data Structures Data Structures | Stack | Question 1
[ { "code": null, "e": 26277, "s": 26249, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26338, "s": 26277, "text": "What does the following function do for a given binary tree?" }, { "code": "int fun(struct node *root){ if (root == NULL) return 0; if (root->left == NULL && root->right == NULL) return 0; return 1 + fun(root->left) + fun(root->right);}", "e": 26515, "s": 26338, "text": null }, { "code": null, "e": 26980, "s": 26515, "text": "(A) Counts leaf nodes(B) Counts internal nodes(C) Returns height where height is defined as number of edges on the path from root to deepest node(D) Return diameter where diameter is number of edges on the longest path between any two nodes.Answer: (B)Explanation: The function counts internal nodes.1) If root is NULL or a leaf node, it returns 0.2) Otherwise returns, 1 plus count of internal nodes in left subtree, plus count of internal nodes in right subtree." }, { "code": null, "e": 27016, "s": 26980, "text": "See the following complete program." }, { "code": "#include <stdio.h> struct node{ int key; struct node *left, *right;}; int fun(struct node *root){ if (root == NULL) return 0; if (root->left == NULL && root->right == NULL) return 0; return 1 + fun(root->left) + fun(root->right);} /* Helper function that allocates a new node with the given key and NULL left and right pointers. */struct node* newNode(int key){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->key = key; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above functions*/int main(){ /* Constructed binary tree is 1 / \\ 2 3 / \\ / 4 5 8 */ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(8); printf(\"%d\", fun(root)); getchar(); return 0;}", "e": 27983, "s": 27016, "text": null }, { "code": null, "e": 28005, "s": 27983, "text": "Quiz of this Question" }, { "code": null, "e": 28021, "s": 28005, "text": "Data Structures" }, { "code": null, "e": 28053, "s": 28021, "text": "Data Structures-Tree Traversals" }, { "code": null, "e": 28069, "s": 28053, "text": "Tree Traversals" }, { "code": null, "e": 28085, "s": 28069, "text": "Data Structures" }, { "code": null, "e": 28101, "s": 28085, "text": "Data Structures" }, { "code": null, "e": 28199, "s": 28101, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28277, "s": 28199, "text": "Count number of times each Edge appears in all possible paths of a given Tree" }, { "code": null, "e": 28320, "s": 28277, "text": "Data Structures | Linked List | Question 5" }, { "code": null, "e": 28363, "s": 28320, "text": "Data Structures | Linked List | Question 6" }, { "code": null, "e": 28424, "s": 28363, "text": "Difference between Singly linked list and Doubly linked list" }, { "code": null, "e": 28468, "s": 28424, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 28505, "s": 28468, "text": "FIFO vs LIFO approach in Programming" }, { "code": null, "e": 28562, "s": 28505, "text": "C program to implement Adjacency Matrix of a given Graph" }, { "code": null, "e": 28599, "s": 28562, "text": "Data Structures | Graph | Question 9" }, { "code": null, "e": 28631, "s": 28599, "text": "Introduction to Data Structures" } ]
Static class in Java - GeeksforGeeks
25 Feb, 2022 Java allows a class to be defined within another class. These are called Nested Classes. Classes can be static which most developers are aware of, henceforth some classes can be made static in Java. Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes. The class in which the nested class is defined is known as the Outer Class. Unlike top-level classes, Inner classes can be Static. Non-static nested classes are also known as Inner classes. An instance of an inner class cannot be created without an instance of the outer class. Therefore, an inner class instance can access all of the members of its outer class, without using a reference to the outer class instance. For this reason, inner classes can help make programs simple and concise. Remember: In static class, we can easily create objects. Differences between Static and Non-static Nested Classes The following are major differences between static nested classes and inner classes. A static nested class may be instantiated without instantiating its outer class.Inner classes can access both static and non-static members of the outer class. A static class can access only the static members of the outer class. A static nested class may be instantiated without instantiating its outer class. Inner classes can access both static and non-static members of the outer class. A static class can access only the static members of the outer class. Example Java // Java program to Demonstrate How to// Implement Static and Non-static Classes // Class 1// Helper classclass OuterClass { // Input string private static String msg = "GeeksForGeeks"; // Static nested class public static class NestedStaticClass { // Only static members of Outer class // is directly accessible in nested // static class public void printMessage() { // Try making 'message' a non-static // variable, there will be compiler error System.out.println( "Message from nested static class: " + msg); } } // Non-static nested class - // also called Inner class public class InnerClass { // Both static and non-static members // of Outer class are accessible in // this Inner class public void display() { // Print statement whenever this method is // called System.out.println( "Message from non-static nested class: " + msg); } }} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating instance of nested Static class // inside main() method OuterClass.NestedStaticClass printer = new OuterClass.NestedStaticClass(); // Calling non-static method of nested // static class printer.printMessage(); // Note: In order to create instance of Inner class // we need an Outer class instance // Creating Outer class instance for creating // non-static nested class OuterClass outer = new OuterClass(); OuterClass.InnerClass inner = outer.new InnerClass(); // Calling non-static method of Inner class inner.display(); // We can also combine above steps in one // step to create instance of Inner class OuterClass.InnerClass innerObject = new OuterClass().new InnerClass(); // Similarly calling inner class defined method innerObject.display(); }} Message from nested static class: GeeksForGeeks Message from non-static nested class: GeeksForGeeks Message from non-static nested class: GeeksForGeeks This article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. mailjesseduncan rajkit simmytarika5 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 25529, "s": 25501, "text": "\n25 Feb, 2022" }, { "code": null, "e": 26011, "s": 25529, "text": "Java allows a class to be defined within another class. These are called Nested Classes. Classes can be static which most developers are aware of, henceforth some classes can be made static in Java. Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes. The class in which the nested class is defined is known as the Outer Class. Unlike top-level classes, Inner classes can be Static. Non-static nested classes are also known as Inner classes." }, { "code": null, "e": 26314, "s": 26011, "text": "An instance of an inner class cannot be created without an instance of the outer class. Therefore, an inner class instance can access all of the members of its outer class, without using a reference to the outer class instance. For this reason, inner classes can help make programs simple and concise. " }, { "code": null, "e": 26371, "s": 26314, "text": "Remember: In static class, we can easily create objects." }, { "code": null, "e": 26428, "s": 26371, "text": "Differences between Static and Non-static Nested Classes" }, { "code": null, "e": 26514, "s": 26428, "text": "The following are major differences between static nested classes and inner classes. " }, { "code": null, "e": 26744, "s": 26514, "text": "A static nested class may be instantiated without instantiating its outer class.Inner classes can access both static and non-static members of the outer class. A static class can access only the static members of the outer class." }, { "code": null, "e": 26825, "s": 26744, "text": "A static nested class may be instantiated without instantiating its outer class." }, { "code": null, "e": 26975, "s": 26825, "text": "Inner classes can access both static and non-static members of the outer class. A static class can access only the static members of the outer class." }, { "code": null, "e": 26984, "s": 26975, "text": "Example " }, { "code": null, "e": 26989, "s": 26984, "text": "Java" }, { "code": "// Java program to Demonstrate How to// Implement Static and Non-static Classes // Class 1// Helper classclass OuterClass { // Input string private static String msg = \"GeeksForGeeks\"; // Static nested class public static class NestedStaticClass { // Only static members of Outer class // is directly accessible in nested // static class public void printMessage() { // Try making 'message' a non-static // variable, there will be compiler error System.out.println( \"Message from nested static class: \" + msg); } } // Non-static nested class - // also called Inner class public class InnerClass { // Both static and non-static members // of Outer class are accessible in // this Inner class public void display() { // Print statement whenever this method is // called System.out.println( \"Message from non-static nested class: \" + msg); } }} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating instance of nested Static class // inside main() method OuterClass.NestedStaticClass printer = new OuterClass.NestedStaticClass(); // Calling non-static method of nested // static class printer.printMessage(); // Note: In order to create instance of Inner class // we need an Outer class instance // Creating Outer class instance for creating // non-static nested class OuterClass outer = new OuterClass(); OuterClass.InnerClass inner = outer.new InnerClass(); // Calling non-static method of Inner class inner.display(); // We can also combine above steps in one // step to create instance of Inner class OuterClass.InnerClass innerObject = new OuterClass().new InnerClass(); // Similarly calling inner class defined method innerObject.display(); }}", "e": 29108, "s": 26989, "text": null }, { "code": null, "e": 29260, "s": 29108, "text": "Message from nested static class: GeeksForGeeks\nMessage from non-static nested class: GeeksForGeeks\nMessage from non-static nested class: GeeksForGeeks" }, { "code": null, "e": 29434, "s": 29260, "text": "This article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 29450, "s": 29434, "text": "mailjesseduncan" }, { "code": null, "e": 29457, "s": 29450, "text": "rajkit" }, { "code": null, "e": 29470, "s": 29457, "text": "simmytarika5" }, { "code": null, "e": 29475, "s": 29470, "text": "Java" }, { "code": null, "e": 29480, "s": 29475, "text": "Java" }, { "code": null, "e": 29578, "s": 29480, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29629, "s": 29578, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29659, "s": 29629, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29674, "s": 29659, "text": "Stream In Java" }, { "code": null, "e": 29705, "s": 29674, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29723, "s": 29705, "text": "ArrayList in Java" }, { "code": null, "e": 29755, "s": 29723, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29775, "s": 29755, "text": "Stack Class in Java" }, { "code": null, "e": 29799, "s": 29775, "text": "Singleton Class in Java" }, { "code": null, "e": 29831, "s": 29799, "text": "Multidimensional Arrays in Java" } ]
PHP | unpack() Function - GeeksforGeeks
09 Jul, 2019 The unpack() function is an inbuilt function in PHP which is used to unpack from a binary string into the respective format. Syntax: array unpack( $format, $data, $offset ) Parameters: This function accepts three parameters as mentioned above and described below: $format: It is required parameter. It specifies the format to be used while packing data.a – denotes string which is NUL-padded.A – denotes string which is SPACE-padded.h – denotes low nibble first Hex string.H – denotes high nibble first Hex string.c – denotes signed character.C – denotes unsigned character.s – denotes signed short (16 bit, machine byte order).S – denotes unsigned short (16 bit, machine byte order).n – denotes unsigned short (16 bit, big endian byte order).v – denotes unsigned short (16 bit, little endian byte order).i – denotes signed integer (machine dependent byte order and size).I – denotes unsigned integer (machine dependent byte order and size).l – denotes signed long (32 bit, machine byte order).L – denotes unsigned long (32 bit, machine byte order).N – denotes unsigned long (32 bit, big endian byte order).V – denotes unsigned long (32 bit, little endian byte order).f – denotes float (machine dependent representation and size).d – denotes double (machine dependent representation and size).x – denotes NUL byte.X – denotes Back up one byte.Z – denotes string which is NUL-padded.@ – denotes NUL-fill to absolute position. a – denotes string which is NUL-padded. A – denotes string which is SPACE-padded. h – denotes low nibble first Hex string. H – denotes high nibble first Hex string. c – denotes signed character. C – denotes unsigned character. s – denotes signed short (16 bit, machine byte order). S – denotes unsigned short (16 bit, machine byte order). n – denotes unsigned short (16 bit, big endian byte order). v – denotes unsigned short (16 bit, little endian byte order). i – denotes signed integer (machine dependent byte order and size). I – denotes unsigned integer (machine dependent byte order and size). l – denotes signed long (32 bit, machine byte order). L – denotes unsigned long (32 bit, machine byte order). N – denotes unsigned long (32 bit, big endian byte order). V – denotes unsigned long (32 bit, little endian byte order). f – denotes float (machine dependent representation and size). d – denotes double (machine dependent representation and size). x – denotes NUL byte. X – denotes Back up one byte. Z – denotes string which is NUL-padded. @ – denotes NUL-fill to absolute position. $data: It is Required parameter. It specifies the binary data to be unpacked. offset: This parameter holds the offset to begin from unpacking. Return Value: It returns an associative array containing unpacked elements on success, or returns FALSE on failure. Note: This function is available for PHP 4.0.0 and newer version. Example 1: This program uses C format to unpack the data from binary string. <?php var_dump( unpack("C*", "GEEKSFORGEEKS"));?> array(13) { [1]=> int(71) [2]=> int(69) [3]=> int(69) [4]=> int(75) [5]=> int(83) [6]=> int(70) [7]=> int(79) [8]=> int(82) [9]=> int(71) [10]=> int(69) [11]=> int(69) [12]=> int(75) [13]=> int(83) } Example 2: <?php $binary_data = pack("c2n2", 0x1634, 0x3623, 65, 66);var_dump(unpack("c2chars/n2int", $binary_data));?> array(4) { ["chars1"]=> int(52) ["chars2"]=> int(35) ["int1"]=> int(65) ["int2"]=> int(66) } Example 3: This example uses i format to unpack the data from binary string. <?php $binary_data = pack("i3", 56, 49, 54);var_dump(unpack("i3", $binary_data));?> array(3) { [1]=> int(56) [2]=> int(49) [3]=> int(54) } Reference: https://www.php.net/manual/en/function.unpack.php PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? PHP str_replace() Function How to pass form variables from one page to other page in PHP ? Different ways for passing data to view in Laravel Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26243, "s": 26215, "text": "\n09 Jul, 2019" }, { "code": null, "e": 26368, "s": 26243, "text": "The unpack() function is an inbuilt function in PHP which is used to unpack from a binary string into the respective format." }, { "code": null, "e": 26376, "s": 26368, "text": "Syntax:" }, { "code": null, "e": 26416, "s": 26376, "text": "array unpack( $format, $data, $offset )" }, { "code": null, "e": 26507, "s": 26416, "text": "Parameters: This function accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 27668, "s": 26507, "text": "$format: It is required parameter. It specifies the format to be used while packing data.a – denotes string which is NUL-padded.A – denotes string which is SPACE-padded.h – denotes low nibble first Hex string.H – denotes high nibble first Hex string.c – denotes signed character.C – denotes unsigned character.s – denotes signed short (16 bit, machine byte order).S – denotes unsigned short (16 bit, machine byte order).n – denotes unsigned short (16 bit, big endian byte order).v – denotes unsigned short (16 bit, little endian byte order).i – denotes signed integer (machine dependent byte order and size).I – denotes unsigned integer (machine dependent byte order and size).l – denotes signed long (32 bit, machine byte order).L – denotes unsigned long (32 bit, machine byte order).N – denotes unsigned long (32 bit, big endian byte order).V – denotes unsigned long (32 bit, little endian byte order).f – denotes float (machine dependent representation and size).d – denotes double (machine dependent representation and size).x – denotes NUL byte.X – denotes Back up one byte.Z – denotes string which is NUL-padded.@ – denotes NUL-fill to absolute position." }, { "code": null, "e": 27708, "s": 27668, "text": "a – denotes string which is NUL-padded." }, { "code": null, "e": 27750, "s": 27708, "text": "A – denotes string which is SPACE-padded." }, { "code": null, "e": 27791, "s": 27750, "text": "h – denotes low nibble first Hex string." }, { "code": null, "e": 27833, "s": 27791, "text": "H – denotes high nibble first Hex string." }, { "code": null, "e": 27863, "s": 27833, "text": "c – denotes signed character." }, { "code": null, "e": 27895, "s": 27863, "text": "C – denotes unsigned character." }, { "code": null, "e": 27950, "s": 27895, "text": "s – denotes signed short (16 bit, machine byte order)." }, { "code": null, "e": 28007, "s": 27950, "text": "S – denotes unsigned short (16 bit, machine byte order)." }, { "code": null, "e": 28067, "s": 28007, "text": "n – denotes unsigned short (16 bit, big endian byte order)." }, { "code": null, "e": 28130, "s": 28067, "text": "v – denotes unsigned short (16 bit, little endian byte order)." }, { "code": null, "e": 28198, "s": 28130, "text": "i – denotes signed integer (machine dependent byte order and size)." }, { "code": null, "e": 28268, "s": 28198, "text": "I – denotes unsigned integer (machine dependent byte order and size)." }, { "code": null, "e": 28322, "s": 28268, "text": "l – denotes signed long (32 bit, machine byte order)." }, { "code": null, "e": 28378, "s": 28322, "text": "L – denotes unsigned long (32 bit, machine byte order)." }, { "code": null, "e": 28437, "s": 28378, "text": "N – denotes unsigned long (32 bit, big endian byte order)." }, { "code": null, "e": 28499, "s": 28437, "text": "V – denotes unsigned long (32 bit, little endian byte order)." }, { "code": null, "e": 28562, "s": 28499, "text": "f – denotes float (machine dependent representation and size)." }, { "code": null, "e": 28626, "s": 28562, "text": "d – denotes double (machine dependent representation and size)." }, { "code": null, "e": 28648, "s": 28626, "text": "x – denotes NUL byte." }, { "code": null, "e": 28678, "s": 28648, "text": "X – denotes Back up one byte." }, { "code": null, "e": 28718, "s": 28678, "text": "Z – denotes string which is NUL-padded." }, { "code": null, "e": 28761, "s": 28718, "text": "@ – denotes NUL-fill to absolute position." }, { "code": null, "e": 28839, "s": 28761, "text": "$data: It is Required parameter. It specifies the binary data to be unpacked." }, { "code": null, "e": 28904, "s": 28839, "text": "offset: This parameter holds the offset to begin from unpacking." }, { "code": null, "e": 29020, "s": 28904, "text": "Return Value: It returns an associative array containing unpacked elements on success, or returns FALSE on failure." }, { "code": null, "e": 29086, "s": 29020, "text": "Note: This function is available for PHP 4.0.0 and newer version." }, { "code": null, "e": 29163, "s": 29086, "text": "Example 1: This program uses C format to unpack the data from binary string." }, { "code": "<?php var_dump( unpack(\"C*\", \"GEEKSFORGEEKS\"));?>", "e": 29214, "s": 29163, "text": null }, { "code": null, "e": 29467, "s": 29214, "text": "array(13) {\n [1]=>\n int(71)\n [2]=>\n int(69)\n [3]=>\n int(69)\n [4]=>\n int(75)\n [5]=>\n int(83)\n [6]=>\n int(70)\n [7]=>\n int(79)\n [8]=>\n int(82)\n [9]=>\n int(71)\n [10]=>\n int(69)\n [11]=>\n int(69)\n [12]=>\n int(75)\n [13]=>\n int(83)\n}\n" }, { "code": null, "e": 29478, "s": 29467, "text": "Example 2:" }, { "code": "<?php $binary_data = pack(\"c2n2\", 0x1634, 0x3623, 65, 66);var_dump(unpack(\"c2chars/n2int\", $binary_data));?>", "e": 29588, "s": 29478, "text": null }, { "code": null, "e": 29698, "s": 29588, "text": "array(4) {\n [\"chars1\"]=>\n int(52)\n [\"chars2\"]=>\n int(35)\n [\"int1\"]=>\n int(65)\n [\"int2\"]=>\n int(66)\n}\n" }, { "code": null, "e": 29775, "s": 29698, "text": "Example 3: This example uses i format to unpack the data from binary string." }, { "code": "<?php $binary_data = pack(\"i3\", 56, 49, 54);var_dump(unpack(\"i3\", $binary_data));?>", "e": 29860, "s": 29775, "text": null }, { "code": null, "e": 29928, "s": 29860, "text": "array(3) {\n [1]=>\n int(56)\n [2]=>\n int(49)\n [3]=>\n int(54)\n}\n" }, { "code": null, "e": 29989, "s": 29928, "text": "Reference: https://www.php.net/manual/en/function.unpack.php" }, { "code": null, "e": 30002, "s": 29989, "text": "PHP-function" }, { "code": null, "e": 30006, "s": 30002, "text": "PHP" }, { "code": null, "e": 30023, "s": 30006, "text": "Web Technologies" }, { "code": null, "e": 30027, "s": 30023, "text": "PHP" }, { "code": null, "e": 30125, "s": 30027, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30207, "s": 30125, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 30249, "s": 30207, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 30276, "s": 30249, "text": "PHP str_replace() Function" }, { "code": null, "e": 30340, "s": 30276, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 30391, "s": 30340, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 30431, "s": 30391, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30464, "s": 30431, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30509, "s": 30464, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30552, "s": 30509, "text": "How to fetch data from an API in ReactJS ?" } ]
Find n-th node in Preorder traversal of a Binary Tree - GeeksforGeeks
23 Jun, 2021 Given a Binary tree and a number N, write a program to find the N-th node in the Preorder traversal of the given Binary tree.Prerequisite: Tree TraversalExamples: Input: N = 4 11 / \ 21 31 / \ 41 51 Output: 51 Explanation: Preorder Traversal of given Binary Tree is 11 21 41 51 31, so 4th node will be 51. Input: N = 5 25 / \ 20 30 / \ / \ 18 22 24 32 Output: 30 The idea to solve this problem is to do preorder traversal of the given binary tree and keep track of the count of nodes visited while traversing the tree and print the current node when the count becomes equal to N. C++ Java Python3 C# Javascript // C++ program to find n-th node of// Preorder Traversal of Binary Tree#include <bits/stdc++.h>using namespace std; // Tree nodestruct Node { int data; Node *left, *right;}; // function to create new nodestruct Node* createNode(int item){ Node* temp = new Node; temp->data = item; temp->left = NULL; temp->right = NULL; return temp;} // function to find the N-th node in the preorder// traversal of a given binary treevoid NthPreordernode(struct Node* root, int N){ static int flag = 0; if (root == NULL) return; if (flag <= N) { flag++; // prints the n-th node of preorder traversal if (flag == N) cout << root->data; // left recursion NthPreordernode(root->left, N); // right recursion NthPreordernode(root->right, N); }} // Driver codeint main(){ // construction of binary tree struct Node* root = createNode(25); root->left = createNode(20); root->right = createNode(30); root->left->left = createNode(18); root->left->right = createNode(22); root->right->left = createNode(24); root->right->right = createNode(32); // nth node int N = 6; // prints n-th found found NthPreordernode(root, N); return 0;} // Java program to find n-th node of// Preorder Traversal of Binary Treeclass GFG{ // Tree nodestatic class Node{ int data; Node left, right;}; // function to create new nodestatic Node createNode(int item){ Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;}static int flag = 0; // function to find the N-th node in the preorder// traversal of a given binary treestatic void NthPreordernode(Node root, int N){ if (root == null) return; if (flag <= N) { flag++; // prints the n-th node of preorder traversal if (flag == N) System.out.print( root.data); // left recursion NthPreordernode(root.left, N); // right recursion NthPreordernode(root.right, N); }} // Driver codepublic static void main(String args[]){ // construction of binary tree Node root = createNode(25); root.left = createNode(20); root.right = createNode(30); root.left.left = createNode(18); root.left.right = createNode(22); root.right.left = createNode(24); root.right.right = createNode(32); // nth node int N = 6; // prints n-th found found NthPreordernode(root, N);}} // This code contributed by Arnab Kundu # Python program to find n-th node of# Preorder Traversal of Binary Tree class createNode(): def __init__(self, data): self.data = data self.left = None self.right = None # function to find the N-th node in the preorder# traversal of a given binary treeflag = [0]def NthPreordernode(root, N): if (root == None): return if (flag[0] <= N): flag[0] += 1 # prints the n-th node of preorder traversal if (flag[0] == N): print(root.data) # left recursion NthPreordernode(root.left, N) # right recursion NthPreordernode(root.right, N) # Driver codeif __name__ == '__main__': # construction of binary tree root = createNode(25) root.left = createNode(20) root.right = createNode(30) root.left.left = createNode(18) root.left.right = createNode(22) root.right.left = createNode(24) root.right.right = createNode(32) # nth node N = 6 # prints n-th found found NthPreordernode(root, N) # This code is contributed by SHUBHAMSINGH10 // C# program to find n-th node of// Preorder Traversal of Binary Treeusing System; class GFG{ // Tree nodepublic class Node{ public int data; public Node left, right;}; // function to create new nodestatic Node createNode(int item){ Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;}static int flag = 0; // function to find the N-th node in the preorder// traversal of a given binary treestatic void NthPreordernode(Node root, int N){ if (root == null) return; if (flag <= N) { flag++; // prints the n-th node of preorder traversal if (flag == N) Console.Write( root.data); // left recursion NthPreordernode(root.left, N); // right recursion NthPreordernode(root.right, N); }} // Driver codepublic static void Main(String []args){ // construction of binary tree Node root = createNode(25); root.left = createNode(20); root.right = createNode(30); root.left.left = createNode(18); root.left.right = createNode(22); root.right.left = createNode(24); root.right.right = createNode(32); // nth node int N = 6; // prints n-th found found NthPreordernode(root, N);}} // This code is contributed by Rajput-Ji <script>// Javascript program to find n-th node of// Preorder Traversal of Binary Tree // Tree nodeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // function to create new nodefunction createNode(item){ var temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} var flag = 0; // function to find the N-th node in the preorder// traversal of a given binary treefunction NthPreordernode(root, N){ if (root == null) return; if (flag <= N) { flag++; // prints the n-th node of preorder traversal if (flag == N) document.write( root.data); // left recursion NthPreordernode(root.left, N); // right recursion NthPreordernode(root.right, N); }} // Driver code// construction of binary treevar root = createNode(25);root.left = createNode(20);root.right = createNode(30);root.left.left = createNode(18);root.left.right = createNode(22);root.right.left = createNode(24);root.right.right = createNode(32); // nth nodevar N = 6; // prints n-th found foundNthPreordernode(root, N); // This code is contributed by famously.</script> 24 Time Complexity: O(n), where n is the number of nodes in the given binary tree. Auxiliary Space: O(1) SHUBHAMSINGH10 andrew1234 Rajput-Ji famously Binary Tree Preorder Traversal tree-traversal Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Tree Data Structure DFS traversal of a tree using recursion Top 50 Tree Coding Problems for Interviews Find the node with minimum value in a Binary Search Tree Count number of times each Edge appears in all possible paths of a given Tree Print Binary Tree in 2-Dimensions Real-time application of Data Structures Iterative Postorder Traversal | Set 2 (Using One Stack) Find maximum (or minimum) in Binary Tree Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
[ { "code": null, "e": 26184, "s": 26156, "text": "\n23 Jun, 2021" }, { "code": null, "e": 26349, "s": 26184, "text": "Given a Binary tree and a number N, write a program to find the N-th node in the Preorder traversal of the given Binary tree.Prerequisite: Tree TraversalExamples: " }, { "code": null, "e": 26690, "s": 26349, "text": "Input: N = 4\n 11\n / \\\n 21 31\n / \\\n 41 51\nOutput: 51\nExplanation: Preorder Traversal of given Binary Tree is 11 21 41 51 31, \nso 4th node will be 51.\n\nInput: N = 5\n 25\n / \\\n 20 30\n / \\ / \\\n 18 22 24 32\nOutput: 30" }, { "code": null, "e": 26911, "s": 26692, "text": "The idea to solve this problem is to do preorder traversal of the given binary tree and keep track of the count of nodes visited while traversing the tree and print the current node when the count becomes equal to N. " }, { "code": null, "e": 26915, "s": 26911, "text": "C++" }, { "code": null, "e": 26920, "s": 26915, "text": "Java" }, { "code": null, "e": 26928, "s": 26920, "text": "Python3" }, { "code": null, "e": 26931, "s": 26928, "text": "C#" }, { "code": null, "e": 26942, "s": 26931, "text": "Javascript" }, { "code": "// C++ program to find n-th node of// Preorder Traversal of Binary Tree#include <bits/stdc++.h>using namespace std; // Tree nodestruct Node { int data; Node *left, *right;}; // function to create new nodestruct Node* createNode(int item){ Node* temp = new Node; temp->data = item; temp->left = NULL; temp->right = NULL; return temp;} // function to find the N-th node in the preorder// traversal of a given binary treevoid NthPreordernode(struct Node* root, int N){ static int flag = 0; if (root == NULL) return; if (flag <= N) { flag++; // prints the n-th node of preorder traversal if (flag == N) cout << root->data; // left recursion NthPreordernode(root->left, N); // right recursion NthPreordernode(root->right, N); }} // Driver codeint main(){ // construction of binary tree struct Node* root = createNode(25); root->left = createNode(20); root->right = createNode(30); root->left->left = createNode(18); root->left->right = createNode(22); root->right->left = createNode(24); root->right->right = createNode(32); // nth node int N = 6; // prints n-th found found NthPreordernode(root, N); return 0;}", "e": 28197, "s": 26942, "text": null }, { "code": "// Java program to find n-th node of// Preorder Traversal of Binary Treeclass GFG{ // Tree nodestatic class Node{ int data; Node left, right;}; // function to create new nodestatic Node createNode(int item){ Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;}static int flag = 0; // function to find the N-th node in the preorder// traversal of a given binary treestatic void NthPreordernode(Node root, int N){ if (root == null) return; if (flag <= N) { flag++; // prints the n-th node of preorder traversal if (flag == N) System.out.print( root.data); // left recursion NthPreordernode(root.left, N); // right recursion NthPreordernode(root.right, N); }} // Driver codepublic static void main(String args[]){ // construction of binary tree Node root = createNode(25); root.left = createNode(20); root.right = createNode(30); root.left.left = createNode(18); root.left.right = createNode(22); root.right.left = createNode(24); root.right.right = createNode(32); // nth node int N = 6; // prints n-th found found NthPreordernode(root, N);}} // This code contributed by Arnab Kundu", "e": 29467, "s": 28197, "text": null }, { "code": "# Python program to find n-th node of# Preorder Traversal of Binary Tree class createNode(): def __init__(self, data): self.data = data self.left = None self.right = None # function to find the N-th node in the preorder# traversal of a given binary treeflag = [0]def NthPreordernode(root, N): if (root == None): return if (flag[0] <= N): flag[0] += 1 # prints the n-th node of preorder traversal if (flag[0] == N): print(root.data) # left recursion NthPreordernode(root.left, N) # right recursion NthPreordernode(root.right, N) # Driver codeif __name__ == '__main__': # construction of binary tree root = createNode(25) root.left = createNode(20) root.right = createNode(30) root.left.left = createNode(18) root.left.right = createNode(22) root.right.left = createNode(24) root.right.right = createNode(32) # nth node N = 6 # prints n-th found found NthPreordernode(root, N) # This code is contributed by SHUBHAMSINGH10", "e": 30557, "s": 29467, "text": null }, { "code": "// C# program to find n-th node of// Preorder Traversal of Binary Treeusing System; class GFG{ // Tree nodepublic class Node{ public int data; public Node left, right;}; // function to create new nodestatic Node createNode(int item){ Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;}static int flag = 0; // function to find the N-th node in the preorder// traversal of a given binary treestatic void NthPreordernode(Node root, int N){ if (root == null) return; if (flag <= N) { flag++; // prints the n-th node of preorder traversal if (flag == N) Console.Write( root.data); // left recursion NthPreordernode(root.left, N); // right recursion NthPreordernode(root.right, N); }} // Driver codepublic static void Main(String []args){ // construction of binary tree Node root = createNode(25); root.left = createNode(20); root.right = createNode(30); root.left.left = createNode(18); root.left.right = createNode(22); root.right.left = createNode(24); root.right.right = createNode(32); // nth node int N = 6; // prints n-th found found NthPreordernode(root, N);}} // This code is contributed by Rajput-Ji", "e": 31855, "s": 30557, "text": null }, { "code": "<script>// Javascript program to find n-th node of// Preorder Traversal of Binary Tree // Tree nodeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // function to create new nodefunction createNode(item){ var temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} var flag = 0; // function to find the N-th node in the preorder// traversal of a given binary treefunction NthPreordernode(root, N){ if (root == null) return; if (flag <= N) { flag++; // prints the n-th node of preorder traversal if (flag == N) document.write( root.data); // left recursion NthPreordernode(root.left, N); // right recursion NthPreordernode(root.right, N); }} // Driver code// construction of binary treevar root = createNode(25);root.left = createNode(20);root.right = createNode(30);root.left.left = createNode(18);root.left.right = createNode(22);root.right.left = createNode(24);root.right.right = createNode(32); // nth nodevar N = 6; // prints n-th found foundNthPreordernode(root, N); // This code is contributed by famously.</script>", "e": 33080, "s": 31855, "text": null }, { "code": null, "e": 33083, "s": 33080, "text": "24" }, { "code": null, "e": 33188, "s": 33085, "text": "Time Complexity: O(n), where n is the number of nodes in the given binary tree. Auxiliary Space: O(1) " }, { "code": null, "e": 33203, "s": 33188, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 33214, "s": 33203, "text": "andrew1234" }, { "code": null, "e": 33224, "s": 33214, "text": "Rajput-Ji" }, { "code": null, "e": 33233, "s": 33224, "text": "famously" }, { "code": null, "e": 33245, "s": 33233, "text": "Binary Tree" }, { "code": null, "e": 33264, "s": 33245, "text": "Preorder Traversal" }, { "code": null, "e": 33279, "s": 33264, "text": "tree-traversal" }, { "code": null, "e": 33284, "s": 33279, "text": "Tree" }, { "code": null, "e": 33289, "s": 33284, "text": "Tree" }, { "code": null, "e": 33387, "s": 33289, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33423, "s": 33387, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 33463, "s": 33423, "text": "DFS traversal of a tree using recursion" }, { "code": null, "e": 33506, "s": 33463, "text": "Top 50 Tree Coding Problems for Interviews" }, { "code": null, "e": 33563, "s": 33506, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 33641, "s": 33563, "text": "Count number of times each Edge appears in all possible paths of a given Tree" }, { "code": null, "e": 33675, "s": 33641, "text": "Print Binary Tree in 2-Dimensions" }, { "code": null, "e": 33716, "s": 33675, "text": "Real-time application of Data Structures" }, { "code": null, "e": 33772, "s": 33716, "text": "Iterative Postorder Traversal | Set 2 (Using One Stack)" }, { "code": null, "e": 33813, "s": 33772, "text": "Find maximum (or minimum) in Binary Tree" } ]
Convert PDF to CSV using Python - GeeksforGeeks
02 Feb, 2021 Python is a high-level, general-purpose, and very popular programming language. Python programming language (the latest Python 3) is being used in web development, Machine Learning applications, along with all cutting-edge technology in Software Industry. Python Programming Language is very well suited for Beginners, also for experienced programmers with other programming languages like C++ and Java. In this article, we will learn how to convert a PDF File to CSV File Using Python. Here we will discuss various methods for conversion. For all methods, we are using an input PDF file. Method 1: Here will use the pdftables_api Module for converting the PDF file into any other format. The pdftables_api module is used for reading the tables in a PDF. It also allows us to convert PDF Files into another format. Installation: Open Command Prompt and type "pip install git+https://github.com/pdftables/python-pdftables-api.git" It will install the pdftables_api Module After Installation, you need an API KEY. Go to PDFTables.com and signup, then visit the API Page to see your API KEY. Approach: Verify the API key. For Converting PDF File Into CSV File we will use csv() method. Syntax: pdftables_api.Client('API KEY').csv(pdf_path, csv_path) Below is the Implementation: PDF File Used: PDF FILE Python3 # Import Moduleimport pdftables_api # API KEY VERIFICATIONconversion = pdftables_api.Client('API KEY') # PDf to CSV # (Hello.pdf, Hello)conversion.csv(pdf_file_path, output_file_path) Output: CSV FILE Method 2: Here will use the tabula-py Module for converting the PDF file into any other format. The tabula-py is a simple Python wrapper of tabula-java, which can read tables in a PDF. You can read tables from a PDF and convert them into a pandas DataFrame. tabula-py also enables you to convert a PDF file into a CSV, a TSV, or a JSON file. Installation: pip install tabula-py Before we start, first we need to install java and add a java installation folder to the PATH variable. Install java click here Add java installation folder (C:\Program Files (x86)\Java\jre1.8.0_251\bin) to the environment path variable Approach: Read PDF file using read_pdf() method. Then we will convert the PDF files into a CSV file using the to_csv() method. Syntax: read_pdf(PDF File Path, pages = Number of pages, **agrs) Below is the Implementation: PDF File Used: PDF FILE Python3 # Import Module import tabula # Read PDF File# this contain a listdf = tabula.read_pdf(PDF File Path, pages = 1)[0] # Convert into Excel Filedf.to_csv('Excel File Path') Output: CSV FILE Picked python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25562, "s": 25534, "text": "\n02 Feb, 2021" }, { "code": null, "e": 25966, "s": 25562, "text": "Python is a high-level, general-purpose, and very popular programming language. Python programming language (the latest Python 3) is being used in web development, Machine Learning applications, along with all cutting-edge technology in Software Industry. Python Programming Language is very well suited for Beginners, also for experienced programmers with other programming languages like C++ and Java." }, { "code": null, "e": 26151, "s": 25966, "text": "In this article, we will learn how to convert a PDF File to CSV File Using Python. Here we will discuss various methods for conversion. For all methods, we are using an input PDF file." }, { "code": null, "e": 26161, "s": 26151, "text": "Method 1:" }, { "code": null, "e": 26377, "s": 26161, "text": "Here will use the pdftables_api Module for converting the PDF file into any other format. The pdftables_api module is used for reading the tables in a PDF. It also allows us to convert PDF Files into another format." }, { "code": null, "e": 26391, "s": 26377, "text": "Installation:" }, { "code": null, "e": 26492, "s": 26391, "text": "Open Command Prompt and type \"pip install git+https://github.com/pdftables/python-pdftables-api.git\"" }, { "code": null, "e": 26533, "s": 26492, "text": "It will install the pdftables_api Module" }, { "code": null, "e": 26574, "s": 26533, "text": "After Installation, you need an API KEY." }, { "code": null, "e": 26651, "s": 26574, "text": "Go to PDFTables.com and signup, then visit the API Page to see your API KEY." }, { "code": null, "e": 26661, "s": 26651, "text": "Approach:" }, { "code": null, "e": 26681, "s": 26661, "text": "Verify the API key." }, { "code": null, "e": 26745, "s": 26681, "text": "For Converting PDF File Into CSV File we will use csv() method." }, { "code": null, "e": 26753, "s": 26745, "text": "Syntax:" }, { "code": null, "e": 26809, "s": 26753, "text": "pdftables_api.Client('API KEY').csv(pdf_path, csv_path)" }, { "code": null, "e": 26838, "s": 26809, "text": "Below is the Implementation:" }, { "code": null, "e": 26853, "s": 26838, "text": "PDF File Used:" }, { "code": null, "e": 26862, "s": 26853, "text": "PDF FILE" }, { "code": null, "e": 26870, "s": 26862, "text": "Python3" }, { "code": "# Import Moduleimport pdftables_api # API KEY VERIFICATIONconversion = pdftables_api.Client('API KEY') # PDf to CSV # (Hello.pdf, Hello)conversion.csv(pdf_file_path, output_file_path)", "e": 27056, "s": 26870, "text": null }, { "code": null, "e": 27064, "s": 27056, "text": "Output:" }, { "code": null, "e": 27073, "s": 27064, "text": "CSV FILE" }, { "code": null, "e": 27083, "s": 27073, "text": "Method 2:" }, { "code": null, "e": 27415, "s": 27083, "text": "Here will use the tabula-py Module for converting the PDF file into any other format. The tabula-py is a simple Python wrapper of tabula-java, which can read tables in a PDF. You can read tables from a PDF and convert them into a pandas DataFrame. tabula-py also enables you to convert a PDF file into a CSV, a TSV, or a JSON file." }, { "code": null, "e": 27429, "s": 27415, "text": "Installation:" }, { "code": null, "e": 27451, "s": 27429, "text": "pip install tabula-py" }, { "code": null, "e": 27555, "s": 27451, "text": "Before we start, first we need to install java and add a java installation folder to the PATH variable." }, { "code": null, "e": 27579, "s": 27555, "text": "Install java click here" }, { "code": null, "e": 27688, "s": 27579, "text": "Add java installation folder (C:\\Program Files (x86)\\Java\\jre1.8.0_251\\bin) to the environment path variable" }, { "code": null, "e": 27698, "s": 27688, "text": "Approach:" }, { "code": null, "e": 27737, "s": 27698, "text": "Read PDF file using read_pdf() method." }, { "code": null, "e": 27815, "s": 27737, "text": "Then we will convert the PDF files into a CSV file using the to_csv() method." }, { "code": null, "e": 27823, "s": 27815, "text": "Syntax:" }, { "code": null, "e": 27880, "s": 27823, "text": "read_pdf(PDF File Path, pages = Number of pages, **agrs)" }, { "code": null, "e": 27909, "s": 27880, "text": "Below is the Implementation:" }, { "code": null, "e": 27924, "s": 27909, "text": "PDF File Used:" }, { "code": null, "e": 27933, "s": 27924, "text": "PDF FILE" }, { "code": null, "e": 27941, "s": 27933, "text": "Python3" }, { "code": "# Import Module import tabula # Read PDF File# this contain a listdf = tabula.read_pdf(PDF File Path, pages = 1)[0] # Convert into Excel Filedf.to_csv('Excel File Path')", "e": 28113, "s": 27941, "text": null }, { "code": null, "e": 28121, "s": 28113, "text": "Output:" }, { "code": null, "e": 28130, "s": 28121, "text": "CSV FILE" }, { "code": null, "e": 28137, "s": 28130, "text": "Picked" }, { "code": null, "e": 28152, "s": 28137, "text": "python-utility" }, { "code": null, "e": 28159, "s": 28152, "text": "Python" }, { "code": null, "e": 28257, "s": 28159, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28289, "s": 28257, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28331, "s": 28289, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28373, "s": 28331, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28429, "s": 28373, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28456, "s": 28429, "text": "Python Classes and Objects" }, { "code": null, "e": 28495, "s": 28456, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28526, "s": 28495, "text": "Python | os.path.join() method" }, { "code": null, "e": 28548, "s": 28526, "text": "Defaultdict in Python" }, { "code": null, "e": 28577, "s": 28548, "text": "Create a directory in Python" } ]
Implementing neural machine translation using keras | by Renu Khandelwal | Towards Data Science
In this article, you get a step by step explanation of building a neural machine translator using English as the source language and Spanish as the target language. We will be using Long Short Term Memory(LSTM) units in keras towardsdatascience.com In this article, we will create a Sequence to Sequence model using an encoder and decoder framework with LSTM as the basic block Sequence to Sequence model maps a source sequence to target sequence. The source sequence is input language to the machine translation system, and the target sequence is the output language. A step by step implementation of a neural machine translation(NMT) using Teacher forcing without Attention mechanism. Implementation is using keras library with LSTM as the basic block Reading the data from the file containing the source and target sentences Cleaning the data by converting to lowercase, removing spaces, special characters, digits, and quotes Tag the start and end of the target sentence using START_ and _END respectively for training and inference Create the dictionary of unique source and target words to vector and vice-versa Shuffle the data for better generalization Split the dataset into train and test data Create the data; we will be using fit_generator() to fit the data to the model Build the encoder using Embedding and LSTM layers Build the decoder using Embedding and LSTM layers and takes input from the embedding layer and the encoder states. Compile the model and train the model Make predictions from the model Import the required libraries import pandas as pdimport numpy as npimport stringfrom string import digitsimport matplotlib.pyplot as plt%matplotlib inlineimport refrom sklearn.utils import shufflefrom sklearn.model_selection import train_test_splitfrom keras.layers import Input, LSTM, Embedding, Densefrom keras.models import Model Read the file that contains the English-Spanish translations that we downloaded from the here # Path to the data txt file on disk.data_path = "\\NMT\\spa-eng\\spa.txt"# open the file eng-spa.txt and readlines= pd.read_table(data_path, names =['source', 'target', 'comments'])#printing sample data from lineslines.sample(6) We apply the following text cleaning Convert text to lower case Remove quotes Remove all special characters like “@, !, *, $, #, ?, %, etc.” Clean digits from the source and target sentences. If the source or the target language use different symbols for the numbers, then remove those symbols Remove spaces # convert source and target text to Lowercase lines.source=lines.source.apply(lambda x: x.lower())lines.target=lines.target.apply(lambda x: x.lower())# Remove quotes from source and target textlines.source=lines.source.apply(lambda x: re.sub("'", '', x))lines.target=lines.target.apply(lambda x: re.sub("'", '', x))# create a set of all special charactersspecial_characters= set(string.punctuation)# Remove all the special characterslines.source = lines.source.apply(lambda x: ''.join(char1 for char1 in x if char1 not in special_characters))lines.target = lines.target.apply(lambda x: ''.join(char1 for char1 in x if char1 not in special_characters))# Remove digits from source and target sentencesnum_digits= str.maketrans('','', digits)lines.source=lines.source.apply(lambda x: x.translate(num_digits))lines.target= lines.target.apply(lambda x: x.translate(num_digits))# Remove extra spaceslines.source=lines.source.apply(lambda x: x.strip())lines.target=lines.target.apply(lambda x: x.strip())lines.source=lines.source.apply(lambda x: re.sub(" +", " ", x))lines.target=lines.target.apply(lambda x: re.sub(" +", " ", x)) Adding the START_ and the _END token to the target sentences is very useful for training and during inference. These tags help to know when to start the translation and when to end the translation. # Add start and end tokens to target sequenceslines.target = lines.target.apply(lambda x : 'START_ '+ x + ' _END')lines.sample(6) START_ tag marks the start of the target sentences, and an _END tag marks the completion of the target sentence. Create a set of unique words both for source and target language from the dataset and sort them alphabetically # Find all the source and target words and sort them# Vocabulary of Source languageall_source_words=set()for source in lines.source: for word in source.split(): if word not in all_source_words: all_source_words.add(word)# Vocabulary of Target all_target_words=set()for target in lines.target: for word in target.split(): if word not in all_target_words: all_target_words.add(word)# sort all unique source and target wordssource_words= sorted(list(all_source_words))target_words=sorted(list(all_target_words)) Find the maximum length of the source and target sentences in the dataset #Find maximum sentence length in the source and target datasource_length_list=[]for l in lines.source: source_length_list.append(len(l.split(' ')))max_source_length= max(source_length_list)print(" Max length of the source sentence",max_source_length)target_length_list=[]for l in lines.target: target_length_list.append(len(l.split(' ')))max_target_length= max(target_length_list)print(" Max length of the target sentence",max_target_length) Create a word to index dictionary and an index to word dictionary for all unique source and target words in the dataset. Size of the word to vector will be based on the length of the source and target vocabulary # creating a word to index(word2idx) for source and targetsource_word2idx= dict([(word, i+1) for i,word in enumerate(source_words)])target_word2idx=dict([(word, i+1) for i, word in enumerate(target_words)]) #creating a dictionary for index to word for source and target vocabularysource_idx2word= dict([(i, word) for word, i in source_word2idx.items()])print(source_idx2word)target_idx2word =dict([(i, word) for word, i in target_word2idx.items()]) Shuffle the data Shuffling helps with Reducing variance Ensures models remain generic and overfit less Batches between epochs do not look alike Makes model more robust #Shuffle the datalines = shuffle(lines) # Train - Test SplitX, y = lines.source, lines.targetX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1)X_train.shape, X_test.shape We will use fit_generator() instead of the fit() method as our data is too large to fit into the memory. fit_generator() needs an underlying function to generate the data. We create the underlying function generate_batch() for generating data in batches The fit_generator() will accept a batch of data from the underlying function, generate_batch() To train a sequence to sequence model, we need to create one-hot encoded data for encoder inputs: The 2D array will be of shape (batch_size, max source sentence length). For a batch_size of 128 and a max source sentence length of 47, the shape of encoder_input will be (128,47) decoder inputs: The 2D array will be of shape (batch_size, max target sentence length). For a batch_size of 128 and a max target sentence length of 55, the shape of decoder inputs will be (128,55) decoder outputs: The 3D array will be of shape (batch_size, max target sentence length, number of unique words in target sentences). For a batch_size of 128 and a max target sentence length of 55, the shape of decoder output will be (128,55, 27200). Number of unique words in the target_sentence is 27199 which we zero pad, and hence the third parameter in decoder output is 27200 # Input tokens for encodernum_encoder_tokens=len(source_words)# Input tokens for decoder zero paddednum_decoder_tokens=len(target_words) +1 We now create the generator_batch function() def generate_batch(X = X_train, y = y_train, batch_size = 128): ''' Generate a batch of data ''' while True: for j in range(0, len(X), batch_size): encoder_input_data = np.zeros((batch_size, max_source_length),dtype='float32') decoder_input_data = np.zeros((batch_size, max_target_length),dtype='float32') decoder_target_data = np.zeros((batch_size, max_target_length, num_decoder_tokens),dtype='float32') for i, (input_text, target_text) in enumerate(zip(X[j:j+batch_size], y[j:j+batch_size])): for t, word in enumerate(input_text.split()):encoder_input_data[i, t] = source_word2idx[word] for t, word in enumerate(target_text.split()): if t<len(target_text.split())-1: decoder_input_data[i, t] = target_word2idx[word] # decoder input seq if t>0: # decoder target sequence (one hot encoded) # does not include the START_ token # Offset by one timestep #print(word) decoder_target_data[i, t - 1, target_word2idx[word]] = 1. yield([encoder_input_data, decoder_input_data], decoder_target_data) We will use Teacher Forcing to train the sequence to sequence model for faster and efficient training of the decoder. Teacher forcing algorithm trains decoder by supplying the actual output of the previous timestamp instead of the predicted output from the last time step as inputs during training. Decoder learns to generate a word at t+1 timestep, taking into account the actual output at time step t and the encoder’s internal state; hence we offset the decoder output by one timestep. Setup basic parameters We set the necessary parameters like number of training samples number of validation samples batch_size used for creating the training data Epochs to train on The latent dimension of the encoding space train_samples = len(X_train)val_samples = len(X_test)batch_size = 128epochs = 50latent_dim=256 Build the encoder and decoder using LSTM. The encoder will encode the input sentences of the source language. Hidden state and the cell state of the encoder will be passed as input to the decoder along with actual target sequences. The encoder will encode the input sequence. We pass the input through the input layer. The first hidden layer will be the embedding layer. Embeddings translate large sparse vectors into a dense lower-dimensional space preserving the semantic relationships. Pass three parameters to Embedding(); the first parameter is the size of the vocabulary; the second parameter is the dimension of the dense Embedding. We set mask_zero as True as this implies that the input value of 0 is a special “padding” value that should be masked out. Create the LSTM layer and only set return_state to True as we want to retain the hidden state and cell state of the encoder. We discard the encoder_output and preserve the hidden state and cell state of the LSTM to be passed to the decoder # Define an input sequence and process it.encoder_inputs = Input(shape=(None,))enc_emb = Embedding(num_encoder_tokens, latent_dim, mask_zero = True)(encoder_inputs)encoder_lstm = LSTM(latent_dim, return_state=True)encoder_outputs, state_h, state_c = encoder_lstm(enc_emb)# We discard `encoder_outputs` and only keep the states.encoder_states = [state_h, state_c] We create an input layer for the decoder_inputs; Embedding is again the first hidden layer in the decoder. The LSTM layer will return output sequences as well as the internal states. The internal states will be used only during the inference phase and will not be used during the training phase. LSTM in the decoder takes input from the embedding layer and the encoder states. We apply a softmax activation to the Dense layer and then finally generate the decoder outputs # Set up the decoder, using `encoder_states` as initial state.decoder_inputs = Input(shape=(None,))dec_emb_layer = Embedding(num_decoder_tokens, latent_dim, mask_zero = True)dec_emb = dec_emb_layer(decoder_inputs)# We set up our decoder to return full output sequences,# and to return internal states as well. We don't use the# return states in the training model, but we will use them in inference.decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True)decoder_outputs, _, _ = decoder_lstm(dec_emb, initial_state=encoder_states)decoder_dense = Dense(num_decoder_tokens, activation='softmax')decoder_outputs = decoder_dense(decoder_outputs) Define the model The sequence to sequence model takes encoder and decoder inputs to output decoder outputs # Define the model that takes encoder and decoder input # to output decoder_outputsmodel = Model([encoder_inputs, decoder_inputs], decoder_outputs) To train the model, we first compile the model and then fit the data to the model We compile the model using “rmsprop” optimizer; use categorical_crossentropy as we use categorical labels which is one-hot encoded vectors model.compile(optimizer=’rmsprop’, loss=’categorical_crossentropy’, metrics=[‘acc’]) setup the parameters to fit the model train_samples = len(X_train) # Total Training samplesval_samples = len(X_test) # Total validation or test samplesbatch_size = 128epochs = 100 Fit the model using fit_generator(). we had already created the underlying function for generating the data, generate_batch() for generating the training and the test dataset. steps_per_epoch is computed by dividing the total number of training samples by the batch size. When we reach the step count, we start with a new epoch model.fit_generator(generator = generate_batch(X_train, y_train, batch_size = batch_size), steps_per_epoch = train_samples//batch_size, epochs=epochs, validation_data = generate_batch(X_test, y_test, batch_size = batch_size), validation_steps = val_samples//batch_size) Save the weights so that you can load them later for inference model.save_weights(‘nmt_weights_100epochs.h5’) Weights can be loaded from the saved weights file model.load_weights('nmt_weights_100epochs.h5') During inference, we want to decode unknown input sequences to predict the output. Steps for inference Encode the input sequences into hidden state and cell state of the LSTM The decoder will predict one sequence at a time. The first input to the decoder will be hidden state and cell state of the encoder and the START_ tag The output of the decoder will be fed as an input to the decoder for the next time step as shown in the diagram below At each time step, decoder outputs one-hot encoded vector to which we apply np.argmax and convert the vector to word from the dictionary that stores index to word Keep appending the target words generated at each time step Repeat the steps till we hit the _END tag or the word limit Define the inference model # Encode the input sequence to get the "Context vectors"encoder_model = Model(encoder_inputs, encoder_states)# Decoder setup# Below tensors will hold the states of the previous time stepdecoder_state_input_h = Input(shape=(latent_dim,))decoder_state_input_c = Input(shape=(latent_dim,))decoder_state_input = [decoder_state_input_h, decoder_state_input_c]# Get the embeddings of the decoder sequencedec_emb2= dec_emb_layer(decoder_inputs)# To predict the next word in the sequence, set the initial states to the states from the previous time stepdecoder_outputs2, state_h2, state_c2 = decoder_lstm(dec_emb2, initial_state=decoder_state_input)decoder_states2 = [state_h2, state_c2]# A dense softmax layer to generate prob dist. over the target vocabularydecoder_outputs2 = decoder_dense(decoder_outputs2)# Final decoder modeldecoder_model = Model( [decoder_inputs] + decoder_state_input, [decoder_outputs2] + decoder_states2) Create a function for inference lookup def decode_sequence(input_seq): # Encode the input as state vectors. states_value = encoder_model.predict(input_seq) # Generate empty target sequence of length 1. target_seq = np.zeros((1,1)) # Populate the first character of #target sequence with the start character. target_seq[0, 0] = target_word2idx['START_']# Sampling loop for a batch of sequences # (to simplify, here we assume a batch of size 1). stop_condition = False decoded_sentence = '' while not stop_condition: output_tokens, h, c = decoder_model.predict([target_seq] + states_value)# Sample a token sampled_token_index = np.argmax(output_tokens[0, -1, :]) sampled_word =target_idx2word[sampled_token_index] decoded_sentence += ' '+ sampled_word# Exit condition: either hit max length # or find stop character. if (sampled_word == '_END' or len(decoded_sentence) > 50): stop_condition = True# Update the target sequence (of length 1). target_seq = np.zeros((1,1)) target_seq[0, 0] = sampled_token_index# Update states states_value = [h, c]return decoded_sentence train_gen = generate_batch(X_train, y_train, batch_size = 1)k=-1 Pass a source sentence and then compare the predicted output to actual output k+=1(input_seq, actual_output), _ = next(train_gen)decoded_sentence = decode_sequence(input_seq)print(‘Input Source sentence:’, X_train[k:k+1].values[0])print(‘Actual Target Translation:’, y_train[k:k+1].values[0][6:-4])print(‘Predicted Target Translation:’, decoded_sentence[:-4]) test_gen = generate_batch(X_test, y_test, batch_size = 1)k=10k+=1(input_seq, actual_output), _ = next(test_gen)decoded_sentence = decode_sequence(input_seq)print('Input Source sentence:', X_test[k:k+1].values[0])print('Actual Target Translation:', y_test[k:k+1].values[0][6:-4])print('Predicted Target Translation:', decoded_sentence[:-4]) Some predictions were good, some reasonable and some not right. Additional enhancements to the model We can replace LSTM’s will GRU, add more LSTM/GRU nodes, train for more epochs and use attention mechanism
[ { "code": null, "e": 397, "s": 171, "text": "In this article, you get a step by step explanation of building a neural machine translator using English as the source language and Spanish as the target language. We will be using Long Short Term Memory(LSTM) units in keras" }, { "code": null, "e": 420, "s": 397, "text": "towardsdatascience.com" }, { "code": null, "e": 549, "s": 420, "text": "In this article, we will create a Sequence to Sequence model using an encoder and decoder framework with LSTM as the basic block" }, { "code": null, "e": 740, "s": 549, "text": "Sequence to Sequence model maps a source sequence to target sequence. The source sequence is input language to the machine translation system, and the target sequence is the output language." }, { "code": null, "e": 925, "s": 740, "text": "A step by step implementation of a neural machine translation(NMT) using Teacher forcing without Attention mechanism. Implementation is using keras library with LSTM as the basic block" }, { "code": null, "e": 999, "s": 925, "text": "Reading the data from the file containing the source and target sentences" }, { "code": null, "e": 1101, "s": 999, "text": "Cleaning the data by converting to lowercase, removing spaces, special characters, digits, and quotes" }, { "code": null, "e": 1208, "s": 1101, "text": "Tag the start and end of the target sentence using START_ and _END respectively for training and inference" }, { "code": null, "e": 1289, "s": 1208, "text": "Create the dictionary of unique source and target words to vector and vice-versa" }, { "code": null, "e": 1332, "s": 1289, "text": "Shuffle the data for better generalization" }, { "code": null, "e": 1375, "s": 1332, "text": "Split the dataset into train and test data" }, { "code": null, "e": 1454, "s": 1375, "text": "Create the data; we will be using fit_generator() to fit the data to the model" }, { "code": null, "e": 1504, "s": 1454, "text": "Build the encoder using Embedding and LSTM layers" }, { "code": null, "e": 1619, "s": 1504, "text": "Build the decoder using Embedding and LSTM layers and takes input from the embedding layer and the encoder states." }, { "code": null, "e": 1657, "s": 1619, "text": "Compile the model and train the model" }, { "code": null, "e": 1689, "s": 1657, "text": "Make predictions from the model" }, { "code": null, "e": 1719, "s": 1689, "text": "Import the required libraries" }, { "code": null, "e": 2022, "s": 1719, "text": "import pandas as pdimport numpy as npimport stringfrom string import digitsimport matplotlib.pyplot as plt%matplotlib inlineimport refrom sklearn.utils import shufflefrom sklearn.model_selection import train_test_splitfrom keras.layers import Input, LSTM, Embedding, Densefrom keras.models import Model" }, { "code": null, "e": 2116, "s": 2022, "text": "Read the file that contains the English-Spanish translations that we downloaded from the here" }, { "code": null, "e": 2346, "s": 2116, "text": "# Path to the data txt file on disk.data_path = \"\\\\NMT\\\\spa-eng\\\\spa.txt\"# open the file eng-spa.txt and readlines= pd.read_table(data_path, names =['source', 'target', 'comments'])#printing sample data from lineslines.sample(6)" }, { "code": null, "e": 2383, "s": 2346, "text": "We apply the following text cleaning" }, { "code": null, "e": 2410, "s": 2383, "text": "Convert text to lower case" }, { "code": null, "e": 2424, "s": 2410, "text": "Remove quotes" }, { "code": null, "e": 2487, "s": 2424, "text": "Remove all special characters like “@, !, *, $, #, ?, %, etc.”" }, { "code": null, "e": 2640, "s": 2487, "text": "Clean digits from the source and target sentences. If the source or the target language use different symbols for the numbers, then remove those symbols" }, { "code": null, "e": 2654, "s": 2640, "text": "Remove spaces" }, { "code": null, "e": 3778, "s": 2654, "text": "# convert source and target text to Lowercase lines.source=lines.source.apply(lambda x: x.lower())lines.target=lines.target.apply(lambda x: x.lower())# Remove quotes from source and target textlines.source=lines.source.apply(lambda x: re.sub(\"'\", '', x))lines.target=lines.target.apply(lambda x: re.sub(\"'\", '', x))# create a set of all special charactersspecial_characters= set(string.punctuation)# Remove all the special characterslines.source = lines.source.apply(lambda x: ''.join(char1 for char1 in x if char1 not in special_characters))lines.target = lines.target.apply(lambda x: ''.join(char1 for char1 in x if char1 not in special_characters))# Remove digits from source and target sentencesnum_digits= str.maketrans('','', digits)lines.source=lines.source.apply(lambda x: x.translate(num_digits))lines.target= lines.target.apply(lambda x: x.translate(num_digits))# Remove extra spaceslines.source=lines.source.apply(lambda x: x.strip())lines.target=lines.target.apply(lambda x: x.strip())lines.source=lines.source.apply(lambda x: re.sub(\" +\", \" \", x))lines.target=lines.target.apply(lambda x: re.sub(\" +\", \" \", x))" }, { "code": null, "e": 3976, "s": 3778, "text": "Adding the START_ and the _END token to the target sentences is very useful for training and during inference. These tags help to know when to start the translation and when to end the translation." }, { "code": null, "e": 4106, "s": 3976, "text": "# Add start and end tokens to target sequenceslines.target = lines.target.apply(lambda x : 'START_ '+ x + ' _END')lines.sample(6)" }, { "code": null, "e": 4219, "s": 4106, "text": "START_ tag marks the start of the target sentences, and an _END tag marks the completion of the target sentence." }, { "code": null, "e": 4330, "s": 4219, "text": "Create a set of unique words both for source and target language from the dataset and sort them alphabetically" }, { "code": null, "e": 4881, "s": 4330, "text": "# Find all the source and target words and sort them# Vocabulary of Source languageall_source_words=set()for source in lines.source: for word in source.split(): if word not in all_source_words: all_source_words.add(word)# Vocabulary of Target all_target_words=set()for target in lines.target: for word in target.split(): if word not in all_target_words: all_target_words.add(word)# sort all unique source and target wordssource_words= sorted(list(all_source_words))target_words=sorted(list(all_target_words))" }, { "code": null, "e": 4955, "s": 4881, "text": "Find the maximum length of the source and target sentences in the dataset" }, { "code": null, "e": 5404, "s": 4955, "text": "#Find maximum sentence length in the source and target datasource_length_list=[]for l in lines.source: source_length_list.append(len(l.split(' ')))max_source_length= max(source_length_list)print(\" Max length of the source sentence\",max_source_length)target_length_list=[]for l in lines.target: target_length_list.append(len(l.split(' ')))max_target_length= max(target_length_list)print(\" Max length of the target sentence\",max_target_length)" }, { "code": null, "e": 5525, "s": 5404, "text": "Create a word to index dictionary and an index to word dictionary for all unique source and target words in the dataset." }, { "code": null, "e": 5616, "s": 5525, "text": "Size of the word to vector will be based on the length of the source and target vocabulary" }, { "code": null, "e": 5823, "s": 5616, "text": "# creating a word to index(word2idx) for source and targetsource_word2idx= dict([(word, i+1) for i,word in enumerate(source_words)])target_word2idx=dict([(word, i+1) for i, word in enumerate(target_words)])" }, { "code": null, "e": 6066, "s": 5823, "text": "#creating a dictionary for index to word for source and target vocabularysource_idx2word= dict([(i, word) for word, i in source_word2idx.items()])print(source_idx2word)target_idx2word =dict([(i, word) for word, i in target_word2idx.items()])" }, { "code": null, "e": 6083, "s": 6066, "text": "Shuffle the data" }, { "code": null, "e": 6104, "s": 6083, "text": "Shuffling helps with" }, { "code": null, "e": 6122, "s": 6104, "text": "Reducing variance" }, { "code": null, "e": 6169, "s": 6122, "text": "Ensures models remain generic and overfit less" }, { "code": null, "e": 6210, "s": 6169, "text": "Batches between epochs do not look alike" }, { "code": null, "e": 6234, "s": 6210, "text": "Makes model more robust" }, { "code": null, "e": 6274, "s": 6234, "text": "#Shuffle the datalines = shuffle(lines)" }, { "code": null, "e": 6429, "s": 6274, "text": "# Train - Test SplitX, y = lines.source, lines.targetX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1)X_train.shape, X_test.shape" }, { "code": null, "e": 6601, "s": 6429, "text": "We will use fit_generator() instead of the fit() method as our data is too large to fit into the memory. fit_generator() needs an underlying function to generate the data." }, { "code": null, "e": 6683, "s": 6601, "text": "We create the underlying function generate_batch() for generating data in batches" }, { "code": null, "e": 6778, "s": 6683, "text": "The fit_generator() will accept a batch of data from the underlying function, generate_batch()" }, { "code": null, "e": 6860, "s": 6778, "text": "To train a sequence to sequence model, we need to create one-hot encoded data for" }, { "code": null, "e": 7056, "s": 6860, "text": "encoder inputs: The 2D array will be of shape (batch_size, max source sentence length). For a batch_size of 128 and a max source sentence length of 47, the shape of encoder_input will be (128,47)" }, { "code": null, "e": 7253, "s": 7056, "text": "decoder inputs: The 2D array will be of shape (batch_size, max target sentence length). For a batch_size of 128 and a max target sentence length of 55, the shape of decoder inputs will be (128,55)" }, { "code": null, "e": 7503, "s": 7253, "text": "decoder outputs: The 3D array will be of shape (batch_size, max target sentence length, number of unique words in target sentences). For a batch_size of 128 and a max target sentence length of 55, the shape of decoder output will be (128,55, 27200)." }, { "code": null, "e": 7634, "s": 7503, "text": "Number of unique words in the target_sentence is 27199 which we zero pad, and hence the third parameter in decoder output is 27200" }, { "code": null, "e": 7774, "s": 7634, "text": "# Input tokens for encodernum_encoder_tokens=len(source_words)# Input tokens for decoder zero paddednum_decoder_tokens=len(target_words) +1" }, { "code": null, "e": 7819, "s": 7774, "text": "We now create the generator_batch function()" }, { "code": null, "e": 9106, "s": 7819, "text": "def generate_batch(X = X_train, y = y_train, batch_size = 128): ''' Generate a batch of data ''' while True: for j in range(0, len(X), batch_size): encoder_input_data = np.zeros((batch_size, max_source_length),dtype='float32') decoder_input_data = np.zeros((batch_size, max_target_length),dtype='float32') decoder_target_data = np.zeros((batch_size, max_target_length, num_decoder_tokens),dtype='float32') for i, (input_text, target_text) in enumerate(zip(X[j:j+batch_size], y[j:j+batch_size])): for t, word in enumerate(input_text.split()):encoder_input_data[i, t] = source_word2idx[word] for t, word in enumerate(target_text.split()): if t<len(target_text.split())-1: decoder_input_data[i, t] = target_word2idx[word] # decoder input seq if t>0: # decoder target sequence (one hot encoded) # does not include the START_ token # Offset by one timestep #print(word) decoder_target_data[i, t - 1, target_word2idx[word]] = 1. yield([encoder_input_data, decoder_input_data], decoder_target_data)" }, { "code": null, "e": 9224, "s": 9106, "text": "We will use Teacher Forcing to train the sequence to sequence model for faster and efficient training of the decoder." }, { "code": null, "e": 9405, "s": 9224, "text": "Teacher forcing algorithm trains decoder by supplying the actual output of the previous timestamp instead of the predicted output from the last time step as inputs during training." }, { "code": null, "e": 9595, "s": 9405, "text": "Decoder learns to generate a word at t+1 timestep, taking into account the actual output at time step t and the encoder’s internal state; hence we offset the decoder output by one timestep." }, { "code": null, "e": 9618, "s": 9595, "text": "Setup basic parameters" }, { "code": null, "e": 9655, "s": 9618, "text": "We set the necessary parameters like" }, { "code": null, "e": 9682, "s": 9655, "text": "number of training samples" }, { "code": null, "e": 9711, "s": 9682, "text": "number of validation samples" }, { "code": null, "e": 9758, "s": 9711, "text": "batch_size used for creating the training data" }, { "code": null, "e": 9777, "s": 9758, "text": "Epochs to train on" }, { "code": null, "e": 9820, "s": 9777, "text": "The latent dimension of the encoding space" }, { "code": null, "e": 9915, "s": 9820, "text": "train_samples = len(X_train)val_samples = len(X_test)batch_size = 128epochs = 50latent_dim=256" }, { "code": null, "e": 10147, "s": 9915, "text": "Build the encoder and decoder using LSTM. The encoder will encode the input sentences of the source language. Hidden state and the cell state of the encoder will be passed as input to the decoder along with actual target sequences." }, { "code": null, "e": 10404, "s": 10147, "text": "The encoder will encode the input sequence. We pass the input through the input layer. The first hidden layer will be the embedding layer. Embeddings translate large sparse vectors into a dense lower-dimensional space preserving the semantic relationships." }, { "code": null, "e": 10678, "s": 10404, "text": "Pass three parameters to Embedding(); the first parameter is the size of the vocabulary; the second parameter is the dimension of the dense Embedding. We set mask_zero as True as this implies that the input value of 0 is a special “padding” value that should be masked out." }, { "code": null, "e": 10918, "s": 10678, "text": "Create the LSTM layer and only set return_state to True as we want to retain the hidden state and cell state of the encoder. We discard the encoder_output and preserve the hidden state and cell state of the LSTM to be passed to the decoder" }, { "code": null, "e": 11282, "s": 10918, "text": "# Define an input sequence and process it.encoder_inputs = Input(shape=(None,))enc_emb = Embedding(num_encoder_tokens, latent_dim, mask_zero = True)(encoder_inputs)encoder_lstm = LSTM(latent_dim, return_state=True)encoder_outputs, state_h, state_c = encoder_lstm(enc_emb)# We discard `encoder_outputs` and only keep the states.encoder_states = [state_h, state_c]" }, { "code": null, "e": 11389, "s": 11282, "text": "We create an input layer for the decoder_inputs; Embedding is again the first hidden layer in the decoder." }, { "code": null, "e": 11578, "s": 11389, "text": "The LSTM layer will return output sequences as well as the internal states. The internal states will be used only during the inference phase and will not be used during the training phase." }, { "code": null, "e": 11754, "s": 11578, "text": "LSTM in the decoder takes input from the embedding layer and the encoder states. We apply a softmax activation to the Dense layer and then finally generate the decoder outputs" }, { "code": null, "e": 12449, "s": 11754, "text": "# Set up the decoder, using `encoder_states` as initial state.decoder_inputs = Input(shape=(None,))dec_emb_layer = Embedding(num_decoder_tokens, latent_dim, mask_zero = True)dec_emb = dec_emb_layer(decoder_inputs)# We set up our decoder to return full output sequences,# and to return internal states as well. We don't use the# return states in the training model, but we will use them in inference.decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True)decoder_outputs, _, _ = decoder_lstm(dec_emb, initial_state=encoder_states)decoder_dense = Dense(num_decoder_tokens, activation='softmax')decoder_outputs = decoder_dense(decoder_outputs)" }, { "code": null, "e": 12466, "s": 12449, "text": "Define the model" }, { "code": null, "e": 12556, "s": 12466, "text": "The sequence to sequence model takes encoder and decoder inputs to output decoder outputs" }, { "code": null, "e": 12704, "s": 12556, "text": "# Define the model that takes encoder and decoder input # to output decoder_outputsmodel = Model([encoder_inputs, decoder_inputs], decoder_outputs)" }, { "code": null, "e": 12786, "s": 12704, "text": "To train the model, we first compile the model and then fit the data to the model" }, { "code": null, "e": 12925, "s": 12786, "text": "We compile the model using “rmsprop” optimizer; use categorical_crossentropy as we use categorical labels which is one-hot encoded vectors" }, { "code": null, "e": 13010, "s": 12925, "text": "model.compile(optimizer=’rmsprop’, loss=’categorical_crossentropy’, metrics=[‘acc’])" }, { "code": null, "e": 13048, "s": 13010, "text": "setup the parameters to fit the model" }, { "code": null, "e": 13193, "s": 13048, "text": "train_samples = len(X_train) # Total Training samplesval_samples = len(X_test) # Total validation or test samplesbatch_size = 128epochs = 100" }, { "code": null, "e": 13369, "s": 13193, "text": "Fit the model using fit_generator(). we had already created the underlying function for generating the data, generate_batch() for generating the training and the test dataset." }, { "code": null, "e": 13521, "s": 13369, "text": "steps_per_epoch is computed by dividing the total number of training samples by the batch size. When we reach the step count, we start with a new epoch" }, { "code": null, "e": 13867, "s": 13521, "text": "model.fit_generator(generator = generate_batch(X_train, y_train, batch_size = batch_size), steps_per_epoch = train_samples//batch_size, epochs=epochs, validation_data = generate_batch(X_test, y_test, batch_size = batch_size), validation_steps = val_samples//batch_size)" }, { "code": null, "e": 13930, "s": 13867, "text": "Save the weights so that you can load them later for inference" }, { "code": null, "e": 13977, "s": 13930, "text": "model.save_weights(‘nmt_weights_100epochs.h5’)" }, { "code": null, "e": 14027, "s": 13977, "text": "Weights can be loaded from the saved weights file" }, { "code": null, "e": 14074, "s": 14027, "text": "model.load_weights('nmt_weights_100epochs.h5')" }, { "code": null, "e": 14157, "s": 14074, "text": "During inference, we want to decode unknown input sequences to predict the output." }, { "code": null, "e": 14177, "s": 14157, "text": "Steps for inference" }, { "code": null, "e": 14249, "s": 14177, "text": "Encode the input sequences into hidden state and cell state of the LSTM" }, { "code": null, "e": 14399, "s": 14249, "text": "The decoder will predict one sequence at a time. The first input to the decoder will be hidden state and cell state of the encoder and the START_ tag" }, { "code": null, "e": 14517, "s": 14399, "text": "The output of the decoder will be fed as an input to the decoder for the next time step as shown in the diagram below" }, { "code": null, "e": 14680, "s": 14517, "text": "At each time step, decoder outputs one-hot encoded vector to which we apply np.argmax and convert the vector to word from the dictionary that stores index to word" }, { "code": null, "e": 14740, "s": 14680, "text": "Keep appending the target words generated at each time step" }, { "code": null, "e": 14800, "s": 14740, "text": "Repeat the steps till we hit the _END tag or the word limit" }, { "code": null, "e": 14827, "s": 14800, "text": "Define the inference model" }, { "code": null, "e": 15757, "s": 14827, "text": "# Encode the input sequence to get the \"Context vectors\"encoder_model = Model(encoder_inputs, encoder_states)# Decoder setup# Below tensors will hold the states of the previous time stepdecoder_state_input_h = Input(shape=(latent_dim,))decoder_state_input_c = Input(shape=(latent_dim,))decoder_state_input = [decoder_state_input_h, decoder_state_input_c]# Get the embeddings of the decoder sequencedec_emb2= dec_emb_layer(decoder_inputs)# To predict the next word in the sequence, set the initial states to the states from the previous time stepdecoder_outputs2, state_h2, state_c2 = decoder_lstm(dec_emb2, initial_state=decoder_state_input)decoder_states2 = [state_h2, state_c2]# A dense softmax layer to generate prob dist. over the target vocabularydecoder_outputs2 = decoder_dense(decoder_outputs2)# Final decoder modeldecoder_model = Model( [decoder_inputs] + decoder_state_input, [decoder_outputs2] + decoder_states2)" }, { "code": null, "e": 15796, "s": 15757, "text": "Create a function for inference lookup" }, { "code": null, "e": 16942, "s": 15796, "text": "def decode_sequence(input_seq): # Encode the input as state vectors. states_value = encoder_model.predict(input_seq) # Generate empty target sequence of length 1. target_seq = np.zeros((1,1)) # Populate the first character of #target sequence with the start character. target_seq[0, 0] = target_word2idx['START_']# Sampling loop for a batch of sequences # (to simplify, here we assume a batch of size 1). stop_condition = False decoded_sentence = '' while not stop_condition: output_tokens, h, c = decoder_model.predict([target_seq] + states_value)# Sample a token sampled_token_index = np.argmax(output_tokens[0, -1, :]) sampled_word =target_idx2word[sampled_token_index] decoded_sentence += ' '+ sampled_word# Exit condition: either hit max length # or find stop character. if (sampled_word == '_END' or len(decoded_sentence) > 50): stop_condition = True# Update the target sequence (of length 1). target_seq = np.zeros((1,1)) target_seq[0, 0] = sampled_token_index# Update states states_value = [h, c]return decoded_sentence" }, { "code": null, "e": 17007, "s": 16942, "text": "train_gen = generate_batch(X_train, y_train, batch_size = 1)k=-1" }, { "code": null, "e": 17085, "s": 17007, "text": "Pass a source sentence and then compare the predicted output to actual output" }, { "code": null, "e": 17367, "s": 17085, "text": "k+=1(input_seq, actual_output), _ = next(train_gen)decoded_sentence = decode_sequence(input_seq)print(‘Input Source sentence:’, X_train[k:k+1].values[0])print(‘Actual Target Translation:’, y_train[k:k+1].values[0][6:-4])print(‘Predicted Target Translation:’, decoded_sentence[:-4])" }, { "code": null, "e": 17707, "s": 17367, "text": "test_gen = generate_batch(X_test, y_test, batch_size = 1)k=10k+=1(input_seq, actual_output), _ = next(test_gen)decoded_sentence = decode_sequence(input_seq)print('Input Source sentence:', X_test[k:k+1].values[0])print('Actual Target Translation:', y_test[k:k+1].values[0][6:-4])print('Predicted Target Translation:', decoded_sentence[:-4])" }, { "code": null, "e": 17771, "s": 17707, "text": "Some predictions were good, some reasonable and some not right." }, { "code": null, "e": 17808, "s": 17771, "text": "Additional enhancements to the model" } ]
How to create MongoDB stored procedure?
The following is the syntax to create MongoDB stored procedure − db.system.js.save ( { _id:"yourStoredProcedueName", value:function(argument1,....N) { statement1, . . N } } ); Now implement the above syntax. The query to create a stored procedure is as follows − > db.system.js.save ( { _id:"addTwoValue", value:function(a,b) { return a+b } } ); The following is the output − WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : "addTwoValue" }) Now you can call the stored procedure using eval(). The query is as follows − > db.eval("return addTwoValue(100,25)"); 125
[ { "code": null, "e": 1127, "s": 1062, "text": "The following is the syntax to create MongoDB stored procedure −" }, { "code": null, "e": 1304, "s": 1127, "text": "db.system.js.save\n(\n {\n _id:\"yourStoredProcedueName\",\n value:function(argument1,....N)\n {\n statement1,\n .\n .\n N\n }\n }\n);" }, { "code": null, "e": 1391, "s": 1304, "text": "Now implement the above syntax. The query to create a stored procedure is as follows −" }, { "code": null, "e": 1513, "s": 1391, "text": "> db.system.js.save\n(\n {\n _id:\"addTwoValue\",\n value:function(a,b)\n {\n return a+b\n }\n }\n);" }, { "code": null, "e": 1543, "s": 1513, "text": "The following is the output −" }, { "code": null, "e": 1632, "s": 1543, "text": "WriteResult({ \"nMatched\" : 0, \"nUpserted\" : 1, \"nModified\" : 0, \"_id\" : \"addTwoValue\" })" }, { "code": null, "e": 1710, "s": 1632, "text": "Now you can call the stored procedure using eval(). The query is as follows −" }, { "code": null, "e": 1755, "s": 1710, "text": "> db.eval(\"return addTwoValue(100,25)\");\n125" } ]
Security Testing - HTTP Methods
The set of common methods for HTTP/1.1 is defined below and this set can be expanded based on requirement. These method names are case sensitive and they must be used in uppercase. GET It is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data. HEAD It is same as GET, but only transfers the status line and header section. POST It is used to send data to the server. For example, customer information, file uploading etc. using HTML forms. PUT It replaces all current representations of the target resource with the uploaded content. DELETE It removes all current representations of the target resource given by URI. CONNECT It establishes a tunnel to the server identified by a given URI. OPTIONS It describes the communication options for the target resource. TRACE It performs a message loop-back test along the path to the target resource. It retrieves data from a web server by specifying parameters in the URL portion of the request. This is the main method used for document retrieval. The following example makes use of GET method to fetch hello.htm − GET /hello.htm HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.tutorialspoint.com Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive The following server response is issued against the above GET request − HTTP/1.1 200 OK Date: Mon, 27 Jul 2009 12:28:53 GMT Server: Apache/2.2.14 (Win32) Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT ETag: "34aa387-d-1568eb00" Vary: Authorization,Accept Accept-Ranges: bytes Content-Length: 88 Content-Type: text/html Connection: Closed <html> <body> <h1>Hello, World!</h1> </body> </html> It is functionally similar to GET, except that the server replies with a response line and headers, but no entity-body. The following example makes use of HEAD method to fetch header information about hello.htm − HEAD /hello.htm HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.tutorialspoint.com Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive The following server response is issued against the above GET request − HTTP/1.1 200 OK Date: Mon, 27 Jul 2009 12:28:53 GMT Server: Apache/2.2.14 (Win32) Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT ETag: "34aa387-d-1568eb00" Vary: Authorization,Accept Accept-Ranges: bytes Content-Length: 88 Content-Type: text/html Connection: Closed You can notice that the server does not send any data after header. It is used when you want to send some data to the server. For example, file update, form data etc. The following simple example makes use of POST method to send a form data to the server which is processed by a process.cgi and finally a response is returned − POST /cgi-bin/process.cgi HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.tutorialspoint.com Content-Type: text/xml; charset = utf-8 Content-Length: 88 Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive <?xml version = "1.0" encoding = "utf-8"?> <string xmlns = "http://clearforest.com/">string</string> Server side script process.cgi processes the passed data and sends the following response − HTTP/1.1 200 OK Date: Mon, 27 Jul 2009 12:28:53 GMT Server: Apache/2.2.14 (Win32) Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT ETag: "34aa387-d-1568eb00" Vary: Authorization,Accept Accept-Ranges: bytes Content-Length: 88 Content-Type: text/html Connection: Closed <html> <body> <h1>Request Processed Successfully</h1> </body> </html> The PUT method is used to request the server to store the included entity-body at a location specified by the given URL. The following example requests server to save the given entity-boy in hello.htm at the root of the server − PUT /hello.htm HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.tutorialspoint.com Accept-Language: en-us Connection: Keep-Alive Content-type: text/html Content-Length: 182 <html> <body> <h1>Hello, World!</h1> </body> </html> The server stores the given entity-body in hello.htm file and sends the following response back to the client − HTTP/1.1 201 Created Date: Mon, 27 Jul 2009 12:28:53 GMT Server: Apache/2.2.14 (Win32) Content-type: text/html Content-length: 30 Connection: Closed <html> <body> <h1>The file was created.</h1> </body> </html> The DELETE method is used to request the server to delete file at a location specified by the given URL. The following example requests server to delete the given file hello.htm at the root of the server − DELETE /hello.htm HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.tutorialspoint.com Accept-Language: en-us Connection: Keep-Alive The server deletes the mentioned file hello.htm and sends the following response back to the client − HTTP/1.1 200 OK Date: Mon, 27 Jul 2009 12:28:53 GMT Server: Apache/2.2.14 (Win32) Content-type: text/html Content-length: 30 Connection: Closed <html> <body> <h1>URL deleted.</h1> </body> </html> It is used by the client to establish a network connection to a web server over HTTP. The following example requests a connection with a web server running on host tutorialspoint.com − CONNECT www.tutorialspoint.com HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) The connection is established with the server and the following response is sent back to the client − HTTP/1.1 200 Connection established Date: Mon, 27 Jul 2009 12:28:53 GMT Server: Apache/2.2.14 (Win32) It is used by the client to find out what are the HTTP methods and other options supported by a web server. The client can specify a URL for the OPTIONS method, or an asterisk (*) to refer to the entire server. The following example requests a list of methods supported by a web server running on tutorialspoint.com − OPTIONS * HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) The server sends information based on the current configuration of the server, for example − HTTP/1.1 200 OK Date: Mon, 27 Jul 2009 12:28:53 GMT Server: Apache/2.2.14 (Win32) Allow: GET,HEAD,POST,OPTIONS,TRACE Content-Type: httpd/unix-directory It is used to echo the contents of an HTTP Request back to the requester which can be used for debugging purpose at the time of development. The following example shows the usage of TRACE method − TRACE / HTTP/1.1 Host: www.tutorialspoint.com User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) The server will send the following message in response of the above request − HTTP/1.1 200 OK Date: Mon, 27 Jul 2009 12:28:53 GMT Server: Apache/2.2.14 (Win32) Connection: close Content-Type: message/http Content-Length: 39 TRACE / HTTP/1.1 Host: www.tutorialspoint.com User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) 36 Lectures 5 hours Sharad Kumar 26 Lectures 2.5 hours Harshit Srivastava 47 Lectures 2 hours Dhabaleshwar Das 14 Lectures 1.5 hours Harshit Srivastava 38 Lectures 3 hours Harshit Srivastava 32 Lectures 3 hours Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2621, "s": 2440, "text": "The set of common methods for HTTP/1.1 is defined below and this set can be expanded based on requirement. These method names are case sensitive and they must be used in uppercase." }, { "code": null, "e": 2625, "s": 2621, "text": "GET" }, { "code": null, "e": 2791, "s": 2625, "text": "It is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data." }, { "code": null, "e": 2796, "s": 2791, "text": "HEAD" }, { "code": null, "e": 2870, "s": 2796, "text": "It is same as GET, but only transfers the status line and header section." }, { "code": null, "e": 2875, "s": 2870, "text": "POST" }, { "code": null, "e": 2987, "s": 2875, "text": "It is used to send data to the server. For example, customer information, file uploading etc. using HTML forms." }, { "code": null, "e": 2991, "s": 2987, "text": "PUT" }, { "code": null, "e": 3081, "s": 2991, "text": "It replaces all current representations of the target resource with the uploaded content." }, { "code": null, "e": 3088, "s": 3081, "text": "DELETE" }, { "code": null, "e": 3164, "s": 3088, "text": "It removes all current representations of the target resource given by URI." }, { "code": null, "e": 3172, "s": 3164, "text": "CONNECT" }, { "code": null, "e": 3237, "s": 3172, "text": "It establishes a tunnel to the server identified by a given URI." }, { "code": null, "e": 3245, "s": 3237, "text": "OPTIONS" }, { "code": null, "e": 3309, "s": 3245, "text": "It describes the communication options for the target resource." }, { "code": null, "e": 3315, "s": 3309, "text": "TRACE" }, { "code": null, "e": 3391, "s": 3315, "text": "It performs a message loop-back test along the path to the target resource." }, { "code": null, "e": 3607, "s": 3391, "text": "It retrieves data from a web server by specifying parameters in the URL portion of the request. This is the main method used for document retrieval. The following example makes use of GET method to fetch hello.htm −" }, { "code": null, "e": 3797, "s": 3607, "text": "GET /hello.htm HTTP/1.1\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\nHost: www.tutorialspoint.com\nAccept-Language: en-us\nAccept-Encoding: gzip, deflate\nConnection: Keep-Alive\n" }, { "code": null, "e": 3869, "s": 3797, "text": "The following server response is issued against the above GET request −" }, { "code": null, "e": 4199, "s": 3869, "text": "HTTP/1.1 200 OK\nDate: Mon, 27 Jul 2009 12:28:53 GMT\nServer: Apache/2.2.14 (Win32)\nLast-Modified: Wed, 22 Jul 2009 19:15:56 GMT\nETag: \"34aa387-d-1568eb00\"\nVary: Authorization,Accept\nAccept-Ranges: bytes\nContent-Length: 88\nContent-Type: text/html\nConnection: Closed\n\n<html>\n <body>\n <h1>Hello, World!</h1>\n </body>\n</html>" }, { "code": null, "e": 4412, "s": 4199, "text": "It is functionally similar to GET, except that the server replies with a response line and headers, but no entity-body. The following example makes use of HEAD method to fetch header information about hello.htm −" }, { "code": null, "e": 4605, "s": 4412, "text": " \nHEAD /hello.htm HTTP/1.1\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\nHost: www.tutorialspoint.com\nAccept-Language: en-us\nAccept-Encoding: gzip, deflate\nConnection: Keep-Alive\n" }, { "code": null, "e": 4677, "s": 4605, "text": "The following server response is issued against the above GET request −" }, { "code": null, "e": 4942, "s": 4677, "text": "HTTP/1.1 200 OK\nDate: Mon, 27 Jul 2009 12:28:53 GMT\nServer: Apache/2.2.14 (Win32)\nLast-Modified: Wed, 22 Jul 2009 19:15:56 GMT\nETag: \"34aa387-d-1568eb00\"\nVary: Authorization,Accept\nAccept-Ranges: bytes\nContent-Length: 88\nContent-Type: text/html\nConnection: Closed\n" }, { "code": null, "e": 5010, "s": 4942, "text": "You can notice that the server does not send any data after header." }, { "code": null, "e": 5270, "s": 5010, "text": "It is used when you want to send some data to the server. For example, file update, form data etc. The following simple example makes use of POST method to send a form data to the server which is processed by a process.cgi and finally a response is returned −" }, { "code": null, "e": 5631, "s": 5270, "text": "POST /cgi-bin/process.cgi HTTP/1.1\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\nHost: www.tutorialspoint.com\nContent-Type: text/xml; charset = utf-8\nContent-Length: 88\nAccept-Language: en-us\nAccept-Encoding: gzip, deflate\nConnection: Keep-Alive\n\n<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<string xmlns = \"http://clearforest.com/\">string</string>" }, { "code": null, "e": 5723, "s": 5631, "text": "Server side script process.cgi processes the passed data and sends the following response −" }, { "code": null, "e": 6070, "s": 5723, "text": "HTTP/1.1 200 OK\nDate: Mon, 27 Jul 2009 12:28:53 GMT\nServer: Apache/2.2.14 (Win32)\nLast-Modified: Wed, 22 Jul 2009 19:15:56 GMT\nETag: \"34aa387-d-1568eb00\"\nVary: Authorization,Accept\nAccept-Ranges: bytes\nContent-Length: 88\nContent-Type: text/html\nConnection: Closed\n\n<html>\n <body>\n <h1>Request Processed Successfully</h1>\n </body>\n</html>" }, { "code": null, "e": 6299, "s": 6070, "text": "The PUT method is used to request the server to store the included entity-body at a location specified by the given URL. The following example requests server to save the given entity-boy in hello.htm at the root of the server −" }, { "code": null, "e": 6567, "s": 6299, "text": "PUT /hello.htm HTTP/1.1\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\nHost: www.tutorialspoint.com\nAccept-Language: en-us\nConnection: Keep-Alive\nContent-type: text/html\nContent-Length: 182\n\n<html>\n <body>\n <h1>Hello, World!</h1>\n </body>\n</html>" }, { "code": null, "e": 6679, "s": 6567, "text": "The server stores the given entity-body in hello.htm file and sends the following response back to the client −" }, { "code": null, "e": 6902, "s": 6679, "text": "HTTP/1.1 201 Created\nDate: Mon, 27 Jul 2009 12:28:53 GMT\nServer: Apache/2.2.14 (Win32)\nContent-type: text/html\nContent-length: 30\nConnection: Closed\n\n<html>\n <body>\n <h1>The file was created.</h1>\n </body>\n</html>" }, { "code": null, "e": 7108, "s": 6902, "text": "The DELETE method is used to request the server to delete file at a location specified by the given URL. The following example requests server to delete the given file hello.htm at the root of the server −" }, { "code": null, "e": 7270, "s": 7108, "text": "DELETE /hello.htm HTTP/1.1\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\nHost: www.tutorialspoint.com\nAccept-Language: en-us\nConnection: Keep-Alive\n" }, { "code": null, "e": 7372, "s": 7270, "text": "The server deletes the mentioned file hello.htm and sends the following response back to the client −" }, { "code": null, "e": 7581, "s": 7372, "text": "HTTP/1.1 200 OK\nDate: Mon, 27 Jul 2009 12:28:53 GMT\nServer: Apache/2.2.14 (Win32)\nContent-type: text/html\nContent-length: 30\nConnection: Closed\n\n<html>\n <body>\n <h1>URL deleted.</h1>\n </body>\n</html>" }, { "code": null, "e": 7766, "s": 7581, "text": "It is used by the client to establish a network connection to a web server over HTTP. The following example requests a connection with a web server running on host tutorialspoint.com −" }, { "code": null, "e": 7866, "s": 7766, "text": "CONNECT www.tutorialspoint.com HTTP/1.1\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\n" }, { "code": null, "e": 7968, "s": 7866, "text": "The connection is established with the server and the following response is sent back to the client −" }, { "code": null, "e": 8071, "s": 7968, "text": "HTTP/1.1 200 Connection established\nDate: Mon, 27 Jul 2009 12:28:53 GMT\nServer: Apache/2.2.14 (Win32)\n" }, { "code": null, "e": 8389, "s": 8071, "text": "It is used by the client to find out what are the HTTP methods and other options supported by a web server. The client can specify a URL for the OPTIONS method, or an asterisk (*) to refer to the entire server. The following example requests a list of methods supported by a web server running on tutorialspoint.com −" }, { "code": null, "e": 8468, "s": 8389, "text": "OPTIONS * HTTP/1.1\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\n" }, { "code": null, "e": 8561, "s": 8468, "text": "The server sends information based on the current configuration of the server, for example −" }, { "code": null, "e": 8714, "s": 8561, "text": "HTTP/1.1 200 OK\nDate: Mon, 27 Jul 2009 12:28:53 GMT\nServer: Apache/2.2.14 (Win32)\nAllow: GET,HEAD,POST,OPTIONS,TRACE\nContent-Type: httpd/unix-directory\n" }, { "code": null, "e": 8911, "s": 8714, "text": "It is used to echo the contents of an HTTP Request back to the requester which can be used for debugging purpose at the time of development. The following example shows the usage of TRACE method −" }, { "code": null, "e": 9017, "s": 8911, "text": "TRACE / HTTP/1.1\nHost: www.tutorialspoint.com\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\n" }, { "code": null, "e": 9095, "s": 9017, "text": "The server will send the following message in response of the above request −" }, { "code": null, "e": 9348, "s": 9095, "text": "HTTP/1.1 200 OK\nDate: Mon, 27 Jul 2009 12:28:53 GMT\nServer: Apache/2.2.14 (Win32)\nConnection: close\nContent-Type: message/http\nContent-Length: 39\n\nTRACE / HTTP/1.1\nHost: www.tutorialspoint.com\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\n" }, { "code": null, "e": 9381, "s": 9348, "text": "\n 36 Lectures \n 5 hours \n" }, { "code": null, "e": 9395, "s": 9381, "text": " Sharad Kumar" }, { "code": null, "e": 9430, "s": 9395, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9450, "s": 9430, "text": " Harshit Srivastava" }, { "code": null, "e": 9483, "s": 9450, "text": "\n 47 Lectures \n 2 hours \n" }, { "code": null, "e": 9501, "s": 9483, "text": " Dhabaleshwar Das" }, { "code": null, "e": 9536, "s": 9501, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9556, "s": 9536, "text": " Harshit Srivastava" }, { "code": null, "e": 9589, "s": 9556, "text": "\n 38 Lectures \n 3 hours \n" }, { "code": null, "e": 9609, "s": 9589, "text": " Harshit Srivastava" }, { "code": null, "e": 9642, "s": 9609, "text": "\n 32 Lectures \n 3 hours \n" }, { "code": null, "e": 9662, "s": 9642, "text": " Harshit Srivastava" }, { "code": null, "e": 9669, "s": 9662, "text": " Print" }, { "code": null, "e": 9680, "s": 9669, "text": " Add Notes" } ]
DASK: A Guide to Process Large Datasets using Parallelization | by Paras Varshney | Towards Data Science
If you are dealing with a large amount of data and you are worried that Pandas’ data frame is unable to load it or NumPy arrays get stuck in between and you even need a much better and parallelized solution for your data processing and training machine learning models then dask open up a solution to this problem. Before diving into that, let’s see what actually is dask? Before diving-in deep, have you ever heard about Lazy-Loading? Check out how Vaex is dominating the market of loading huge datasets. towardsdatascience.com Dask is an extremely efficient open-source project that uses existing Python Apis and knowledge structures that makes it straightforward to modify between Numpy, Pandas, Scikit-learn into their Dask-powered equivalents. Also, Dask’s schedulers scale to thousand-node clusters and its algorithms are tested on a number of the most important supercomputers within the world. Does quality comes pre-installed inside your Anaconda but for pip you can get the complete one using this command: Conda installation for Dask: !conda install dask pip installation for Dask: !pip install “dask[complete]” Dask helps to parallelize Arrays, DataFrames, and Machine Learning for dealing with a large amount of data as: Arrays: Parallelized Numpy # Arrays implement the Numpy APIimport dask.array as dax = da.random.random(size=(10000, 10000), chunks=(1000, 1000))x + x.T - x.mean(axis=0) DataFrame: Parallelized Pandas # Dataframes implement the Pandas APIimport dask.dataframe as dddf = dd.read_csv('financial_dataset.csv')df.groupby(df.amount).balance.sum() Machine Learning: Parallelized Scikit-Learn # Dask-ML implements the Scikit-Learn APIfrom dask_ml.linear_model import LogisticRegressionlr = LogisticRegression()lr.fit(train, test) Most of the Dask API is very similar to the Pandas API so you can directly use the data frames of the Pandas in Dusk with a very similar command. To generate a discrete data frame you can just simply call the `read_csv()` method in the same way you used to call in Pandas or can easily convert a Pandas DataFrame into a Dask DataFrame. import dask.dataframe as ddfdd = ddf.from_pandas(df, npartitions=N) For the following benchmarking the machine used had a standard 4-core processor which stays standard for testing both frameworks. I have done a very simple yet interesting benchmark to show how fast is Dask DataFrame as compared to a traditional Pandas DataFrame for reading a dataset from a .csv file having 5 million records. Results: To read a 5M data file of size over 600MB Pandas DataFrame took around 6.2 seconds whereas the same task is performed by Dask DataFrame in much much less than a second time due to its impressive parallelization capabilities. Note: This test was done on a small dataset, but as soon as the size of data increases, this time difference in reading data gets exponentially high. You can use the code below to alter the benchmarking for a bigger dataset. In this Benchmark, I generated a 1Trillion sized array of random numbers using both Numpy Array as well as Dask Array. Result: As expected the results were pretty obvious as Numpy Array took a bit less than 8 seconds to compute whereas the Dask Array took negligible time! You can try out the same benchmark using the code below Dask helps in doing data analysis faster because it parallelizes the existing frameworks like Pandas, Numpy, Scikit-Learn, and process data parallelly using the full potential of your machine’s CPU. You can try experimenting with the amazing features of Dask here. The combination of Lazy Loading with Parallel Processing is really a deadly combination and helps you to utilize the full potential of your system whenever required, to know more you can read this article about Vaex.
[ { "code": null, "e": 544, "s": 171, "text": "If you are dealing with a large amount of data and you are worried that Pandas’ data frame is unable to load it or NumPy arrays get stuck in between and you even need a much better and parallelized solution for your data processing and training machine learning models then dask open up a solution to this problem. Before diving into that, let’s see what actually is dask?" }, { "code": null, "e": 677, "s": 544, "text": "Before diving-in deep, have you ever heard about Lazy-Loading? Check out how Vaex is dominating the market of loading huge datasets." }, { "code": null, "e": 700, "s": 677, "text": "towardsdatascience.com" }, { "code": null, "e": 1073, "s": 700, "text": "Dask is an extremely efficient open-source project that uses existing Python Apis and knowledge structures that makes it straightforward to modify between Numpy, Pandas, Scikit-learn into their Dask-powered equivalents. Also, Dask’s schedulers scale to thousand-node clusters and its algorithms are tested on a number of the most important supercomputers within the world." }, { "code": null, "e": 1188, "s": 1073, "text": "Does quality comes pre-installed inside your Anaconda but for pip you can get the complete one using this command:" }, { "code": null, "e": 1217, "s": 1188, "text": "Conda installation for Dask:" }, { "code": null, "e": 1237, "s": 1217, "text": "!conda install dask" }, { "code": null, "e": 1264, "s": 1237, "text": "pip installation for Dask:" }, { "code": null, "e": 1294, "s": 1264, "text": "!pip install “dask[complete]”" }, { "code": null, "e": 1405, "s": 1294, "text": "Dask helps to parallelize Arrays, DataFrames, and Machine Learning for dealing with a large amount of data as:" }, { "code": null, "e": 1432, "s": 1405, "text": "Arrays: Parallelized Numpy" }, { "code": null, "e": 1574, "s": 1432, "text": "# Arrays implement the Numpy APIimport dask.array as dax = da.random.random(size=(10000, 10000), chunks=(1000, 1000))x + x.T - x.mean(axis=0)" }, { "code": null, "e": 1605, "s": 1574, "text": "DataFrame: Parallelized Pandas" }, { "code": null, "e": 1746, "s": 1605, "text": "# Dataframes implement the Pandas APIimport dask.dataframe as dddf = dd.read_csv('financial_dataset.csv')df.groupby(df.amount).balance.sum()" }, { "code": null, "e": 1790, "s": 1746, "text": "Machine Learning: Parallelized Scikit-Learn" }, { "code": null, "e": 1927, "s": 1790, "text": "# Dask-ML implements the Scikit-Learn APIfrom dask_ml.linear_model import LogisticRegressionlr = LogisticRegression()lr.fit(train, test)" }, { "code": null, "e": 2263, "s": 1927, "text": "Most of the Dask API is very similar to the Pandas API so you can directly use the data frames of the Pandas in Dusk with a very similar command. To generate a discrete data frame you can just simply call the `read_csv()` method in the same way you used to call in Pandas or can easily convert a Pandas DataFrame into a Dask DataFrame." }, { "code": null, "e": 2331, "s": 2263, "text": "import dask.dataframe as ddfdd = ddf.from_pandas(df, npartitions=N)" }, { "code": null, "e": 2461, "s": 2331, "text": "For the following benchmarking the machine used had a standard 4-core processor which stays standard for testing both frameworks." }, { "code": null, "e": 2659, "s": 2461, "text": "I have done a very simple yet interesting benchmark to show how fast is Dask DataFrame as compared to a traditional Pandas DataFrame for reading a dataset from a .csv file having 5 million records." }, { "code": null, "e": 2893, "s": 2659, "text": "Results: To read a 5M data file of size over 600MB Pandas DataFrame took around 6.2 seconds whereas the same task is performed by Dask DataFrame in much much less than a second time due to its impressive parallelization capabilities." }, { "code": null, "e": 3043, "s": 2893, "text": "Note: This test was done on a small dataset, but as soon as the size of data increases, this time difference in reading data gets exponentially high." }, { "code": null, "e": 3118, "s": 3043, "text": "You can use the code below to alter the benchmarking for a bigger dataset." }, { "code": null, "e": 3237, "s": 3118, "text": "In this Benchmark, I generated a 1Trillion sized array of random numbers using both Numpy Array as well as Dask Array." }, { "code": null, "e": 3391, "s": 3237, "text": "Result: As expected the results were pretty obvious as Numpy Array took a bit less than 8 seconds to compute whereas the Dask Array took negligible time!" }, { "code": null, "e": 3447, "s": 3391, "text": "You can try out the same benchmark using the code below" }, { "code": null, "e": 3712, "s": 3447, "text": "Dask helps in doing data analysis faster because it parallelizes the existing frameworks like Pandas, Numpy, Scikit-Learn, and process data parallelly using the full potential of your machine’s CPU. You can try experimenting with the amazing features of Dask here." } ]
How to write the comparator as a lambda expression in Java?
A lambda expression is an anonymous method and doesn't execute on its own in java. Instead, it is used to implement a method defined by the functional interface. A lambda expression used with any functional interface and Comparator is a functional interface. The Comparator interface has used when sorting a collection of objects compared with each other. In the below example, we can sort the employee list by name using the Comparator interface. import java.util.ArrayList; import java.util.Collections; import java.util.List; class Employee { int id; String name; double salary; public Employee(int id, String name, double salary) { super(); this.id = id; this.name = name; this.salary = salary; } } public class LambdaComparatorTest { public static void main(String[] args) { List<Employee> list = new ArrayList<Employee>(); // Adding employees list.add(new Employee(115, "Adithya", 25000.00)); list.add(new Employee(125, "Jai", 30000.00)); list.add(new Employee(135, "Chaitanya", 40000.00)); System.out.println("Sorting the employee list based on the name"); // implementing lambda expression Collections.sort(list, (p1, p2) -> { return p1.name.compareTo(p2.name); }); for(Employee e : list) { System.out.println(e.id + " " + e.name + " " + e.salary); } } } Sorting the employee list based on the name 115 Adithya 25000.0 135 Chaitanya 40000.0 125 Jai 30000.0
[ { "code": null, "e": 1418, "s": 1062, "text": "A lambda expression is an anonymous method and doesn't execute on its own in java. Instead, it is used to implement a method defined by the functional interface. A lambda expression used with any functional interface and Comparator is a functional interface. The Comparator interface has used when sorting a collection of objects compared with each other." }, { "code": null, "e": 1510, "s": 1418, "text": "In the below example, we can sort the employee list by name using the Comparator interface." }, { "code": null, "e": 2459, "s": 1510, "text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\nclass Employee {\n int id;\n String name;\n double salary;\n public Employee(int id, String name, double salary) {\n super();\n this.id = id;\n this.name = name;\n this.salary = salary;\n }\n}\npublic class LambdaComparatorTest {\n public static void main(String[] args) {\n List<Employee> list = new ArrayList<Employee>();\n\n // Adding employees\n list.add(new Employee(115, \"Adithya\", 25000.00));\n list.add(new Employee(125, \"Jai\", 30000.00));\n list.add(new Employee(135, \"Chaitanya\", 40000.00));\n System.out.println(\"Sorting the employee list based on the name\");\n\n // implementing lambda expression\n Collections.sort(list, (p1, p2) -> {\n return p1.name.compareTo(p2.name); \n }); \n for(Employee e : list) {\n System.out.println(e.id + \" \" + e.name + \" \" + e.salary);\n }\n }\n}" }, { "code": null, "e": 2561, "s": 2459, "text": "Sorting the employee list based on the name\n115 Adithya 25000.0\n135 Chaitanya 40000.0\n125 Jai 30000.0" } ]
QlikView - Bar Chart
Bar charts are very widely used charting method to study the relation between two dimensions in form of bars. The height of the bar in the graph represents the value of one dimension. The number of bars represent the sequence of values or grouped values of another dimension. Let us consider the following input data, which represents the sales figure of different product lines and product categories. Product_Line,Product_category,Value Sporting Goods,Outdoor Recreation,5642 Food, Beverages & Tobacco,2514 Apparel & Accessories,Clothing,2365 Apparel & Accessories,Costumes & Accessories,4487 Sporting Goods,Athletics,812 Health & Beauty,Personal Care,6912 Arts & Entertainment,Hobbies & Creative Arts,5201 Arts & Entertainment,Paintings,8451 Arts & Entertainment,Musical Instruments,1245 Hardware,Tool Accessories,456 Home & Garden,Bathroom Accessories,241 Food,Drinks,1247 Home & Garden,Lawn & Garden,5462 Office Supplies,Presentation Supplies,577 Hardware,Blocks,548 Baby & Toddler,Diapering,1247 Baby & Toddler,Toys,257 Home & Garden,Pipes,1241 Office Supplies,Display Board,2177 The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option form the "Data from Files" tab and browse for the file containing the above data. Edit the load script to add the following code. Click "OK" and press "Control+R" to load the data into the QlikView's memory. LOAD Product_Line, Product_category, Value FROM [C:\Qlikview\data\product_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); For the above data, let us create a Table Box, which will show the data in a tabular form. Go to the menu Layout → New Sheet Object → Table Box and choose the column as shown below. Click Apply and then OK to finish creating the Table box. The below given screen appears. To start creating a bar chart, we will use the quick chart wizard. On clicking it, the following screen appears which prompts for selecting the chart type. Choose bar Chart and click Next. Choose Product Line as the First Dimension. The chart expression is used to apply the functions like Sum, Average, or Count on the fields with numeric values. We will apply the Sum function on the filed named Value. Click Next. The Chart format defines the style and orientation of the chart. We choose the first option in each category. Click Next. The Bar chart appears as shown below. It shows the height of the field value for different product lines. 70 Lectures 5 hours Arthur Fong Print Add Notes Bookmark this page
[ { "code": null, "e": 3196, "s": 2920, "text": "Bar charts are very widely used charting method to study the relation between two dimensions in form of bars. The height of the bar in the graph represents the value of one dimension. The number of bars represent the sequence of values or grouped values of another dimension." }, { "code": null, "e": 3323, "s": 3196, "text": "Let us consider the following input data, which represents the sales figure of different product lines and product categories." }, { "code": null, "e": 4007, "s": 3323, "text": "Product_Line,Product_category,Value\nSporting Goods,Outdoor Recreation,5642\nFood, Beverages & Tobacco,2514\nApparel & Accessories,Clothing,2365\nApparel & Accessories,Costumes & Accessories,4487\nSporting Goods,Athletics,812\nHealth & Beauty,Personal Care,6912\nArts & Entertainment,Hobbies & Creative Arts,5201\nArts & Entertainment,Paintings,8451\nArts & Entertainment,Musical Instruments,1245\nHardware,Tool Accessories,456\nHome & Garden,Bathroom Accessories,241\nFood,Drinks,1247\nHome & Garden,Lawn & Garden,5462\nOffice Supplies,Presentation Supplies,577\nHardware,Blocks,548\nBaby & Toddler,Diapering,1247\nBaby & Toddler,Toys,257\nHome & Garden,Pipes,1241\nOffice Supplies,Display Board,2177\n" }, { "code": null, "e": 4385, "s": 4007, "text": "The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the \"Table Files\" option form the \"Data from Files\" tab and browse for the file containing the above data. Edit the load script to add the following code. Click \"OK\" and press \"Control+R\" to load the data into\nthe QlikView's memory." }, { "code": null, "e": 4547, "s": 4385, "text": "LOAD Product_Line, \n Product_category, \n Value\nFROM\n[C:\\Qlikview\\data\\product_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 4729, "s": 4547, "text": "For the above data, let us create a Table Box, which will show the data in a tabular form. Go to the menu Layout → New Sheet Object → Table Box and choose the column as shown below." }, { "code": null, "e": 4819, "s": 4729, "text": "Click Apply and then OK to finish creating the Table box. The below given screen appears." }, { "code": null, "e": 5008, "s": 4819, "text": "To start creating a bar chart, we will use the quick chart wizard. On clicking it, the following\nscreen appears which prompts for selecting the chart type. Choose bar Chart and click\nNext." }, { "code": null, "e": 5052, "s": 5008, "text": "Choose Product Line as the First Dimension." }, { "code": null, "e": 5236, "s": 5052, "text": "The chart expression is used to apply the functions like Sum, Average, or Count on the fields with numeric values. We will apply the Sum function on the filed named Value. Click Next." }, { "code": null, "e": 5358, "s": 5236, "text": "The Chart format defines the style and orientation of the chart. We choose the first option\nin each category. Click Next." }, { "code": null, "e": 5464, "s": 5358, "text": "The Bar chart appears as shown below. It shows the height of the field value for different product lines." }, { "code": null, "e": 5497, "s": 5464, "text": "\n 70 Lectures \n 5 hours \n" }, { "code": null, "e": 5510, "s": 5497, "text": " Arthur Fong" }, { "code": null, "e": 5517, "s": 5510, "text": " Print" }, { "code": null, "e": 5528, "s": 5517, "text": " Add Notes" } ]
Drawing multiple figures in parallel in Python with Matplotlib
To draw multiple figures in parallel in Python with matplolib, we can take the following steps− Create random data using numpy. Add a subplot to the current figure, nrows=1, ncols=4 and at index=1. Display data as an image, i.e., on a 2D regular raster, using imshow() method with cmap="Blues_r". Add a subplot to the current figure, nrows=1, ncols=4 and at index=2. Display data as an image, i.e., on a 2D regular raster, using imshow() method with cmap="Accent_r". Add a subplot to the current figure, nrows=1, ncols=4 and at index=3. Display data as an image, i.e., on a 2D regular raster, using imshow() method with cmap="terrain_r" Add a subplot to the current figure, nrows=1, ncols=4 and at index=4. Display data as an image, i.e., on a 2D regular raster, using imshow() method with cmap="twilight_shifted_r". To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True data = np.random.rand(5, 5) plt.subplot(1, 4, 1) plt.imshow(data, cmap="Blues_r") plt.subplot(1, 4, 2) plt.imshow(data, cmap="Accent_r") plt.subplot(1, 4, 3) plt.imshow(data, cmap="terrain_r") plt.subplot(1, 4, 4) plt.imshow(data, cmap="twilight_shifted_r") plt.show()
[ { "code": null, "e": 1158, "s": 1062, "text": "To draw multiple figures in parallel in Python with matplolib, we can take the following steps−" }, { "code": null, "e": 1190, "s": 1158, "text": "Create random data using numpy." }, { "code": null, "e": 1260, "s": 1190, "text": "Add a subplot to the current figure, nrows=1, ncols=4 and at index=1." }, { "code": null, "e": 1359, "s": 1260, "text": "Display data as an image, i.e., on a 2D regular raster, using imshow() method with cmap=\"Blues_r\"." }, { "code": null, "e": 1429, "s": 1359, "text": "Add a subplot to the current figure, nrows=1, ncols=4 and at index=2." }, { "code": null, "e": 1529, "s": 1429, "text": "Display data as an image, i.e., on a 2D regular raster, using imshow() method with cmap=\"Accent_r\"." }, { "code": null, "e": 1599, "s": 1529, "text": "Add a subplot to the current figure, nrows=1, ncols=4 and at index=3." }, { "code": null, "e": 1699, "s": 1599, "text": "Display data as an image, i.e., on a 2D regular raster, using imshow() method with cmap=\"terrain_r\"" }, { "code": null, "e": 1769, "s": 1699, "text": "Add a subplot to the current figure, nrows=1, ncols=4 and at index=4." }, { "code": null, "e": 1879, "s": 1769, "text": "Display data as an image, i.e., on a 2D regular raster, using imshow() method with cmap=\"twilight_shifted_r\"." }, { "code": null, "e": 1921, "s": 1879, "text": "To display the figure, use show() method." }, { "code": null, "e": 2333, "s": 1921, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndata = np.random.rand(5, 5)\nplt.subplot(1, 4, 1)\nplt.imshow(data, cmap=\"Blues_r\")\nplt.subplot(1, 4, 2)\nplt.imshow(data, cmap=\"Accent_r\")\nplt.subplot(1, 4, 3)\nplt.imshow(data, cmap=\"terrain_r\")\nplt.subplot(1, 4, 4)\nplt.imshow(data, cmap=\"twilight_shifted_r\")\nplt.show()" } ]
Node.js - Request Object
The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. Following is the list of few properties associated with request object. req.app This property holds a reference to the instance of the express application that is using the middleware. req.baseUrl The URL path on which a router instance was mounted. req.body Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser req.cookies When using cookie-parser middleware, this property is an object that contains cookies sent by the request. req.fresh Indicates whether the request is "fresh." It is the opposite of req.stale. req.hostname Contains the hostname from the "Host" HTTP header. req.ip The remote IP address of the request. req.ips When the trust proxy setting is true, this property contains an array of IP addresses specified in the “X-Forwarded-For” request header. req.originalUrl This property is much like req.url; however, it retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes. req.params An object containing properties mapped to the named route “parameters”. For example, if you have the route /user/:name, then the "name" property is available as req.params.name. This object defaults to {}. req.path Contains the path part of the request URL. req.protocol The request protocol string, "http" or "https" when requested with TLS. req.query An object containing a property for each query string parameter in the route. req.route The currently-matched route, a string. req.secure A Boolean that is true if a TLS connection is established. req.signedCookies When using cookie-parser middleware, this property contains signed cookies sent by the request, unsigned and ready for use. req.stale Indicates whether the request is "stale," and is the opposite of req.fresh. req.subdomains An array of subdomains in the domain name of the request. req.xhr A Boolean value that is true if the request’s "X-Requested-With" header field is “XMLHttpRequest”, indicating that the request was issued by a client library such as jQuery. req.accepts(types) This method checks if the specified content types are acceptable, based on the request’s Accept HTTP header field. Following are a few examples − // Accept: text/html req.accepts('html'); // => "html" // Accept: text/*, application/json req.accepts('html'); // => "html" req.accepts('text/html'); // => "text/html" req.get(field) This method returns the specified HTTP request header field. Following are a few examples − req.get('Content-Type'); // => "text/plain" req.get('content-type'); // => "text/plain" req.get('Something'); // => undefined req.is(type) This method returns true if the incoming request’s "Content-Type" HTTP header field matches the MIME type specified by the type parameter. Following are few a examples − // With Content-Type: text/html; charset=utf-8 req.is('html'); req.is('text/html'); req.is('text/*'); // => true req.param(name [, defaultValue]) This method returns the value of param name when present. Following are few examples − // ?name=tobi req.param('name') // => "tobi" // POST name=tobi req.param('name') // => "tobi" // /user/tobi for /user/:name req.param('name') // => "tobi" 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": 2153, "s": 2018, "text": "The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on." }, { "code": null, "e": 2225, "s": 2153, "text": "Following is the list of few properties associated with request object." }, { "code": null, "e": 2233, "s": 2225, "text": "req.app" }, { "code": null, "e": 2338, "s": 2233, "text": "This property holds a reference to the instance of the express application that is using the middleware." }, { "code": null, "e": 2350, "s": 2338, "text": "req.baseUrl" }, { "code": null, "e": 2403, "s": 2350, "text": "The URL path on which a router instance was mounted." }, { "code": null, "e": 2412, "s": 2403, "text": "req.body" }, { "code": null, "e": 2579, "s": 2412, "text": "Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser" }, { "code": null, "e": 2591, "s": 2579, "text": "req.cookies" }, { "code": null, "e": 2698, "s": 2591, "text": "When using cookie-parser middleware, this property is an object that contains cookies sent by the request." }, { "code": null, "e": 2708, "s": 2698, "text": "req.fresh" }, { "code": null, "e": 2783, "s": 2708, "text": "Indicates whether the request is \"fresh.\" It is the opposite of req.stale." }, { "code": null, "e": 2796, "s": 2783, "text": "req.hostname" }, { "code": null, "e": 2847, "s": 2796, "text": "Contains the hostname from the \"Host\" HTTP header." }, { "code": null, "e": 2854, "s": 2847, "text": "req.ip" }, { "code": null, "e": 2892, "s": 2854, "text": "The remote IP address of the request." }, { "code": null, "e": 2900, "s": 2892, "text": "req.ips" }, { "code": null, "e": 3037, "s": 2900, "text": "When the trust proxy setting is true, this property contains an array of IP addresses specified in the “X-Forwarded-For” request header." }, { "code": null, "e": 3053, "s": 3037, "text": "req.originalUrl" }, { "code": null, "e": 3205, "s": 3053, "text": "This property is much like req.url; however, it retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes." }, { "code": null, "e": 3216, "s": 3205, "text": "req.params" }, { "code": null, "e": 3422, "s": 3216, "text": "An object containing properties mapped to the named route “parameters”. For example, if you have the route /user/:name, then the \"name\" property is available as req.params.name. This object defaults to {}." }, { "code": null, "e": 3431, "s": 3422, "text": "req.path" }, { "code": null, "e": 3474, "s": 3431, "text": "Contains the path part of the request URL." }, { "code": null, "e": 3487, "s": 3474, "text": "req.protocol" }, { "code": null, "e": 3559, "s": 3487, "text": "The request protocol string, \"http\" or \"https\" when requested with TLS." }, { "code": null, "e": 3569, "s": 3559, "text": "req.query" }, { "code": null, "e": 3647, "s": 3569, "text": "An object containing a property for each query string parameter in the route." }, { "code": null, "e": 3657, "s": 3647, "text": "req.route" }, { "code": null, "e": 3696, "s": 3657, "text": "The currently-matched route, a string." }, { "code": null, "e": 3707, "s": 3696, "text": "req.secure" }, { "code": null, "e": 3766, "s": 3707, "text": "A Boolean that is true if a TLS connection is established." }, { "code": null, "e": 3784, "s": 3766, "text": "req.signedCookies" }, { "code": null, "e": 3909, "s": 3784, "text": "When using cookie-parser middleware, this property contains signed cookies sent by the request, unsigned and ready for use. " }, { "code": null, "e": 3919, "s": 3909, "text": "req.stale" }, { "code": null, "e": 3995, "s": 3919, "text": "Indicates whether the request is \"stale,\" and is the opposite of req.fresh." }, { "code": null, "e": 4010, "s": 3995, "text": "req.subdomains" }, { "code": null, "e": 4068, "s": 4010, "text": "An array of subdomains in the domain name of the request." }, { "code": null, "e": 4076, "s": 4068, "text": "req.xhr" }, { "code": null, "e": 4250, "s": 4076, "text": "A Boolean value that is true if the request’s \"X-Requested-With\" header field is “XMLHttpRequest”, indicating that the request was issued by a client library such as jQuery." }, { "code": null, "e": 4270, "s": 4250, "text": "req.accepts(types)\n" }, { "code": null, "e": 4416, "s": 4270, "text": "This method checks if the specified content types are acceptable, based on the request’s Accept HTTP header field. Following are a few examples −" }, { "code": null, "e": 4587, "s": 4416, "text": "// Accept: text/html\nreq.accepts('html');\n// => \"html\"\n\n// Accept: text/*, application/json\nreq.accepts('html');\n\n// => \"html\"\nreq.accepts('text/html');\n// => \"text/html\"" }, { "code": null, "e": 4603, "s": 4587, "text": "req.get(field)\n" }, { "code": null, "e": 4695, "s": 4603, "text": "This method returns the specified HTTP request header field. Following are a few examples −" }, { "code": null, "e": 4823, "s": 4695, "text": "req.get('Content-Type');\n// => \"text/plain\"\n\nreq.get('content-type');\n// => \"text/plain\"\n\nreq.get('Something');\n// => undefined" }, { "code": null, "e": 4836, "s": 4823, "text": "req.is(type)" }, { "code": null, "e": 5007, "s": 4836, "text": "This method returns true if the incoming request’s \"Content-Type\" HTTP header field matches the MIME type specified by the type parameter. Following are few a examples −" }, { "code": null, "e": 5120, "s": 5007, "text": "// With Content-Type: text/html; charset=utf-8\nreq.is('html');\nreq.is('text/html');\nreq.is('text/*');\n// => true" }, { "code": null, "e": 5153, "s": 5120, "text": "req.param(name [, defaultValue])" }, { "code": null, "e": 5240, "s": 5153, "text": "This method returns the value of param name when present. Following are few examples −" }, { "code": null, "e": 5398, "s": 5240, "text": "// ?name=tobi\nreq.param('name')\n// => \"tobi\"\n\n// POST name=tobi\nreq.param('name')\n// => \"tobi\"\n\n// /user/tobi for /user/:name \nreq.param('name')\n// => \"tobi\"" }, { "code": null, "e": 5433, "s": 5398, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5461, "s": 5433, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5495, "s": 5461, "text": "\n 88 Lectures \n 17 hours \n" }, { "code": null, "e": 5523, "s": 5495, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5558, "s": 5523, "text": "\n 32 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5573, "s": 5558, "text": " Richard Wells" }, { "code": null, "e": 5604, "s": 5573, "text": "\n 8 Lectures \n 33 mins\n" }, { "code": null, "e": 5618, "s": 5604, "text": " Anant Rungta" }, { "code": null, "e": 5652, "s": 5618, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5672, "s": 5652, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 5705, "s": 5672, "text": "\n 97 Lectures \n 6 hours \n" }, { "code": null, "e": 5725, "s": 5705, "text": " Skillbakerystudios" }, { "code": null, "e": 5732, "s": 5725, "text": " Print" }, { "code": null, "e": 5743, "s": 5732, "text": " Add Notes" } ]
Sum of square of first n odd numbers
The series of squares of first n odd numbers takes squares of of first n odd numbers in series. The series is: 1,9,25,49,81,121... The series can also be written as − 12, 32, 52, 72, 92, 112.... The sum of this series has a mathematical formula − n(2n+1)(2n-1)/ 3= n(4n2 - 1)/3 Lets take an example, Input: N = 4 Output: sum = 12 + 32 + 52 + 72 = 1 +9+ 25 + 49 = 84 Using formula, sum = 4(4(4)2- 1)/3 = 4(64-1)/3 = 4(63)/3 = 4*21 = 84 both these methods are good but the one using mathematical formula is better because it does not use looks which reduces its time complexity. #include <stdio.h> int main() { int n = 8; int sum = 0; for (int i = 1; i <= n; i++) sum += (2*i - 1) * (2*i - 1); printf("The sum of square of first %d odd numbers is %d",n, sum); return 0; } The sum of square of first 8 odd numbers is 680 #include <stdio.h> int main() { int n = 18; int sum = ((n*((4*n*n)-1))/3); printf("The sum of square of first %d odd numbers is %d",n, sum); return 0; } The sum of square of first 18 odd numbers is 7770
[ { "code": null, "e": 1158, "s": 1062, "text": "The series of squares of first n odd numbers takes squares of of first n odd numbers in series." }, { "code": null, "e": 1193, "s": 1158, "text": "The series is: 1,9,25,49,81,121..." }, { "code": null, "e": 1257, "s": 1193, "text": "The series can also be written as − 12, 32, 52, 72, 92, 112...." }, { "code": null, "e": 1309, "s": 1257, "text": "The sum of this series has a mathematical formula −" }, { "code": null, "e": 1340, "s": 1309, "text": "n(2n+1)(2n-1)/ 3= n(4n2 - 1)/3" }, { "code": null, "e": 1362, "s": 1340, "text": "Lets take an example," }, { "code": null, "e": 1389, "s": 1362, "text": "Input: N = 4\nOutput: sum =" }, { "code": null, "e": 1428, "s": 1389, "text": "12 + 32 + 52 + 72 = 1 +9+ 25 + 49 = 84" }, { "code": null, "e": 1639, "s": 1428, "text": "Using formula, sum = 4(4(4)2- 1)/3 = 4(64-1)/3 = 4(63)/3 = 4*21 = 84 both these methods are good but the one using mathematical formula is better because it does not use looks which reduces its time complexity." }, { "code": null, "e": 1853, "s": 1639, "text": "#include <stdio.h>\nint main() {\n int n = 8;\n int sum = 0;\n for (int i = 1; i <= n; i++)\n sum += (2*i - 1) * (2*i - 1);\n printf(\"The sum of square of first %d odd numbers is %d\",n, sum);\n return 0;\n}" }, { "code": null, "e": 1901, "s": 1853, "text": "The sum of square of first 8 odd numbers is 680" }, { "code": null, "e": 2066, "s": 1901, "text": "#include <stdio.h>\nint main() {\n int n = 18;\n int sum = ((n*((4*n*n)-1))/3);\n printf(\"The sum of square of first %d odd numbers is %d\",n, sum);\n return 0;\n}" }, { "code": null, "e": 2116, "s": 2066, "text": "The sum of square of first 18 odd numbers is 7770" } ]
Deep CARs— Transfer Learning With Pytorch | by Ngong Ivoline-Clarisse Kieleh | Towards Data Science
A step by step guide to completing Hackathon Auto-matic How can you teach a computer to recognize different car brands? Would you like to take a picture of any car and your phone automatically tells you what the make of the car is? If this excites you then you are in the right place. We are going to write a model that can recognize 196 different types of cars. Side Note Hackathon Automatic is the second project of an initiative to organize weekend hackathons started by 4 ladies and myself(from different parts of the world) As part of the 5000 students selected for Secure and Private AI Scholarship Challenge on Udacity sponsored by facebook, we decided to organize weekend hackathons; 48hours of solving a problem with Pytorch, having fun and competing against each other. To our surprise, in our first hackathon, 41 teams participated 🙌 . Hackathon Blossom was the name given to the first hackathon. Hackathon Auto-matic which like Hackathon Blossom is also based on image classification. I can go on and on about how incredible this opportunity has been and the amazing community we have there. I better stop here and go back to our goal for today :) We would be using a neural network to accomplish our goal. To be more precise we will be using a very deep neural network hence the name deep cars. This tutorial is divided into 2 parts: Part 1: Building a car classifier Part 2: Deploying a classifier(In progress...) In this article, we would be going through Part 1 Prerequisite: In order to follow up, some knowledge in the following is required: Python — Udacity provides a great course on Introduction to Python Convolutional Neural Networks — Adit provides a great explanation on CNNs Basics of Pytorch We will be using a method called Transfer Learning to train our classifier. Transfer Learning is a method in deep learning where a model that is developed to solve one task is reused as a starting point for another task. Say for example you want to build a network to identify birds, Rather than writing a model from scratch which can be a very complex task, to say the least, you can use an already existing model that was developed to do the same or similar task (in our case of recognizing birds we could use a network that recognizes other animals). The advantage of using transfer learning; the learning process is faster, more accurate and requires less training data. The already existing model is called a Pre-trained model. Most pre-trained models used in transfer learning are based on large convolutional neural nets. Some people pre-trained models are VGGNet, ResNet, DenseNet, Google’s Inception, etc. Most of these networks are trained on ImageNet. ImageNet is a massive dataset with over 1 million labeled images in 1000 categories. In Pytorch it is easy to load pre-trained networks based on ImageNet which are available from torchvision. We will use some of these pre-trained models to train our network. Our model will be built on Google Colab using the following steps (Notebook can be found here): Load data and Perform TransformationsBuild the ModelTrain the ModelTest the Model on Unseen Data Load data and Perform Transformations Build the Model Train the Model Test the Model on Unseen Data Import Libraries Here we just load the libraries and make sure GPU is turned on. Since we will be using pre-trained models which are very deep networks, training on CPU is not really an option as it will take a really long time. The GPU performs linear algebra computations in parallel, hence the training speed increases 100x. If your GPU is off and you are using Colab, on your notebook go to Edit => Notebook Settings. Make sure the Runtime is set to Python 3 and under Hardware Accelerator choose GPU. You will notice that we are checking if cuda is available. Most deep learning frameworks use CUDA to compute the forward and backward passes on the GPU. 1.1 Downloading The Dataset Now that our libraries are imported we load our dataset from Kaggle. This dataset contains 196 car brands. Here, we download the dataset and load them using Pytorch DataLoaders. We download the data directly into the google drive, hence we have to get authorized access. #Mounting google drive inorder to access datafrom google.colab import drivedrive.mount('/content/drive') After running this: Click on the link that appears, log in to your account, click on allow, then copy and paste the generated text into your notebook. Check out this article which shows you how to get the API key and download the dataset easily. We add this line !unzip \*.zip to unzip the downloaded files. Your code should be something like this: Notice we have 2 directories; the train and test directories. We will use our model to predict the values of a test set later. We have to split the train data into train and validation data. Before splitting, let us understand what transformations are and write our transformations. 1.2 Data Transformations Now that the dataset is downloaded we perform transformations on the data. Transformation is converting the data from one form to another. We are going to apply 2 main transformations to our images: Data Augmentation This is a strategy to increase the diversity and size of a dataset for training without actually collecting new data. Techniques like resizing, cropping, horizontal flipping, padding and even GANs etc are applied to images on the dataset and “new” images are created. It has 2 main advantages; generates more data from limited data and prevents overfitting. However, do not expect to see these generated images in the dataset. They are only created during batch generation, so the actual images during training will increase even though you do not see the number of images in the dataset increasing. In our model, we apply 3 augmentation strategies; resizing (RandomResize), cropping(RandomCrop) and flipping horizontally (HorizontalFlip). Note that for the test data, we do not do the RandomResizedCrop, RandomRotation and RandomHorizontalFlip transformations. Instead, we just resize the test images to 256×256 and crop out the center 224×224 in order to be able to use them with the pre-trained model. Data Normalization After performing augmentation the image is transformed into a tensor and normalized by using the mean and standard deviation of all images in ImageNet. Usually, for very large datasets the mean and standard deviation of the dataset itself is used. Given that our dataset is not too large we use those of ImageNet which are: [0.485, 0.456, 0.406], [0.229, 0.224, 0.225] After performing these transformations we load our data using ImageFolder from Pytorch. But first we need validation data, so we split the training set. Only 1% of our data is chosen for validation and the rest for training. Visualizing Labels We visualize our labels to see the structure of the file. We see that one car name appears above 0. Hence we have to add a header name while reading our csv file and we get the right output. It is very important to note that our labels start from 0 to 195 (very important) 3 Visualize Images We can now load and visualize our data. A method imshow() (from the challenge course)is created to display our images. The images in the training set look like this. We notice that some of them have been flipped or rotated. As earlier mentioned we are going to be using pre-trained models based on ImageNet. The steps we are going to use for building and training are: Load the pre-trained modelFreeze parameters in convolutional layersCreate a custom classifier and define hyperparametersTrain the custom classifier Load the pre-trained model Freeze parameters in convolutional layers Create a custom classifier and define hyperparameters Train the custom classifier 2.2 Loading the Pre-trained Model We are going to try out different architectures; densenet161, inceptionv3, resnet121 and vggnet architecture. Here, we load the different models and specify the number of input features in the fully connected layer of the models because we will need this when building the custom classifier. 2.3 Freeze Parameters and Create Custom Classifier Since most of the parameters in our pre-trained model are already trained for us, we don’t backprop through them. This will allow us to keep the pre-trained weights for early convolutional layers (whose purpose here is for feature extraction). We do this by resetting the requires_grad field to false. After doing that we replace the fully connected network which will have the same inputs as our pretrained neuron, a custom hidden layer and our output. Our build_classifer method is flexible, it works when we want no hidden layers in our network and when we want more than one hidden layer. The activation function (in this case relu)and dropouts are also defined. Now we specify our hyperparameters and hidden layers. We specify the criterion, different optimizers like Adam, Adadelta, SGD which contain the learning rate and momentum. We play with these hyperparameters for the different pre-trained networks and choose the ones that give us the best results. We use 2 types of different schedulers for resnet and vggnet. This what they do: torch.optim.lr_scheduler provides several methods to adjust the learning rate based on the number of epochs. torch.optim.lr_scheduler.ReduceLROnPlateau allows dynamic learning rate reducing based on some validation measurements. Read more here 2.4 Train And Validation In order to train our model with PyTorch we generally perform the following steps while iterating through each epoch: Make a forward pass through the network using forward(images) Use the network output in the criterion function to calculate the loss Perform a backward pass through the network with loss.backward() to calculate the gradients Take a step with the optimizer to update the weights optimizer.step() optimizer.zero_grad() is used to clear accumulated gradients A technique called early stopping is used to prevent overfitting. It causes the training to stop when the performance on the validation dataset begins to fall. We also save the model(checkpoints) when we get the best accuracy as training goes on. This way checkpoints can be restored and training continued later if power is lost or training is disrupted due to some reason. The model is adapted from the PyTorch Website Now we train our model. Epoch 1/60 ---------- train Loss: 0.5672 Acc: 0.8441 valid Loss: 0.6750 Acc: 0.8329 Epoch 2/60 ---------- train Loss: 0.6184 Acc: 0.8357 valid Loss: 0.5980 Acc: 0.8415 Epoch 3/60 ---------- train Loss: 0.5695 Acc: 0.8487 valid Loss: 0.5503 Acc: 0.8575 ... This looks promising. The model appears to be learning with each epoch. Additionally, it does not appear that our model is overfitting (at least too much) since the training and validation metrics are not diverging too much. This model particular epoch results were gotten with the ResNet architecture and this was the second training. The accuracies started really low but improved with time. The hyperparameters that affected the accuracies we got a lot were the optimizer, the scheduler, the number of epochs and the architecture. Tweaking these values either gave very low accuracies (as low as 0 or even negative) or started with an accuracy like 0.013 which increased as the number of epochs increased (patience is key here). 4. Test the Model on Unseen Data Once we feel comfortable with our validation accuracy we load our saved model and do predictions on the test data. The in-class competition required that we submit results in a csv file in the format Id, Predicted. Id here is the name of our image files without the extension .jpg and Predicted is the class of our model predicted for each image (should be between 1 and 196). Remember our labels start from 0 to 195, so we have to add 1 to our predicted classes to get the right values. We load our saved model model.load_state_dict(torch.load('/content/drive/MyDrive/ResnetCars.pt'))model.to(device) Now we load the test dataset and pass our model through the dataset. Since we are only doing predictions we do not need to compute gradients. We do this by torch.no_grad() and set to evaluation model.eval() . We calculate the predictions. After getting our results we print the data frame and write our results into a .csv file which we would submit on the competition website. Check out the amazing kernel of Khush Patel’s who emerged as the winner of the hackathon with a 99.18% accuracy. He used inceptionV3 architecture, with CrossEntropyLoss and an SGD optimizer. Can your model beat this? :) You can join the inclass competition on Kaggle . And we are done. Congratulations 👏, It was a long post but you made it until the end. Now you can build your own models with transfer learning. The code is reusable and you can use it for other datasets as well. Thanks for reading! Feel free to reach out any time on Twitter and LinkedIn. References [1] F. Zaidi, Transfer Learning in PyTorch, Part 1: How to Use DataLoaders and Build a Fully Connected Class (2019) [2] G. Adjei, Transfer Learning with PyTorch, (2019), HeartBeat
[ { "code": null, "e": 228, "s": 172, "text": "A step by step guide to completing Hackathon Auto-matic" }, { "code": null, "e": 404, "s": 228, "text": "How can you teach a computer to recognize different car brands? Would you like to take a picture of any car and your phone automatically tells you what the make of the car is?" }, { "code": null, "e": 535, "s": 404, "text": "If this excites you then you are in the right place. We are going to write a model that can recognize 196 different types of cars." }, { "code": null, "e": 545, "s": 535, "text": "Side Note" }, { "code": null, "e": 701, "s": 545, "text": "Hackathon Automatic is the second project of an initiative to organize weekend hackathons started by 4 ladies and myself(from different parts of the world)" }, { "code": null, "e": 1169, "s": 701, "text": "As part of the 5000 students selected for Secure and Private AI Scholarship Challenge on Udacity sponsored by facebook, we decided to organize weekend hackathons; 48hours of solving a problem with Pytorch, having fun and competing against each other. To our surprise, in our first hackathon, 41 teams participated 🙌 . Hackathon Blossom was the name given to the first hackathon. Hackathon Auto-matic which like Hackathon Blossom is also based on image classification." }, { "code": null, "e": 1332, "s": 1169, "text": "I can go on and on about how incredible this opportunity has been and the amazing community we have there. I better stop here and go back to our goal for today :)" }, { "code": null, "e": 1480, "s": 1332, "text": "We would be using a neural network to accomplish our goal. To be more precise we will be using a very deep neural network hence the name deep cars." }, { "code": null, "e": 1519, "s": 1480, "text": "This tutorial is divided into 2 parts:" }, { "code": null, "e": 1553, "s": 1519, "text": "Part 1: Building a car classifier" }, { "code": null, "e": 1600, "s": 1553, "text": "Part 2: Deploying a classifier(In progress...)" }, { "code": null, "e": 1650, "s": 1600, "text": "In this article, we would be going through Part 1" }, { "code": null, "e": 1664, "s": 1650, "text": "Prerequisite:" }, { "code": null, "e": 1732, "s": 1664, "text": "In order to follow up, some knowledge in the following is required:" }, { "code": null, "e": 1799, "s": 1732, "text": "Python — Udacity provides a great course on Introduction to Python" }, { "code": null, "e": 1873, "s": 1799, "text": "Convolutional Neural Networks — Adit provides a great explanation on CNNs" }, { "code": null, "e": 1891, "s": 1873, "text": "Basics of Pytorch" }, { "code": null, "e": 1967, "s": 1891, "text": "We will be using a method called Transfer Learning to train our classifier." }, { "code": null, "e": 2624, "s": 1967, "text": "Transfer Learning is a method in deep learning where a model that is developed to solve one task is reused as a starting point for another task. Say for example you want to build a network to identify birds, Rather than writing a model from scratch which can be a very complex task, to say the least, you can use an already existing model that was developed to do the same or similar task (in our case of recognizing birds we could use a network that recognizes other animals). The advantage of using transfer learning; the learning process is faster, more accurate and requires less training data. The already existing model is called a Pre-trained model." }, { "code": null, "e": 2939, "s": 2624, "text": "Most pre-trained models used in transfer learning are based on large convolutional neural nets. Some people pre-trained models are VGGNet, ResNet, DenseNet, Google’s Inception, etc. Most of these networks are trained on ImageNet. ImageNet is a massive dataset with over 1 million labeled images in 1000 categories." }, { "code": null, "e": 3113, "s": 2939, "text": "In Pytorch it is easy to load pre-trained networks based on ImageNet which are available from torchvision. We will use some of these pre-trained models to train our network." }, { "code": null, "e": 3209, "s": 3113, "text": "Our model will be built on Google Colab using the following steps (Notebook can be found here):" }, { "code": null, "e": 3306, "s": 3209, "text": "Load data and Perform TransformationsBuild the ModelTrain the ModelTest the Model on Unseen Data" }, { "code": null, "e": 3344, "s": 3306, "text": "Load data and Perform Transformations" }, { "code": null, "e": 3360, "s": 3344, "text": "Build the Model" }, { "code": null, "e": 3376, "s": 3360, "text": "Train the Model" }, { "code": null, "e": 3406, "s": 3376, "text": "Test the Model on Unseen Data" }, { "code": null, "e": 3423, "s": 3406, "text": "Import Libraries" }, { "code": null, "e": 3734, "s": 3423, "text": "Here we just load the libraries and make sure GPU is turned on. Since we will be using pre-trained models which are very deep networks, training on CPU is not really an option as it will take a really long time. The GPU performs linear algebra computations in parallel, hence the training speed increases 100x." }, { "code": null, "e": 3912, "s": 3734, "text": "If your GPU is off and you are using Colab, on your notebook go to Edit => Notebook Settings. Make sure the Runtime is set to Python 3 and under Hardware Accelerator choose GPU." }, { "code": null, "e": 4065, "s": 3912, "text": "You will notice that we are checking if cuda is available. Most deep learning frameworks use CUDA to compute the forward and backward passes on the GPU." }, { "code": null, "e": 4093, "s": 4065, "text": "1.1 Downloading The Dataset" }, { "code": null, "e": 4200, "s": 4093, "text": "Now that our libraries are imported we load our dataset from Kaggle. This dataset contains 196 car brands." }, { "code": null, "e": 4364, "s": 4200, "text": "Here, we download the dataset and load them using Pytorch DataLoaders. We download the data directly into the google drive, hence we have to get authorized access." }, { "code": null, "e": 4469, "s": 4364, "text": "#Mounting google drive inorder to access datafrom google.colab import drivedrive.mount('/content/drive')" }, { "code": null, "e": 4818, "s": 4469, "text": "After running this: Click on the link that appears, log in to your account, click on allow, then copy and paste the generated text into your notebook. Check out this article which shows you how to get the API key and download the dataset easily. We add this line !unzip \\*.zip to unzip the downloaded files. Your code should be something like this:" }, { "code": null, "e": 5101, "s": 4818, "text": "Notice we have 2 directories; the train and test directories. We will use our model to predict the values of a test set later. We have to split the train data into train and validation data. Before splitting, let us understand what transformations are and write our transformations." }, { "code": null, "e": 5126, "s": 5101, "text": "1.2 Data Transformations" }, { "code": null, "e": 5325, "s": 5126, "text": "Now that the dataset is downloaded we perform transformations on the data. Transformation is converting the data from one form to another. We are going to apply 2 main transformations to our images:" }, { "code": null, "e": 5343, "s": 5325, "text": "Data Augmentation" }, { "code": null, "e": 5701, "s": 5343, "text": "This is a strategy to increase the diversity and size of a dataset for training without actually collecting new data. Techniques like resizing, cropping, horizontal flipping, padding and even GANs etc are applied to images on the dataset and “new” images are created. It has 2 main advantages; generates more data from limited data and prevents overfitting." }, { "code": null, "e": 5943, "s": 5701, "text": "However, do not expect to see these generated images in the dataset. They are only created during batch generation, so the actual images during training will increase even though you do not see the number of images in the dataset increasing." }, { "code": null, "e": 6083, "s": 5943, "text": "In our model, we apply 3 augmentation strategies; resizing (RandomResize), cropping(RandomCrop) and flipping horizontally (HorizontalFlip)." }, { "code": null, "e": 6348, "s": 6083, "text": "Note that for the test data, we do not do the RandomResizedCrop, RandomRotation and RandomHorizontalFlip transformations. Instead, we just resize the test images to 256×256 and crop out the center 224×224 in order to be able to use them with the pre-trained model." }, { "code": null, "e": 6367, "s": 6348, "text": "Data Normalization" }, { "code": null, "e": 6736, "s": 6367, "text": "After performing augmentation the image is transformed into a tensor and normalized by using the mean and standard deviation of all images in ImageNet. Usually, for very large datasets the mean and standard deviation of the dataset itself is used. Given that our dataset is not too large we use those of ImageNet which are: [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]" }, { "code": null, "e": 6961, "s": 6736, "text": "After performing these transformations we load our data using ImageFolder from Pytorch. But first we need validation data, so we split the training set. Only 1% of our data is chosen for validation and the rest for training." }, { "code": null, "e": 6980, "s": 6961, "text": "Visualizing Labels" }, { "code": null, "e": 7038, "s": 6980, "text": "We visualize our labels to see the structure of the file." }, { "code": null, "e": 7253, "s": 7038, "text": "We see that one car name appears above 0. Hence we have to add a header name while reading our csv file and we get the right output. It is very important to note that our labels start from 0 to 195 (very important)" }, { "code": null, "e": 7272, "s": 7253, "text": "3 Visualize Images" }, { "code": null, "e": 7391, "s": 7272, "text": "We can now load and visualize our data. A method imshow() (from the challenge course)is created to display our images." }, { "code": null, "e": 7496, "s": 7391, "text": "The images in the training set look like this. We notice that some of them have been flipped or rotated." }, { "code": null, "e": 7580, "s": 7496, "text": "As earlier mentioned we are going to be using pre-trained models based on ImageNet." }, { "code": null, "e": 7641, "s": 7580, "text": "The steps we are going to use for building and training are:" }, { "code": null, "e": 7789, "s": 7641, "text": "Load the pre-trained modelFreeze parameters in convolutional layersCreate a custom classifier and define hyperparametersTrain the custom classifier" }, { "code": null, "e": 7816, "s": 7789, "text": "Load the pre-trained model" }, { "code": null, "e": 7858, "s": 7816, "text": "Freeze parameters in convolutional layers" }, { "code": null, "e": 7912, "s": 7858, "text": "Create a custom classifier and define hyperparameters" }, { "code": null, "e": 7940, "s": 7912, "text": "Train the custom classifier" }, { "code": null, "e": 7974, "s": 7940, "text": "2.2 Loading the Pre-trained Model" }, { "code": null, "e": 8266, "s": 7974, "text": "We are going to try out different architectures; densenet161, inceptionv3, resnet121 and vggnet architecture. Here, we load the different models and specify the number of input features in the fully connected layer of the models because we will need this when building the custom classifier." }, { "code": null, "e": 8317, "s": 8266, "text": "2.3 Freeze Parameters and Create Custom Classifier" }, { "code": null, "e": 8619, "s": 8317, "text": "Since most of the parameters in our pre-trained model are already trained for us, we don’t backprop through them. This will allow us to keep the pre-trained weights for early convolutional layers (whose purpose here is for feature extraction). We do this by resetting the requires_grad field to false." }, { "code": null, "e": 8984, "s": 8619, "text": "After doing that we replace the fully connected network which will have the same inputs as our pretrained neuron, a custom hidden layer and our output. Our build_classifer method is flexible, it works when we want no hidden layers in our network and when we want more than one hidden layer. The activation function (in this case relu)and dropouts are also defined." }, { "code": null, "e": 9038, "s": 8984, "text": "Now we specify our hyperparameters and hidden layers." }, { "code": null, "e": 9362, "s": 9038, "text": "We specify the criterion, different optimizers like Adam, Adadelta, SGD which contain the learning rate and momentum. We play with these hyperparameters for the different pre-trained networks and choose the ones that give us the best results. We use 2 types of different schedulers for resnet and vggnet. This what they do:" }, { "code": null, "e": 9606, "s": 9362, "text": "torch.optim.lr_scheduler provides several methods to adjust the learning rate based on the number of epochs. torch.optim.lr_scheduler.ReduceLROnPlateau allows dynamic learning rate reducing based on some validation measurements. Read more here" }, { "code": null, "e": 9631, "s": 9606, "text": "2.4 Train And Validation" }, { "code": null, "e": 9749, "s": 9631, "text": "In order to train our model with PyTorch we generally perform the following steps while iterating through each epoch:" }, { "code": null, "e": 9811, "s": 9749, "text": "Make a forward pass through the network using forward(images)" }, { "code": null, "e": 9882, "s": 9811, "text": "Use the network output in the criterion function to calculate the loss" }, { "code": null, "e": 9974, "s": 9882, "text": "Perform a backward pass through the network with loss.backward() to calculate the gradients" }, { "code": null, "e": 10044, "s": 9974, "text": "Take a step with the optimizer to update the weights optimizer.step()" }, { "code": null, "e": 10105, "s": 10044, "text": "optimizer.zero_grad() is used to clear accumulated gradients" }, { "code": null, "e": 10480, "s": 10105, "text": "A technique called early stopping is used to prevent overfitting. It causes the training to stop when the performance on the validation dataset begins to fall. We also save the model(checkpoints) when we get the best accuracy as training goes on. This way checkpoints can be restored and training continued later if power is lost or training is disrupted due to some reason." }, { "code": null, "e": 10526, "s": 10480, "text": "The model is adapted from the PyTorch Website" }, { "code": null, "e": 10550, "s": 10526, "text": "Now we train our model." }, { "code": null, "e": 10809, "s": 10550, "text": "Epoch 1/60 ---------- train Loss: 0.5672 Acc: 0.8441 valid Loss: 0.6750 Acc: 0.8329 Epoch 2/60 ---------- train Loss: 0.6184 Acc: 0.8357 valid Loss: 0.5980 Acc: 0.8415 Epoch 3/60 ---------- train Loss: 0.5695 Acc: 0.8487 valid Loss: 0.5503 Acc: 0.8575 ..." }, { "code": null, "e": 11541, "s": 10809, "text": "This looks promising. The model appears to be learning with each epoch. Additionally, it does not appear that our model is overfitting (at least too much) since the training and validation metrics are not diverging too much. This model particular epoch results were gotten with the ResNet architecture and this was the second training. The accuracies started really low but improved with time. The hyperparameters that affected the accuracies we got a lot were the optimizer, the scheduler, the number of epochs and the architecture. Tweaking these values either gave very low accuracies (as low as 0 or even negative) or started with an accuracy like 0.013 which increased as the number of epochs increased (patience is key here)." }, { "code": null, "e": 11574, "s": 11541, "text": "4. Test the Model on Unseen Data" }, { "code": null, "e": 12062, "s": 11574, "text": "Once we feel comfortable with our validation accuracy we load our saved model and do predictions on the test data. The in-class competition required that we submit results in a csv file in the format Id, Predicted. Id here is the name of our image files without the extension .jpg and Predicted is the class of our model predicted for each image (should be between 1 and 196). Remember our labels start from 0 to 195, so we have to add 1 to our predicted classes to get the right values." }, { "code": null, "e": 12086, "s": 12062, "text": "We load our saved model" }, { "code": null, "e": 12176, "s": 12086, "text": "model.load_state_dict(torch.load('/content/drive/MyDrive/ResnetCars.pt'))model.to(device)" }, { "code": null, "e": 12415, "s": 12176, "text": "Now we load the test dataset and pass our model through the dataset. Since we are only doing predictions we do not need to compute gradients. We do this by torch.no_grad() and set to evaluation model.eval() . We calculate the predictions." }, { "code": null, "e": 12554, "s": 12415, "text": "After getting our results we print the data frame and write our results into a .csv file which we would submit on the competition website." }, { "code": null, "e": 12774, "s": 12554, "text": "Check out the amazing kernel of Khush Patel’s who emerged as the winner of the hackathon with a 99.18% accuracy. He used inceptionV3 architecture, with CrossEntropyLoss and an SGD optimizer. Can your model beat this? :)" }, { "code": null, "e": 12823, "s": 12774, "text": "You can join the inclass competition on Kaggle ." }, { "code": null, "e": 12840, "s": 12823, "text": "And we are done." }, { "code": null, "e": 13035, "s": 12840, "text": "Congratulations 👏, It was a long post but you made it until the end. Now you can build your own models with transfer learning. The code is reusable and you can use it for other datasets as well." }, { "code": null, "e": 13112, "s": 13035, "text": "Thanks for reading! Feel free to reach out any time on Twitter and LinkedIn." }, { "code": null, "e": 13123, "s": 13112, "text": "References" }, { "code": null, "e": 13239, "s": 13123, "text": "[1] F. Zaidi, Transfer Learning in PyTorch, Part 1: How to Use DataLoaders and Build a Fully Connected Class (2019)" } ]
Gradle - Plugins
Plugin is nothing but set of all useful tasks, such as compiling tasks, setting domain objects, setting up source files, etc. are handled by plugins. Applying a plugin to a project means that it allows the plugin to extend the project’s capabilities. The plugins can do the things such as − Extend the basic Gradle model (e.g. add new DSL elements that can be configured). Extend the basic Gradle model (e.g. add new DSL elements that can be configured). Configure the project, according to conversions (e.g. add new tasks or configure sensible defaults). Configure the project, according to conversions (e.g. add new tasks or configure sensible defaults). Apply specific configuration (e.g. add organisational repositories or enforce standards). Apply specific configuration (e.g. add organisational repositories or enforce standards). There are two types of plugins in Gradle, which are as follows − Script plugins − Script plugins is an additional build script that gives a declarative approach to manipulating the build. This is typically used within a build. Script plugins − Script plugins is an additional build script that gives a declarative approach to manipulating the build. This is typically used within a build. Binary plugins − Binary plugins are the classes, that implements the plugin interface and adopt a programmatic approach to manipulating the build. Binary plugins can reside with a build script, with the project hierarchy or externally in a plugin JAR. Binary plugins − Binary plugins are the classes, that implements the plugin interface and adopt a programmatic approach to manipulating the build. Binary plugins can reside with a build script, with the project hierarchy or externally in a plugin JAR. Project.apply() API method is used to apply the particular plugin. You can use the same plugin for multiple times.There are two types of plugins one is script plugin and second is binary plugin. Script plugins can be applied from a script on the local filesystem or at a remote location. Filesystem locations are relative to the project directory, while remote script locations specify HTTP URL. Take a look at the following code snippet. It is used to apply the other.gradle plugin to the build script. Use this code in build.gradle file. apply from: 'other.gradle' Each plugin is identified by plugin id. Some core plugins use short names to apply the plugin id and some community plugins use fully qualified name for plugin id. Sometimes, it allows to specify the class of plugin. Take a look at the following code snippet. It shows how to apply java plugin by using its type. Use the below code in build.gradle file. apply plugin: JavaPlugin Take a look into the following code for applying core plugin using short name. Use this code in build.gradle file. plugins { id 'java' } Take a look into the following code for applying community plugin using short name. Use this code in build.gradle file. plugins { id "com.jfrog.bintray" version "0.4.1" } While creating a custom plugin, you need to write an implementation of plugin. Gradle instantiates the plugin and calls the plugin instance using Plugin.apply() method. The following example contains a greeting plugin, which adds a hello task to the project. Take a look into the following code and use this code in build.gradlebuild.gradle file. apply plugin: GreetingPlugin class GreetingPlugin implements Plugin<Project> { void apply(Project project) { project.task('hello') << { println "Hello from the GreetingPlugin" } } } Use the following code to execute the above script. C:\> gradle -q hello Output This produces the following output − Hello from the GreetingPlugin Most of the plugins need the configuration support from the build script. The Gradle project has an associated ExtensionContainer object that helps to track all the setting and properties being passed to plugins. Let's add a simple extension object to the project. Here, we add a greeting extension object to the project, which allows you to configure the greeting. Use this code in build.gradlefile. apply plugin: GreetingPlugin greeting.message = 'Hi from Gradle' class GreetingPlugin implements Plugin<Project> { void apply(Project project) { // Add the 'greeting' extension object project.extensions.create("greeting", GreetingPluginExtension) // Add a task that uses the configuration project.task('hello') << { println project.greeting.message } } } class GreetingPluginExtension { def String message = 'Hello from GreetingPlugin' } Use the following code to execute the above script − C:\> gradle -q hello Output When you run the code, you will see the following output − Hi from Gradle In this example, GreetingPlugin is a simple, old Groovy object with a field called message. The extension object is added to the plugin list with the name greeting. This object, then becomes available as a project property with the same name as the extension object. Gradle adds a configuration closure for each extension object, so you can group the settings together. Take a look at the following code. Use this code in build.gradle file. apply plugin: GreetingPlugin greeting { message = 'Hi' greeter = 'Gradle' } class GreetingPlugin implements Plugin<Project> { void apply(Project project) { project.extensions.create("greeting", GreetingPluginExtension) project.task('hello') << { println "${project.greeting.message} from ${project.greeting.greeter}" } } } class GreetingPluginExtension { String message String greeter } Use the following code to execute the above script. C:\> gradle -q hello Output The output is mentioned below − Hello from Gradle There are different plugins which are included in the Gradle distribution. These plugins add support for various languages which can be compiled and executed in the JVM. These plugins add support for various languages. Print Add Notes Bookmark this page
[ { "code": null, "e": 2133, "s": 1882, "text": "Plugin is nothing but set of all useful tasks, such as compiling tasks, setting domain objects, setting up source files, etc. are handled by plugins. Applying a plugin to a project means that it allows the plugin to extend the project’s capabilities." }, { "code": null, "e": 2173, "s": 2133, "text": "The plugins can do the things such as −" }, { "code": null, "e": 2255, "s": 2173, "text": "Extend the basic Gradle model (e.g. add new DSL elements that can be configured)." }, { "code": null, "e": 2337, "s": 2255, "text": "Extend the basic Gradle model (e.g. add new DSL elements that can be configured)." }, { "code": null, "e": 2438, "s": 2337, "text": "Configure the project, according to conversions (e.g. add new tasks or configure sensible defaults)." }, { "code": null, "e": 2539, "s": 2438, "text": "Configure the project, according to conversions (e.g. add new tasks or configure sensible defaults)." }, { "code": null, "e": 2629, "s": 2539, "text": "Apply specific configuration (e.g. add organisational repositories or enforce standards)." }, { "code": null, "e": 2719, "s": 2629, "text": "Apply specific configuration (e.g. add organisational repositories or enforce standards)." }, { "code": null, "e": 2784, "s": 2719, "text": "There are two types of plugins in Gradle, which are as follows −" }, { "code": null, "e": 2946, "s": 2784, "text": "Script plugins − Script plugins is an additional build script that gives a declarative approach to manipulating the build. This is typically used within a build." }, { "code": null, "e": 3108, "s": 2946, "text": "Script plugins − Script plugins is an additional build script that gives a declarative approach to manipulating the build. This is typically used within a build." }, { "code": null, "e": 3360, "s": 3108, "text": "Binary plugins − Binary plugins are the classes, that implements the plugin interface and adopt a programmatic approach to manipulating the build. Binary plugins can reside with a build script, with the project hierarchy or externally in a plugin JAR." }, { "code": null, "e": 3612, "s": 3360, "text": "Binary plugins − Binary plugins are the classes, that implements the plugin interface and adopt a programmatic approach to manipulating the build. Binary plugins can reside with a build script, with the project hierarchy or externally in a plugin JAR." }, { "code": null, "e": 3807, "s": 3612, "text": "Project.apply() API method is used to apply the particular plugin. You can use the same plugin for multiple times.There are two types of plugins one is script plugin and second is binary plugin." }, { "code": null, "e": 4008, "s": 3807, "text": "Script plugins can be applied from a script on the local filesystem or at a remote location. Filesystem locations are relative to the project directory, while remote script locations specify HTTP URL." }, { "code": null, "e": 4152, "s": 4008, "text": "Take a look at the following code snippet. It is used to apply the other.gradle plugin to the build script. Use this code in build.gradle file." }, { "code": null, "e": 4180, "s": 4152, "text": "apply from: 'other.gradle'\n" }, { "code": null, "e": 4397, "s": 4180, "text": "Each plugin is identified by plugin id. Some core plugins use short names to apply the plugin id and some community plugins use fully qualified name for plugin id. Sometimes, it allows to specify the class of plugin." }, { "code": null, "e": 4534, "s": 4397, "text": "Take a look at the following code snippet. It shows how to apply java plugin by using its type. Use the below code in build.gradle file." }, { "code": null, "e": 4560, "s": 4534, "text": "apply plugin: JavaPlugin\n" }, { "code": null, "e": 4675, "s": 4560, "text": "Take a look into the following code for applying core plugin using short name. Use this code in build.gradle file." }, { "code": null, "e": 4701, "s": 4675, "text": "plugins {\n id 'java'\n}\n" }, { "code": null, "e": 4821, "s": 4701, "text": "Take a look into the following code for applying community plugin using short name. Use this code in build.gradle file." }, { "code": null, "e": 4876, "s": 4821, "text": "plugins {\n id \"com.jfrog.bintray\" version \"0.4.1\"\n}\n" }, { "code": null, "e": 5045, "s": 4876, "text": "While creating a custom plugin, you need to write an implementation of plugin. Gradle instantiates the plugin and calls the plugin instance using Plugin.apply() method." }, { "code": null, "e": 5223, "s": 5045, "text": "The following example contains a greeting plugin, which adds a hello task to the project. Take a look into the following code and use this code in build.gradlebuild.gradle file." }, { "code": null, "e": 5433, "s": 5223, "text": "apply plugin: GreetingPlugin\n\nclass GreetingPlugin implements Plugin<Project> {\n void apply(Project project) {\n project.task('hello') << {\n println \"Hello from the GreetingPlugin\"\n }\n }\n}" }, { "code": null, "e": 5485, "s": 5433, "text": "Use the following code to execute the above script." }, { "code": null, "e": 5507, "s": 5485, "text": "C:\\> gradle -q hello\n" }, { "code": null, "e": 5514, "s": 5507, "text": "Output" }, { "code": null, "e": 5551, "s": 5514, "text": "This produces the following output −" }, { "code": null, "e": 5582, "s": 5551, "text": "Hello from the GreetingPlugin\n" }, { "code": null, "e": 5795, "s": 5582, "text": "Most of the plugins need the configuration support from the build script. The Gradle project has an associated ExtensionContainer object that helps to track all the setting and properties being passed to plugins." }, { "code": null, "e": 5983, "s": 5795, "text": "Let's add a simple extension object to the project. Here, we add a greeting extension object to the project, which allows you to configure the greeting. Use this code in build.gradlefile." }, { "code": null, "e": 6475, "s": 5983, "text": "apply plugin: GreetingPlugin\n\ngreeting.message = 'Hi from Gradle'\n\nclass GreetingPlugin implements Plugin<Project> {\n void apply(Project project) {\n // Add the 'greeting' extension object\n project.extensions.create(\"greeting\", GreetingPluginExtension)\n\t\t\n // Add a task that uses the configuration\n project.task('hello') << {\n println project.greeting.message\n }\n }\n}\n\nclass GreetingPluginExtension {\n def String message = 'Hello from GreetingPlugin'\n}" }, { "code": null, "e": 6528, "s": 6475, "text": "Use the following code to execute the above script −" }, { "code": null, "e": 6550, "s": 6528, "text": "C:\\> gradle -q hello\n" }, { "code": null, "e": 6557, "s": 6550, "text": "Output" }, { "code": null, "e": 6616, "s": 6557, "text": "When you run the code, you will see the following output −" }, { "code": null, "e": 6632, "s": 6616, "text": "Hi from Gradle\n" }, { "code": null, "e": 6899, "s": 6632, "text": "In this example, GreetingPlugin is a simple, old Groovy object with a field called message. The extension object is added to the plugin list with the name greeting. This object, then becomes available as a project property with the same name as the extension object." }, { "code": null, "e": 7073, "s": 6899, "text": "Gradle adds a configuration closure for each extension object, so you can group the settings together. Take a look at the following code. Use this code in build.gradle file." }, { "code": null, "e": 7511, "s": 7073, "text": "apply plugin: GreetingPlugin\n\ngreeting {\n message = 'Hi'\n greeter = 'Gradle'\n}\n\nclass GreetingPlugin implements Plugin<Project> {\n void apply(Project project) {\n project.extensions.create(\"greeting\", GreetingPluginExtension)\n\t\t\n project.task('hello') << {\n println \"${project.greeting.message} from ${project.greeting.greeter}\"\n }\n }\n}\n\nclass GreetingPluginExtension {\n String message\n String greeter\n}" }, { "code": null, "e": 7563, "s": 7511, "text": "Use the following code to execute the above script." }, { "code": null, "e": 7585, "s": 7563, "text": "C:\\> gradle -q hello\n" }, { "code": null, "e": 7592, "s": 7585, "text": "Output" }, { "code": null, "e": 7624, "s": 7592, "text": "The output is mentioned below −" }, { "code": null, "e": 7643, "s": 7624, "text": "Hello from Gradle\n" }, { "code": null, "e": 7718, "s": 7643, "text": "There are different plugins which are included in the Gradle distribution." }, { "code": null, "e": 7813, "s": 7718, "text": "These plugins add support for various languages which can be compiled and executed in the JVM." }, { "code": null, "e": 7862, "s": 7813, "text": "These plugins add support for various languages." }, { "code": null, "e": 7869, "s": 7862, "text": " Print" }, { "code": null, "e": 7880, "s": 7869, "text": " Add Notes" } ]
Write a program to form a cumulative sum list in Python
The cumulative sum till ith element refers to the total sum from 0th to ith element. The program statement is to form a new list from a given list. The ith element in the new list will be the cumulative sum from 0 to ith element in the given list. For example, [10,20,30,40,50] [10,30,60,100,150] [1,2,3,4,5] [1,3,6,10,15] Following is a program to form a cumulative sum list using the input list − The input list is passed to the function cumSum() which returns the cumulative sum list. The input list is passed to the function cumSum() which returns the cumulative sum list. We declare an empty list cum_list to which we will append elements to form the cumulative sum list. We declare an empty list cum_list to which we will append elements to form the cumulative sum list. Initialize a sum variable sm=0. Initialize a sum variable sm=0. Start iterating over the input list, with each iteration we increment the sum value to previous value+ the current element. Start iterating over the input list, with each iteration we increment the sum value to previous value+ the current element. On each iteration, the sum value is appended to the cum_list. On each iteration, the sum value is appended to the cum_list. Thus, on ith iteration, the sum variable will contain sum till the ith element(included), which is then appended to the cum_list. Thus, on ith iteration, the sum variable will contain sum till the ith element(included), which is then appended to the cum_list. After iterating through the whole list, the cum_list is returned. After iterating through the whole list, the cum_list is returned. Live Demo def cumSum(s): sm=0 cum_list=[] for i in s: sm=sm+i cum_list.append(sm) return cum_list a=[10,20,30,40,50] print(cumSum(a)) [10, 30, 60, 100, 150]
[ { "code": null, "e": 1147, "s": 1062, "text": "The cumulative sum till ith element refers to the total sum from 0th to ith element." }, { "code": null, "e": 1310, "s": 1147, "text": "The program statement is to form a new list from a given list. The ith element in the new list will be the cumulative sum from 0 to ith element in the given list." }, { "code": null, "e": 1323, "s": 1310, "text": "For example," }, { "code": null, "e": 1340, "s": 1323, "text": "[10,20,30,40,50]" }, { "code": null, "e": 1359, "s": 1340, "text": "[10,30,60,100,150]" }, { "code": null, "e": 1371, "s": 1359, "text": "[1,2,3,4,5]" }, { "code": null, "e": 1385, "s": 1371, "text": "[1,3,6,10,15]" }, { "code": null, "e": 1461, "s": 1385, "text": "Following is a program to form a cumulative sum list using the input list −" }, { "code": null, "e": 1550, "s": 1461, "text": "The input list is passed to the function cumSum() which returns the cumulative sum list." }, { "code": null, "e": 1639, "s": 1550, "text": "The input list is passed to the function cumSum() which returns the cumulative sum list." }, { "code": null, "e": 1739, "s": 1639, "text": "We declare an empty list cum_list to which we will append elements to form the cumulative sum list." }, { "code": null, "e": 1839, "s": 1739, "text": "We declare an empty list cum_list to which we will append elements to form the cumulative sum list." }, { "code": null, "e": 1871, "s": 1839, "text": "Initialize a sum variable sm=0." }, { "code": null, "e": 1903, "s": 1871, "text": "Initialize a sum variable sm=0." }, { "code": null, "e": 2027, "s": 1903, "text": "Start iterating over the input list, with each iteration we increment the sum value to previous value+ the current element." }, { "code": null, "e": 2151, "s": 2027, "text": "Start iterating over the input list, with each iteration we increment the sum value to previous value+ the current element." }, { "code": null, "e": 2213, "s": 2151, "text": "On each iteration, the sum value is appended to the cum_list." }, { "code": null, "e": 2275, "s": 2213, "text": "On each iteration, the sum value is appended to the cum_list." }, { "code": null, "e": 2405, "s": 2275, "text": "Thus, on ith iteration, the sum variable will contain sum till the ith element(included), which is then appended to the cum_list." }, { "code": null, "e": 2535, "s": 2405, "text": "Thus, on ith iteration, the sum variable will contain sum till the ith element(included), which is then appended to the cum_list." }, { "code": null, "e": 2601, "s": 2535, "text": "After iterating through the whole list, the cum_list is returned." }, { "code": null, "e": 2667, "s": 2601, "text": "After iterating through the whole list, the cum_list is returned." }, { "code": null, "e": 2678, "s": 2667, "text": " Live Demo" }, { "code": null, "e": 2827, "s": 2678, "text": "def cumSum(s):\n sm=0\n cum_list=[]\n for i in s:\n sm=sm+i\n cum_list.append(sm)\n return cum_list\n\na=[10,20,30,40,50]\nprint(cumSum(a))" }, { "code": null, "e": 2850, "s": 2827, "text": "[10, 30, 60, 100, 150]" } ]
Convert String to Tuple in Python
When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result. The 'int' method converts the given data type to an integer type, if that operation is permitted. The split method splits the given data into different sections based on a delimiter or a default delimiter. The 'tuple' method converts the given data type into a tuple type. Below is a demonstration of the same − Live Demo my_str_1 = "7, 8, 0, 3, 45, 3, 2, 22, 4" print ("The string is : " ) print(my_str_1) my_result = tuple(map(int, my_str_1.split(', '))) print("The tuple after converting from a string is : ") print(my_result) The string is : 7, 8, 0, 3, 45, 3, 2, 22, 4 The tuple after converting from a string is : (7, 8, 0, 3, 45, 3, 2, 22, 4) A string is defined and is displayed on the console. The string is split, and every element is converted to an integer, and this operation is applied to every element using the 'map' method. This is again converted to a tuple type. This result is assigned to a value. It is displayed as output on the console.
[ { "code": null, "e": 1208, "s": 1062, "text": "When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used." }, { "code": null, "e": 1345, "s": 1208, "text": "The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result." }, { "code": null, "e": 1443, "s": 1345, "text": "The 'int' method converts the given data type to an integer type, if that operation is permitted." }, { "code": null, "e": 1618, "s": 1443, "text": "The split method splits the given data into different sections based on a delimiter or a default delimiter. The 'tuple' method converts the given data type into a tuple type." }, { "code": null, "e": 1657, "s": 1618, "text": "Below is a demonstration of the same −" }, { "code": null, "e": 1667, "s": 1657, "text": "Live Demo" }, { "code": null, "e": 1878, "s": 1667, "text": "my_str_1 = \"7, 8, 0, 3, 45, 3, 2, 22, 4\"\n\nprint (\"The string is : \" )\nprint(my_str_1)\n\nmy_result = tuple(map(int, my_str_1.split(', ')))\n\nprint(\"The tuple after converting from a string is : \")\nprint(my_result)" }, { "code": null, "e": 1998, "s": 1878, "text": "The string is :\n7, 8, 0, 3, 45, 3, 2, 22, 4\nThe tuple after converting from a string is :\n(7, 8, 0, 3, 45, 3, 2, 22, 4)" }, { "code": null, "e": 2051, "s": 1998, "text": "A string is defined and is displayed on the console." }, { "code": null, "e": 2189, "s": 2051, "text": "The string is split, and every element is converted to an integer, and this operation is applied to every element using the 'map' method." }, { "code": null, "e": 2230, "s": 2189, "text": "This is again converted to a tuple type." }, { "code": null, "e": 2266, "s": 2230, "text": "This result is assigned to a value." }, { "code": null, "e": 2308, "s": 2266, "text": "It is displayed as output on the console." } ]
Predicting Popularity on Spotify — When Data Needs Culture More than Culture Needs Data | by Philip Peker | Towards Data Science
Back when I was an Original Music intern at Butter Music in 2016, our team thought a lot about how to parameterize audio. For one, we were laying the foundation for a proprietary music sync library and we needed a novel taxonomy for all the different sounds that were going to make up the library. The goal was to allow our current and future clients to search by mood, genre, instruments or other keywords. In the meantime, we were also continuing to write original music for our clients’ commercials. While this workflow was more custom and service-driven, we still had to figure out how to continuously transform client feedback such as “Let’s make the track more inquisitive and approachable, but less sappy” into actual melodies, arrangements, timbres, and atmospheres. With both of these tasks, it felt like we were missing a translation layer between colloquial language and the language of music. This problem is not new. If you’re a music nut like, I’m sure you’ve sometimes struggled for the right words that explain why you like a song so much. “I don’t know, it’s just so funky and smooth” is usually what rolls out of my mouth when describing the new Emotional Oranges or SiR track that I can’t stop telling my friends about. Many organizations and teams have embarked on the journey of quantifying music at scale, but none as radically as Spotify. According to Counterpoint Research, they hold a 34% plurality market share in the world for paid subscriptions, as compared to all the other competitions in the space. Apply Music comes in second with a 21% marketshare. Consequently, this also means the size and scale of their data warehouses are second to none. Spotify has found a wonderful harmony between their data engineering teams and their product and sales teams. They feed off and into each other, driving the company’s unrelenting growth. The better Spotify can quantify music, the better they can tune their systems and algorithms to generate more revenue for themselves and their stakeholders. I was fascinated by Spotify’s unique business goal of making quantitative sense of music. So fascinated, that it pushed me to go out of my comfort zone and embark on my personal data science journey to better understand the interplay between music and data. In this article, I invite you to come walk the path I took for my first Machine Learning project using Spotify tracks data as the focal point. Before I move any further, I want to make a few things clear— this article details the trek I took from 0 to 1 and not 1 to ‘n’. My methodology was neither exhaustive nor flawless, and in fact, likely contains many technical opportunities missed, some of which I touch on near the end of the article. I am excited to continue iterating and learning as I go and so this project is not a final stop, but merely a first step. What I want to leave behind is the bigger-picture findings that helped me wrap my head around the shape and size of the problem in quantifying and parameterizing music. I don’t purport to solve anything here, but rather shed a new light, and at a new angle, on an age-old problem that will only get more complex the more we listen and stream music. Alright, enough preambling, let’s dig in. For my data science capstone project (shoutout to General Assembly) I was interested in finding out a bit more on how Spotify understands ‘popularity’. The essential question for me was: could we use a song’s attributes to predict a track’s ‘popularity’? From the get-go, I was eyeing a Kaggle dataset that was put together based on Spotify’s Web API. For those not familiar with the Spotify Web API, here is a screenshot of just some of the callable parameters that can be used to analyze tracks on Spotify: According to Spotify, “popularity is calculated by algorithm and is based, in the most part, on the total number of plays the track has had and how recent those plays are. Generally speaking, songs that are being played a lot now will have a higher popularity than songs that were played a lot in the past.” The first order of business for me is to take a look at the data source and begin on some exploratory data analysis. The dataset has 586,672 rows, 20 columns. Off the bat, I notice three wrinkles in the data that I should be mindful of: Two variables are already dummified (‘mode’ and ‘explicit’) Certain categorical variables, such as ‘key’, are value-encoded, but their relative values are meaningless. If 0 is the key of C, and 1 is the key of C#, this does not mean the key of C# is intrinsically greater by 1 point than the key of C ‘timesignature’ is a predicted value already Let’s take a look at the raw data to ensure it’s in the best format. We drop some null values and do one retouch on the ‘duration_ms’ column. Duration is being expressed in milliseconds which makes little sense in the context of song duration, so we convert to minutes. It may also be useful to dummify the three categorical variables we have in the dataframe, so let’s just do that now. data = pd.get_dummies(data, columns=['time_signature', 'key', 'mode'], drop_first=True) With that, we should be good to start on some visualizations. For starters, we generate some Seaborn Pair plots across several variables: Shockingly, there are little to no simple linear relationships that jump out. Let’s continue on to some more granular visualizations to see what’s really going on. Since predicting popularity is our north star, I’m curious to see what the popularity distribution is across the dataset. The Pareto principle is in full effect here, with a right skewed distribution showing us how truly rare it is to have a popular song. I also want to discover some domain-specific nuances in the data. Among several fun visualizations, the double bar plot of Key/Mode vs Popularity highlighted some interesting points. In Western music, there exists 12 possible keys. Each key, however, can live in either a minor or a major tonality. Diatonically speaking, there are three major modes, and four minor modes. This bar plot describes how the popularity differs for the same key across different tonalities (0 being a minor tonality, 1 being major). For example, a track in C# minor tends to be more popular than a track in C# major. Surely, a confounding variable here could be the keys that a vocalist prefers, assuming the more popular a track is, the more likely it contains vocals, which based on the third point below, seems like a fair assumption to make (i.e ‘acousticness’ has a negative correlation with ‘popularity’). Let’s look at a correlation table to identify some baseline correlations between our many X variables. plt.figure(figsize=(20, 10))sns.heatmap(data.corr(),annot = True) Some observations: ‘Energy’ and ‘loudness’ have the highest correlation, and a positive one, which does not surprise ‘Energy’ and ‘acousticness’ have a highly-correlated inverse relationship, which also makes total sense. The more a song skews towards being acoustic, the less energy it tends to be Unfortunately, with our dependent variable being ‘popularity’, we notice very poor correlation values across our independent variables. The best we get is a -.37 between ‘acousticness’ and ‘popularity’ From this correlation matrix, I plucked four of the best features (ones with the highest correlation) to use later on during feature engineering. These four are: ‘acousticness’, ‘instrumentalness’, ‘loudness’, and ‘energy’ By squaring our highest correlation coefficient, R, we get the coefficient of determination (R2) that we need to clear: .136. The bar is low, but let’s explore by how much we can beat it. To warm up the oven, let’s see what kind of success we can get from a simple linear regression model. Set the variables: Set the variables: X = data[features]y = data['popularity'] For now [features] includes every single independent variable in our dataframe. 2. Split our data from sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionX_train, X_test, y_train, y_test = train_test_split(X[features], y, train_size=0.5, random_state=8) 3. Train our model lr = LinearRegression()lr.fit(X_train, y_train)lr.score(X_test, y_test) This prints out our coefficient of determination, R2, of .213. While we did already beat our baseline, generally speaking, this is a dangerously low R2. 4. Making predictions Now let’s pass a predict method to our testing data. y_pred = lr.predict(X_test) 5. Metric Evaluation Finally, we can print out three key metrics to determine model fit. print(metrics.mean_absolute_error(y_test, y_pred))print(metrics.mean_squared_error(y_test, y_pred))print(np.sqrt(metrics.mean_squared_error(y_test, y_pred))) MAE = 13.24 MSE = 266.19 RMSE = 16.32 6. Conclusion As is standard protocol, we use RMSE as the primary metric to evaluate our linear regression model. An average of 16.32 spread for our residuals in the prediction model for a range of 0–100 in ‘popularity’ is huge. And with R2 value of .213, we haven’t even beat our base correlation. I ran this model again, but now with only the four best features noted above. The model actually worsened, with an R2 of .181 and an RMSE of 16.64. So let’s see if we can nudge these in a positive direction with some other regression techniques. Model 2: Decision Tree from sklearn.tree import DecisionTreeRegressormax_depth_range = range(1, 15)RMSE_scores = []from sklearn.model_selection import cross_val_scorefor depth in max_depth_range: treereg = DecisionTreeRegressor(max_depth=depth, random_state=1) MSE_scores = cross_val_score(treereg, X, y, cv=5, scoring='neg_mean_squared_error') RMSE_scores.append(np.mean(np.sqrt(-MSE_scores)))plt.plot(max_depth_range, RMSE_scores);plt.xlabel('max_depth');plt.ylabel('RMSE (lower is better)'); Even with just a small range of (1, 15), we managed to get a better RMSE of 15.64 using a max_depth_range of 10. Better, but given the nature of decision trees, we naturally engaged in some gross overfitting for a minor gain in the standard deviation of our prediction errors. Model 3: Random Forest Another stretch to try and curb overfitting and improve accuracy. We apply the same methodology as above to a random tree regressor model, and see the following metrics: RMSE: 14.80 Out of bag score: .38 *A reminder: an out of bag score is the accuracy of examples xi using all the trees in the random forest ensemble for which it was omitted during training. We see that our OOB score is now handsomely beating our baseline R2. As far as regression models tested, hiking through the random forest has led us to a happier destination. We’re getting closer and closer to a model that has a stronger generalizability, which is ultimately what we’re shooting for here. With all this being said, I’m definitely not excited about the results we’re getting with our regression methods, so perhaps it’s time to see what the classification world could offer us. Off we go. In order to set up any kind of classification models, we need to move away from trying to predict a continuous integer value for our output, ‘popularity’, and instead predict categories/labels for it. So let’s create some bins for ‘popularity’. We’ll segment and sort our values into equal bins of ‘low’, ‘medium’ and ‘high’ popularity using pd.cut. One element that sticks out from our binning is the uneven count distribution across the three bins. Knowing how easily some classification models can be affected by imbalanced data, I resampled the classes using RandomOverSampler from the imbalanced-learn package: Now that our classes are even, we can set up and instantiate our classification model; this time, we’ll try a KNN classifier. Let’s re-input our four top features to set up our design matrix: feature_cols = ['acousticness', 'instrumentalness', 'loudness', 'energy']X = data[feature_cols] Next, we can perform a train-test split using our oversampled classes: X_train, X_test, y_train, y_test = train_test_split(X_ros, y_ros, random_state=99, test_size=0.3)knn = KNeighborsClassifier(n_neighbors=1)knn.fit(X_train, y_train)y_pred_class = knn.predict(X_test)print(metrics.accuracy_score(y_test, y_pred_class)) Out pops an accuracy score of: .807 Holy smokes, what an improvement. Smells like major overfitting though, so let’s implement some hyperparameter tuning and search for an optimal ‘k’. Since both manual nearest neighbor searching using for-loops and GridSearch were very computationally expensive for my humble computer, I opted to use RandomizedSearchCV. This package still implements a “fit” and “score” method but doesn’t try out all parameter values, like GridSearch does. Rather, a fixed number of parameter settings get sampled from the specified distributions. So how did we do? First, we can print out a confusion matrix. from sklearn.metrics import confusion_matrixcmat = confusion_matrix(y_test, y_pred_class)#print(cmat)print('TP - True Negative {}'.format(cmat[0,0]))print('FP - Flase Positive {}'.format(cmat[0,1]))print('FN - False Negative {}'.format(cmat[1,0]))print('TP - True Positive {}'.format(cmat[1,1]))print('Accuracy Score: {}'.format(np.divide(np.sum([cmat[0,0], cmat[1,1], cmat[2,2]]), np.sum(cmat)))) print('Misclassification Rate: {}'.format(np.divide(np.sum([cmat[1,0], cmat[0,1], cmat[0,2], cmat[2,0], cmat[1,2], cmat[2,1]]), np.sum(cmat)))) An accuracy score of 56.52% is the best we’ve batted so far, and I’m feeling fairly confident in the veracity of this score. For our KNN model, we balanced our classes, we feature engineered, we performed some hyperparameter tuning, and we came all the way from regression world to boot! But for all our work, when we zoom out, an accuracy of 56.52% also means an average error rate 43.48% in predicting with our model. Our highest-performing model was the KNN classification model, but this comes with a large asterisk. Morphing our data to allow for a discrete, classification approach versus a continuous, regression approach means that predictive robustness within the model was largely swept under the rug. It’s much easier for a model to predict for one of three popularity classes (“low”, “medium” or “high”), versus a discrete numerical score for popularity from 0–100. So while we can feel more optimistic about the accuracy of the model itself, we’re far from being able to productionalize this and enable a fulfilling end-user prediction experience from our work so far. I’m also hyper-aware of other limitations that I faced throughout: Machine learning becomes computationally expensive, quickly, and I had to make concessions so that I could even run certain blocks of code. This compromised some level of robustness and depth, whether it was using only five folds for our cross-validator, versus the industry standard of cv=10, or only running our RandomizedSearch for a k_range of (1, 22) In the future, I could try testing a weighted KNN (weighted voting) model to mollify the effect of our imperfect search for the perfect k Did I handle the data balance problem correctly? While we flagged it and did oversample, I did not try undersampling, and perhaps this could have yielded a different result. Yes, it would be less counts, but also less synthetic, duplicative rows As I crawled out of the ML cave, I wondered if there is a bigger question here in terms of the dataset philosophy itself, and whether this was an ontological limitation. Why is it that for a dataset that is so well-manicured and organized, and with no shortage of rows, the relationships found within are strained? One would think that popularity is a lever that artists, labels, management companies, A&R, and Spotify themselves would want to be able to pull up and down. The obvious answer is that there are thousands of other variables that add to the noise. And, perhaps selecting popularity as the dependent variable in my project meant I was destined for disappointment, in that it highlighted how narrow the independent variables I was given to work with are, and also how little we truly know about the Spotify algorithm that computes ‘popularity’. This dataset and its Web API parent is descriptive, not predictive, in nature. ‘good 4 u’ by Olivia Rodrigo isn’t popular because it’s loudness, energy, and instrumentalness scores are high (even though they probably are, but that song wasn’t in this somewhat outdated dataset unfortunately). It’s popular because of who Olivia is, her blend of nostalgic old (hi @ Paramore) with sparkly new, and the buildup of anticipation for anything by Olivia after ‘drivers license’. Where were these parameters in our dataset?! Given the state of modern music and how it’s consumed, it would be prudent to study variables such as, and we’re just scratching the surface here: Social media following Whether an artist is signed to a record label, and if so, which one? A metric to represent an artists’ network value (A “Who do you know here?” score) A “nostalgia” score Historical data for that artist We could also look to break down “popularity” into subsets based on: region demographics which device is it streaming on number of shared Spotify accounts ...and many more slices. With just these new features added to our dataframe, it would be interesting to see if there is an improvement in our model accuracy, and if so, by how much. And yet, like all guardians of a galaxy, Spotify prudently keeps this type of data hidden. Whether for reasons involving PII, or stakeholder contracts and master service agreements, or anything else beyond our purview, those accessing Spotify data via the API are ultimately accessing just the tip of the data iceberg. Obviously, the world of data science and AI extends far, far beyond what was was tried here. Moving forward, I’d love to dig into unsupervised learning and deep learning techniques to see what delights we can find along those paths. All in all, I’m really excited to see the music analytics vertical grow. Coming out of this project, I have a renewed sense of hope that even in our algorithmic, seemingly monolithic streaming world, we can still have wild, silky, colorful, complicated, emotional auditory outliers that punch us in the gut and wake us the f*** up. Thanks for reading all the way until the end (hell, I barely made it to the end writing this). I’m personally still making sense of all this newness, and would love to hear your thoughts on my thoughts, whether you’re a data scientist, a musician, a Spotify enthusiast, a fan of cultural insights, or anything at all. Until next time 🎶 In case you want to check out the full Jupyter notebook and a high-level powerpoint for this capstone project, here’s the Github: https://github.com/philinyouin/SpotifyPopularityPrediction
[ { "code": null, "e": 580, "s": 172, "text": "Back when I was an Original Music intern at Butter Music in 2016, our team thought a lot about how to parameterize audio. For one, we were laying the foundation for a proprietary music sync library and we needed a novel taxonomy for all the different sounds that were going to make up the library. The goal was to allow our current and future clients to search by mood, genre, instruments or other keywords." }, { "code": null, "e": 947, "s": 580, "text": "In the meantime, we were also continuing to write original music for our clients’ commercials. While this workflow was more custom and service-driven, we still had to figure out how to continuously transform client feedback such as “Let’s make the track more inquisitive and approachable, but less sappy” into actual melodies, arrangements, timbres, and atmospheres." }, { "code": null, "e": 1411, "s": 947, "text": "With both of these tasks, it felt like we were missing a translation layer between colloquial language and the language of music. This problem is not new. If you’re a music nut like, I’m sure you’ve sometimes struggled for the right words that explain why you like a song so much. “I don’t know, it’s just so funky and smooth” is usually what rolls out of my mouth when describing the new Emotional Oranges or SiR track that I can’t stop telling my friends about." }, { "code": null, "e": 1754, "s": 1411, "text": "Many organizations and teams have embarked on the journey of quantifying music at scale, but none as radically as Spotify. According to Counterpoint Research, they hold a 34% plurality market share in the world for paid subscriptions, as compared to all the other competitions in the space. Apply Music comes in second with a 21% marketshare." }, { "code": null, "e": 2035, "s": 1754, "text": "Consequently, this also means the size and scale of their data warehouses are second to none. Spotify has found a wonderful harmony between their data engineering teams and their product and sales teams. They feed off and into each other, driving the company’s unrelenting growth." }, { "code": null, "e": 2192, "s": 2035, "text": "The better Spotify can quantify music, the better they can tune their systems and algorithms to generate more revenue for themselves and their stakeholders." }, { "code": null, "e": 2450, "s": 2192, "text": "I was fascinated by Spotify’s unique business goal of making quantitative sense of music. So fascinated, that it pushed me to go out of my comfort zone and embark on my personal data science journey to better understand the interplay between music and data." }, { "code": null, "e": 2593, "s": 2450, "text": "In this article, I invite you to come walk the path I took for my first Machine Learning project using Spotify tracks data as the focal point." }, { "code": null, "e": 3016, "s": 2593, "text": "Before I move any further, I want to make a few things clear— this article details the trek I took from 0 to 1 and not 1 to ‘n’. My methodology was neither exhaustive nor flawless, and in fact, likely contains many technical opportunities missed, some of which I touch on near the end of the article. I am excited to continue iterating and learning as I go and so this project is not a final stop, but merely a first step." }, { "code": null, "e": 3365, "s": 3016, "text": "What I want to leave behind is the bigger-picture findings that helped me wrap my head around the shape and size of the problem in quantifying and parameterizing music. I don’t purport to solve anything here, but rather shed a new light, and at a new angle, on an age-old problem that will only get more complex the more we listen and stream music." }, { "code": null, "e": 3407, "s": 3365, "text": "Alright, enough preambling, let’s dig in." }, { "code": null, "e": 3662, "s": 3407, "text": "For my data science capstone project (shoutout to General Assembly) I was interested in finding out a bit more on how Spotify understands ‘popularity’. The essential question for me was: could we use a song’s attributes to predict a track’s ‘popularity’?" }, { "code": null, "e": 3916, "s": 3662, "text": "From the get-go, I was eyeing a Kaggle dataset that was put together based on Spotify’s Web API. For those not familiar with the Spotify Web API, here is a screenshot of just some of the callable parameters that can be used to analyze tracks on Spotify:" }, { "code": null, "e": 4224, "s": 3916, "text": "According to Spotify, “popularity is calculated by algorithm and is based, in the most part, on the total number of plays the track has had and how recent those plays are. Generally speaking, songs that are being played a lot now will have a higher popularity than songs that were played a lot in the past.”" }, { "code": null, "e": 4341, "s": 4224, "text": "The first order of business for me is to take a look at the data source and begin on some exploratory data analysis." }, { "code": null, "e": 4383, "s": 4341, "text": "The dataset has 586,672 rows, 20 columns." }, { "code": null, "e": 4461, "s": 4383, "text": "Off the bat, I notice three wrinkles in the data that I should be mindful of:" }, { "code": null, "e": 4521, "s": 4461, "text": "Two variables are already dummified (‘mode’ and ‘explicit’)" }, { "code": null, "e": 4762, "s": 4521, "text": "Certain categorical variables, such as ‘key’, are value-encoded, but their relative values are meaningless. If 0 is the key of C, and 1 is the key of C#, this does not mean the key of C# is intrinsically greater by 1 point than the key of C" }, { "code": null, "e": 4807, "s": 4762, "text": "‘timesignature’ is a predicted value already" }, { "code": null, "e": 4876, "s": 4807, "text": "Let’s take a look at the raw data to ensure it’s in the best format." }, { "code": null, "e": 5077, "s": 4876, "text": "We drop some null values and do one retouch on the ‘duration_ms’ column. Duration is being expressed in milliseconds which makes little sense in the context of song duration, so we convert to minutes." }, { "code": null, "e": 5195, "s": 5077, "text": "It may also be useful to dummify the three categorical variables we have in the dataframe, so let’s just do that now." }, { "code": null, "e": 5283, "s": 5195, "text": "data = pd.get_dummies(data, columns=['time_signature', 'key', 'mode'], drop_first=True)" }, { "code": null, "e": 5345, "s": 5283, "text": "With that, we should be good to start on some visualizations." }, { "code": null, "e": 5421, "s": 5345, "text": "For starters, we generate some Seaborn Pair plots across several variables:" }, { "code": null, "e": 5585, "s": 5421, "text": "Shockingly, there are little to no simple linear relationships that jump out. Let’s continue on to some more granular visualizations to see what’s really going on." }, { "code": null, "e": 5707, "s": 5585, "text": "Since predicting popularity is our north star, I’m curious to see what the popularity distribution is across the dataset." }, { "code": null, "e": 5841, "s": 5707, "text": "The Pareto principle is in full effect here, with a right skewed distribution showing us how truly rare it is to have a popular song." }, { "code": null, "e": 6024, "s": 5841, "text": "I also want to discover some domain-specific nuances in the data. Among several fun visualizations, the double bar plot of Key/Mode vs Popularity highlighted some interesting points." }, { "code": null, "e": 6437, "s": 6024, "text": "In Western music, there exists 12 possible keys. Each key, however, can live in either a minor or a major tonality. Diatonically speaking, there are three major modes, and four minor modes. This bar plot describes how the popularity differs for the same key across different tonalities (0 being a minor tonality, 1 being major). For example, a track in C# minor tends to be more popular than a track in C# major." }, { "code": null, "e": 6732, "s": 6437, "text": "Surely, a confounding variable here could be the keys that a vocalist prefers, assuming the more popular a track is, the more likely it contains vocals, which based on the third point below, seems like a fair assumption to make (i.e ‘acousticness’ has a negative correlation with ‘popularity’)." }, { "code": null, "e": 6835, "s": 6732, "text": "Let’s look at a correlation table to identify some baseline correlations between our many X variables." }, { "code": null, "e": 6901, "s": 6835, "text": "plt.figure(figsize=(20, 10))sns.heatmap(data.corr(),annot = True)" }, { "code": null, "e": 6920, "s": 6901, "text": "Some observations:" }, { "code": null, "e": 7018, "s": 6920, "text": "‘Energy’ and ‘loudness’ have the highest correlation, and a positive one, which does not surprise" }, { "code": null, "e": 7200, "s": 7018, "text": "‘Energy’ and ‘acousticness’ have a highly-correlated inverse relationship, which also makes total sense. The more a song skews towards being acoustic, the less energy it tends to be" }, { "code": null, "e": 7402, "s": 7200, "text": "Unfortunately, with our dependent variable being ‘popularity’, we notice very poor correlation values across our independent variables. The best we get is a -.37 between ‘acousticness’ and ‘popularity’" }, { "code": null, "e": 7625, "s": 7402, "text": "From this correlation matrix, I plucked four of the best features (ones with the highest correlation) to use later on during feature engineering. These four are: ‘acousticness’, ‘instrumentalness’, ‘loudness’, and ‘energy’" }, { "code": null, "e": 7813, "s": 7625, "text": "By squaring our highest correlation coefficient, R, we get the coefficient of determination (R2) that we need to clear: .136. The bar is low, but let’s explore by how much we can beat it." }, { "code": null, "e": 7915, "s": 7813, "text": "To warm up the oven, let’s see what kind of success we can get from a simple linear regression model." }, { "code": null, "e": 7934, "s": 7915, "text": "Set the variables:" }, { "code": null, "e": 7953, "s": 7934, "text": "Set the variables:" }, { "code": null, "e": 7994, "s": 7953, "text": "X = data[features]y = data['popularity']" }, { "code": null, "e": 8074, "s": 7994, "text": "For now [features] includes every single independent variable in our dataframe." }, { "code": null, "e": 8092, "s": 8074, "text": "2. Split our data" }, { "code": null, "e": 8293, "s": 8092, "text": "from sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionX_train, X_test, y_train, y_test = train_test_split(X[features], y, train_size=0.5, random_state=8)" }, { "code": null, "e": 8312, "s": 8293, "text": "3. Train our model" }, { "code": null, "e": 8384, "s": 8312, "text": "lr = LinearRegression()lr.fit(X_train, y_train)lr.score(X_test, y_test)" }, { "code": null, "e": 8537, "s": 8384, "text": "This prints out our coefficient of determination, R2, of .213. While we did already beat our baseline, generally speaking, this is a dangerously low R2." }, { "code": null, "e": 8559, "s": 8537, "text": "4. Making predictions" }, { "code": null, "e": 8612, "s": 8559, "text": "Now let’s pass a predict method to our testing data." }, { "code": null, "e": 8640, "s": 8612, "text": "y_pred = lr.predict(X_test)" }, { "code": null, "e": 8661, "s": 8640, "text": "5. Metric Evaluation" }, { "code": null, "e": 8729, "s": 8661, "text": "Finally, we can print out three key metrics to determine model fit." }, { "code": null, "e": 8887, "s": 8729, "text": "print(metrics.mean_absolute_error(y_test, y_pred))print(metrics.mean_squared_error(y_test, y_pred))print(np.sqrt(metrics.mean_squared_error(y_test, y_pred)))" }, { "code": null, "e": 8899, "s": 8887, "text": "MAE = 13.24" }, { "code": null, "e": 8912, "s": 8899, "text": "MSE = 266.19" }, { "code": null, "e": 8925, "s": 8912, "text": "RMSE = 16.32" }, { "code": null, "e": 8939, "s": 8925, "text": "6. Conclusion" }, { "code": null, "e": 9154, "s": 8939, "text": "As is standard protocol, we use RMSE as the primary metric to evaluate our linear regression model. An average of 16.32 spread for our residuals in the prediction model for a range of 0–100 in ‘popularity’ is huge." }, { "code": null, "e": 9224, "s": 9154, "text": "And with R2 value of .213, we haven’t even beat our base correlation." }, { "code": null, "e": 9372, "s": 9224, "text": "I ran this model again, but now with only the four best features noted above. The model actually worsened, with an R2 of .181 and an RMSE of 16.64." }, { "code": null, "e": 9470, "s": 9372, "text": "So let’s see if we can nudge these in a positive direction with some other regression techniques." }, { "code": null, "e": 9493, "s": 9470, "text": "Model 2: Decision Tree" }, { "code": null, "e": 9974, "s": 9493, "text": "from sklearn.tree import DecisionTreeRegressormax_depth_range = range(1, 15)RMSE_scores = []from sklearn.model_selection import cross_val_scorefor depth in max_depth_range: treereg = DecisionTreeRegressor(max_depth=depth, random_state=1) MSE_scores = cross_val_score(treereg, X, y, cv=5, scoring='neg_mean_squared_error') RMSE_scores.append(np.mean(np.sqrt(-MSE_scores)))plt.plot(max_depth_range, RMSE_scores);plt.xlabel('max_depth');plt.ylabel('RMSE (lower is better)');" }, { "code": null, "e": 10251, "s": 9974, "text": "Even with just a small range of (1, 15), we managed to get a better RMSE of 15.64 using a max_depth_range of 10. Better, but given the nature of decision trees, we naturally engaged in some gross overfitting for a minor gain in the standard deviation of our prediction errors." }, { "code": null, "e": 10274, "s": 10251, "text": "Model 3: Random Forest" }, { "code": null, "e": 10444, "s": 10274, "text": "Another stretch to try and curb overfitting and improve accuracy. We apply the same methodology as above to a random tree regressor model, and see the following metrics:" }, { "code": null, "e": 10456, "s": 10444, "text": "RMSE: 14.80" }, { "code": null, "e": 10478, "s": 10456, "text": "Out of bag score: .38" }, { "code": null, "e": 10634, "s": 10478, "text": "*A reminder: an out of bag score is the accuracy of examples xi using all the trees in the random forest ensemble for which it was omitted during training." }, { "code": null, "e": 10940, "s": 10634, "text": "We see that our OOB score is now handsomely beating our baseline R2. As far as regression models tested, hiking through the random forest has led us to a happier destination. We’re getting closer and closer to a model that has a stronger generalizability, which is ultimately what we’re shooting for here." }, { "code": null, "e": 11139, "s": 10940, "text": "With all this being said, I’m definitely not excited about the results we’re getting with our regression methods, so perhaps it’s time to see what the classification world could offer us. Off we go." }, { "code": null, "e": 11489, "s": 11139, "text": "In order to set up any kind of classification models, we need to move away from trying to predict a continuous integer value for our output, ‘popularity’, and instead predict categories/labels for it. So let’s create some bins for ‘popularity’. We’ll segment and sort our values into equal bins of ‘low’, ‘medium’ and ‘high’ popularity using pd.cut." }, { "code": null, "e": 11755, "s": 11489, "text": "One element that sticks out from our binning is the uneven count distribution across the three bins. Knowing how easily some classification models can be affected by imbalanced data, I resampled the classes using RandomOverSampler from the imbalanced-learn package:" }, { "code": null, "e": 11881, "s": 11755, "text": "Now that our classes are even, we can set up and instantiate our classification model; this time, we’ll try a KNN classifier." }, { "code": null, "e": 11947, "s": 11881, "text": "Let’s re-input our four top features to set up our design matrix:" }, { "code": null, "e": 12043, "s": 11947, "text": "feature_cols = ['acousticness', 'instrumentalness', 'loudness', 'energy']X = data[feature_cols]" }, { "code": null, "e": 12114, "s": 12043, "text": "Next, we can perform a train-test split using our oversampled classes:" }, { "code": null, "e": 12363, "s": 12114, "text": "X_train, X_test, y_train, y_test = train_test_split(X_ros, y_ros, random_state=99, test_size=0.3)knn = KNeighborsClassifier(n_neighbors=1)knn.fit(X_train, y_train)y_pred_class = knn.predict(X_test)print(metrics.accuracy_score(y_test, y_pred_class))" }, { "code": null, "e": 12399, "s": 12363, "text": "Out pops an accuracy score of: .807" }, { "code": null, "e": 12548, "s": 12399, "text": "Holy smokes, what an improvement. Smells like major overfitting though, so let’s implement some hyperparameter tuning and search for an optimal ‘k’." }, { "code": null, "e": 12931, "s": 12548, "text": "Since both manual nearest neighbor searching using for-loops and GridSearch were very computationally expensive for my humble computer, I opted to use RandomizedSearchCV. This package still implements a “fit” and “score” method but doesn’t try out all parameter values, like GridSearch does. Rather, a fixed number of parameter settings get sampled from the specified distributions." }, { "code": null, "e": 12949, "s": 12931, "text": "So how did we do?" }, { "code": null, "e": 12993, "s": 12949, "text": "First, we can print out a confusion matrix." }, { "code": null, "e": 13535, "s": 12993, "text": "from sklearn.metrics import confusion_matrixcmat = confusion_matrix(y_test, y_pred_class)#print(cmat)print('TP - True Negative {}'.format(cmat[0,0]))print('FP - Flase Positive {}'.format(cmat[0,1]))print('FN - False Negative {}'.format(cmat[1,0]))print('TP - True Positive {}'.format(cmat[1,1]))print('Accuracy Score: {}'.format(np.divide(np.sum([cmat[0,0], cmat[1,1], cmat[2,2]]), np.sum(cmat)))) print('Misclassification Rate: {}'.format(np.divide(np.sum([cmat[1,0], cmat[0,1], cmat[0,2], cmat[2,0], cmat[1,2], cmat[2,1]]), np.sum(cmat))))" }, { "code": null, "e": 13955, "s": 13535, "text": "An accuracy score of 56.52% is the best we’ve batted so far, and I’m feeling fairly confident in the veracity of this score. For our KNN model, we balanced our classes, we feature engineered, we performed some hyperparameter tuning, and we came all the way from regression world to boot! But for all our work, when we zoom out, an accuracy of 56.52% also means an average error rate 43.48% in predicting with our model." }, { "code": null, "e": 14617, "s": 13955, "text": "Our highest-performing model was the KNN classification model, but this comes with a large asterisk. Morphing our data to allow for a discrete, classification approach versus a continuous, regression approach means that predictive robustness within the model was largely swept under the rug. It’s much easier for a model to predict for one of three popularity classes (“low”, “medium” or “high”), versus a discrete numerical score for popularity from 0–100. So while we can feel more optimistic about the accuracy of the model itself, we’re far from being able to productionalize this and enable a fulfilling end-user prediction experience from our work so far." }, { "code": null, "e": 14684, "s": 14617, "text": "I’m also hyper-aware of other limitations that I faced throughout:" }, { "code": null, "e": 15040, "s": 14684, "text": "Machine learning becomes computationally expensive, quickly, and I had to make concessions so that I could even run certain blocks of code. This compromised some level of robustness and depth, whether it was using only five folds for our cross-validator, versus the industry standard of cv=10, or only running our RandomizedSearch for a k_range of (1, 22)" }, { "code": null, "e": 15178, "s": 15040, "text": "In the future, I could try testing a weighted KNN (weighted voting) model to mollify the effect of our imperfect search for the perfect k" }, { "code": null, "e": 15424, "s": 15178, "text": "Did I handle the data balance problem correctly? While we flagged it and did oversample, I did not try undersampling, and perhaps this could have yielded a different result. Yes, it would be less counts, but also less synthetic, duplicative rows" }, { "code": null, "e": 15594, "s": 15424, "text": "As I crawled out of the ML cave, I wondered if there is a bigger question here in terms of the dataset philosophy itself, and whether this was an ontological limitation." }, { "code": null, "e": 16281, "s": 15594, "text": "Why is it that for a dataset that is so well-manicured and organized, and with no shortage of rows, the relationships found within are strained? One would think that popularity is a lever that artists, labels, management companies, A&R, and Spotify themselves would want to be able to pull up and down. The obvious answer is that there are thousands of other variables that add to the noise. And, perhaps selecting popularity as the dependent variable in my project meant I was destined for disappointment, in that it highlighted how narrow the independent variables I was given to work with are, and also how little we truly know about the Spotify algorithm that computes ‘popularity’." }, { "code": null, "e": 16799, "s": 16281, "text": "This dataset and its Web API parent is descriptive, not predictive, in nature. ‘good 4 u’ by Olivia Rodrigo isn’t popular because it’s loudness, energy, and instrumentalness scores are high (even though they probably are, but that song wasn’t in this somewhat outdated dataset unfortunately). It’s popular because of who Olivia is, her blend of nostalgic old (hi @ Paramore) with sparkly new, and the buildup of anticipation for anything by Olivia after ‘drivers license’. Where were these parameters in our dataset?!" }, { "code": null, "e": 16946, "s": 16799, "text": "Given the state of modern music and how it’s consumed, it would be prudent to study variables such as, and we’re just scratching the surface here:" }, { "code": null, "e": 16969, "s": 16946, "text": "Social media following" }, { "code": null, "e": 17038, "s": 16969, "text": "Whether an artist is signed to a record label, and if so, which one?" }, { "code": null, "e": 17120, "s": 17038, "text": "A metric to represent an artists’ network value (A “Who do you know here?” score)" }, { "code": null, "e": 17140, "s": 17120, "text": "A “nostalgia” score" }, { "code": null, "e": 17172, "s": 17140, "text": "Historical data for that artist" }, { "code": null, "e": 17241, "s": 17172, "text": "We could also look to break down “popularity” into subsets based on:" }, { "code": null, "e": 17248, "s": 17241, "text": "region" }, { "code": null, "e": 17261, "s": 17248, "text": "demographics" }, { "code": null, "e": 17293, "s": 17261, "text": "which device is it streaming on" }, { "code": null, "e": 17327, "s": 17293, "text": "number of shared Spotify accounts" }, { "code": null, "e": 17352, "s": 17327, "text": "...and many more slices." }, { "code": null, "e": 17510, "s": 17352, "text": "With just these new features added to our dataframe, it would be interesting to see if there is an improvement in our model accuracy, and if so, by how much." }, { "code": null, "e": 17829, "s": 17510, "text": "And yet, like all guardians of a galaxy, Spotify prudently keeps this type of data hidden. Whether for reasons involving PII, or stakeholder contracts and master service agreements, or anything else beyond our purview, those accessing Spotify data via the API are ultimately accessing just the tip of the data iceberg." }, { "code": null, "e": 18062, "s": 17829, "text": "Obviously, the world of data science and AI extends far, far beyond what was was tried here. Moving forward, I’d love to dig into unsupervised learning and deep learning techniques to see what delights we can find along those paths." }, { "code": null, "e": 18394, "s": 18062, "text": "All in all, I’m really excited to see the music analytics vertical grow. Coming out of this project, I have a renewed sense of hope that even in our algorithmic, seemingly monolithic streaming world, we can still have wild, silky, colorful, complicated, emotional auditory outliers that punch us in the gut and wake us the f*** up." }, { "code": null, "e": 18712, "s": 18394, "text": "Thanks for reading all the way until the end (hell, I barely made it to the end writing this). I’m personally still making sense of all this newness, and would love to hear your thoughts on my thoughts, whether you’re a data scientist, a musician, a Spotify enthusiast, a fan of cultural insights, or anything at all." }, { "code": null, "e": 18730, "s": 18712, "text": "Until next time 🎶" } ]
Reverse an array upto a given position - GeeksforGeeks
20 Apr, 2021 Given an array arr[] and a position in array, k. Write a function name reverse (a[], k) such that it reverses subarray arr[0..k-1]. Extra space used should be O(1) and time complexity should be O(k). Example: Input: arr[] = {1, 2, 3, 4, 5, 6} k = 4 Output: arr[] = {4, 3, 2, 1, 5, 6} We strongly recommend you to minimize your browser and try this yourself first.Below is the implementation for the same. C++ Java Python3 C# Javascript // C++ program to reverse a subarray arr[0..k-1]#include <bits/stdc++.h>using namespace std; // Reverse subarray a[0..k-1]void reverse(int a[], int n, int k){ if (k > n) { cout << "Invalid k"; return; } // One by one reverse first and last elements of a[0..k-1] for (int i = 0; i < k/2; i++) swap(a[i], a[k-i-1]);} // Driver programint main(){ int a[] = {1, 2, 3, 4, 5, 6}; int n = sizeof(a) / sizeof(int), k = 4; reverse(a, n, k); for (int i = 0; i < n; ++i) printf("%d ", a[i]); return 0;} // java program to reverse a// subarray arr[0..k-1] public class GFG { // Reverse subarray a[0..k-1] static void reverse(int []a, int n, int k) { if (k > n) { System.out.println( "Invalid k"); return; } // One by one reverse first // and last elements of a[0..k-1] for (int i = 0; i < k / 2; i++) { int tempswap = a[i]; a[i] = a[k - i - 1]; a[k - i - 1] = tempswap; } } // Driver code public static void main(String args[]) { int []a = {1, 2, 3, 4, 5, 6}; int n = a.length, k = 4; reverse(a, n, k); for (int i = 0; i < n; ++i) System.out.print(a[i] + " "); }} // This code is contributed by Sam007. # python program to reverse a subarray# arr[0..k-1]from __future__ import print_function # Reverse subarray a[0..k-1]def reverse(a, n, k): if (k > n): print( "Invalid k") return # One by one reverse first and # last elements of a[0..k-1] for i in range(0, (int)(k/2)): temp = a[i] a[i] = a[k-i-1] a[k-i-1] = temp # Driver programa = [1, 2, 3, 4, 5, 6]n = len(a)k = 4 reverse(a, n, k); for i in range(0, n): print(a[i], end=" ") # This code is contributed by Sam007. // C# program to reverse a// subarray arr[0..k-1]using System; class GFG { static void SwapNum(ref int x, ref int y){ int tempswap = x; x = y; y = tempswap; } // Reverse subarray a[0..k-1]static void reverse(int []a, int n, int k){ if (k > n) { Console.Write( "Invalid k"); return; } // One by one reverse first // and last elements of a[0..k-1] for (int i = 0; i < k / 2; i++) SwapNum(ref a[i], ref a[k - i - 1]); } // Driver Codepublic static void Main(){ int []a = {1, 2, 3, 4, 5, 6}; int n = a.Length, k = 4; reverse(a, n, k); for (int i = 0; i < n; ++i) Console.Write(a[i] + " ");}} // This code is contributed by Sam007 <script> // Javascript program to reverse// a subarray arr[0..k-1] // Reverse subarray a[0..k-1]function reverse( a, n, k){ if (k > n) { document.write("Invalid k"); return; } // One by one reverse first // and last elements of a[0..k-1] for (let i = 0; i < Math.floor(k/2); i++) { let temp = a[i] ; a[i] = a[k-i-1] ; a[k-i-1] = temp ; } } // driver code let a = [1, 2, 3, 4, 5, 6]; let n = a.length, k = 4; reverse(a, n, k); for (let i = 0; i < n; ++i) document.write(a[i] + " "); </script> Output: 4 3 2 1 5 6 Time complexity: O(k)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sam007 nidhi_biet jana_sayantan Amazon Reverse Arrays C++ Amazon Arrays Reverse CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Arrays Multidimensional Arrays in Java Linked List vs Array Python | Using 2D arrays/lists the right way Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) std::sort() in C++ STL
[ { "code": null, "e": 24387, "s": 24359, "text": "\n20 Apr, 2021" }, { "code": null, "e": 24597, "s": 24387, "text": "Given an array arr[] and a position in array, k. Write a function name reverse (a[], k) such that it reverses subarray arr[0..k-1]. Extra space used should be O(1) and time complexity should be O(k). Example: " }, { "code": null, "e": 24678, "s": 24597, "text": "Input:\narr[] = {1, 2, 3, 4, 5, 6}\n k = 4\n\nOutput:\narr[] = {4, 3, 2, 1, 5, 6} " }, { "code": null, "e": 24801, "s": 24678, "text": "We strongly recommend you to minimize your browser and try this yourself first.Below is the implementation for the same. " }, { "code": null, "e": 24805, "s": 24801, "text": "C++" }, { "code": null, "e": 24810, "s": 24805, "text": "Java" }, { "code": null, "e": 24818, "s": 24810, "text": "Python3" }, { "code": null, "e": 24821, "s": 24818, "text": "C#" }, { "code": null, "e": 24832, "s": 24821, "text": "Javascript" }, { "code": "// C++ program to reverse a subarray arr[0..k-1]#include <bits/stdc++.h>using namespace std; // Reverse subarray a[0..k-1]void reverse(int a[], int n, int k){ if (k > n) { cout << \"Invalid k\"; return; } // One by one reverse first and last elements of a[0..k-1] for (int i = 0; i < k/2; i++) swap(a[i], a[k-i-1]);} // Driver programint main(){ int a[] = {1, 2, 3, 4, 5, 6}; int n = sizeof(a) / sizeof(int), k = 4; reverse(a, n, k); for (int i = 0; i < n; ++i) printf(\"%d \", a[i]); return 0;}", "e": 25386, "s": 24832, "text": null }, { "code": "// java program to reverse a// subarray arr[0..k-1] public class GFG { // Reverse subarray a[0..k-1] static void reverse(int []a, int n, int k) { if (k > n) { System.out.println( \"Invalid k\"); return; } // One by one reverse first // and last elements of a[0..k-1] for (int i = 0; i < k / 2; i++) { int tempswap = a[i]; a[i] = a[k - i - 1]; a[k - i - 1] = tempswap; } } // Driver code public static void main(String args[]) { int []a = {1, 2, 3, 4, 5, 6}; int n = a.length, k = 4; reverse(a, n, k); for (int i = 0; i < n; ++i) System.out.print(a[i] + \" \"); }} // This code is contributed by Sam007.", "e": 26186, "s": 25386, "text": null }, { "code": "# python program to reverse a subarray# arr[0..k-1]from __future__ import print_function # Reverse subarray a[0..k-1]def reverse(a, n, k): if (k > n): print( \"Invalid k\") return # One by one reverse first and # last elements of a[0..k-1] for i in range(0, (int)(k/2)): temp = a[i] a[i] = a[k-i-1] a[k-i-1] = temp # Driver programa = [1, 2, 3, 4, 5, 6]n = len(a)k = 4 reverse(a, n, k); for i in range(0, n): print(a[i], end=\" \") # This code is contributed by Sam007.", "e": 26724, "s": 26186, "text": null }, { "code": "// C# program to reverse a// subarray arr[0..k-1]using System; class GFG { static void SwapNum(ref int x, ref int y){ int tempswap = x; x = y; y = tempswap; } // Reverse subarray a[0..k-1]static void reverse(int []a, int n, int k){ if (k > n) { Console.Write( \"Invalid k\"); return; } // One by one reverse first // and last elements of a[0..k-1] for (int i = 0; i < k / 2; i++) SwapNum(ref a[i], ref a[k - i - 1]); } // Driver Codepublic static void Main(){ int []a = {1, 2, 3, 4, 5, 6}; int n = a.Length, k = 4; reverse(a, n, k); for (int i = 0; i < n; ++i) Console.Write(a[i] + \" \");}} // This code is contributed by Sam007", "e": 27475, "s": 26724, "text": null }, { "code": "<script> // Javascript program to reverse// a subarray arr[0..k-1] // Reverse subarray a[0..k-1]function reverse( a, n, k){ if (k > n) { document.write(\"Invalid k\"); return; } // One by one reverse first // and last elements of a[0..k-1] for (let i = 0; i < Math.floor(k/2); i++) { let temp = a[i] ; a[i] = a[k-i-1] ; a[k-i-1] = temp ; } } // driver code let a = [1, 2, 3, 4, 5, 6]; let n = a.length, k = 4; reverse(a, n, k); for (let i = 0; i < n; ++i) document.write(a[i] + \" \"); </script>", "e": 28054, "s": 27475, "text": null }, { "code": null, "e": 28063, "s": 28054, "text": "Output: " }, { "code": null, "e": 28075, "s": 28063, "text": "4 3 2 1 5 6" }, { "code": null, "e": 28221, "s": 28075, "text": "Time complexity: O(k)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 28228, "s": 28221, "text": "Sam007" }, { "code": null, "e": 28239, "s": 28228, "text": "nidhi_biet" }, { "code": null, "e": 28253, "s": 28239, "text": "jana_sayantan" }, { "code": null, "e": 28260, "s": 28253, "text": "Amazon" }, { "code": null, "e": 28268, "s": 28260, "text": "Reverse" }, { "code": null, "e": 28275, "s": 28268, "text": "Arrays" }, { "code": null, "e": 28279, "s": 28275, "text": "C++" }, { "code": null, "e": 28286, "s": 28279, "text": "Amazon" }, { "code": null, "e": 28293, "s": 28286, "text": "Arrays" }, { "code": null, "e": 28301, "s": 28293, "text": "Reverse" }, { "code": null, "e": 28305, "s": 28301, "text": "CPP" }, { "code": null, "e": 28403, "s": 28305, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28412, "s": 28403, "text": "Comments" }, { "code": null, "e": 28425, "s": 28412, "text": "Old Comments" }, { "code": null, "e": 28448, "s": 28425, "text": "Introduction to Arrays" }, { "code": null, "e": 28480, "s": 28448, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28501, "s": 28480, "text": "Linked List vs Array" }, { "code": null, "e": 28546, "s": 28501, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 28631, "s": 28546, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 28649, "s": 28631, "text": "Vector in C++ STL" }, { "code": null, "e": 28695, "s": 28649, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 28714, "s": 28695, "text": "Inheritance in C++" }, { "code": null, "e": 28757, "s": 28714, "text": "Map in C++ Standard Template Library (STL)" } ]
How to find the sequence of correlation between variables in an R data frame or matrix?
To find the sequence of correlation between variables in an R data frame or matrix, we can use correlate and stretch function from corrr package. For example, if we have a data frame called df then we can find the sequence of correlation between variables in df by using the below given command − df%>% correlate() %>% stretch() %>% arrange(r) Following snippet creates a sample data frame − x1<-rnorm(20) x2<-rnorm(20,5,0.2) x3<-rnorm(20,5,0.005) x4<-rnorm(20,2,0.14) df1<-data.frame(x1,x2,x3,x4) df1 The following dataframe is created − x1 x2 x3 x4 1 0.6808273 5.100547 5.008409 1.903267 2 -0.8982181 5.236966 5.003451 1.885443 3 1.7004141 4.938643 4.998515 2.078969 4 -0.5556164 5.086777 5.000830 1.836611 5 -0.3700080 5.180180 4.999621 2.066981 6 -0.6171065 5.218265 5.006482 2.012696 7 1.3167304 4.886068 5.005309 1.697461 8 -1.0291898 5.082370 4.996527 1.876241 9 0.3552824 5.354599 5.004550 2.010306 10 -0.8318924 4.943031 4.999007 2.097666 11 -0.3643198 5.287603 4.996394 2.119303 12 -0.6422962 4.864442 4.998594 2.105324 13 3.3631619 4.675183 4.999328 1.878981 14 1.7794186 4.769273 4.997484 2.027005 15 -0.5102582 5.140516 5.001077 1.830695 16 1.1652416 4.586822 4.996408 2.101790 17 -0.4535449 5.046426 5.004014 1.906526 18 -2.0166857 4.666686 4.996425 2.011478 19 -0.9543124 4.956333 5.002519 1.984997 20 1.5101443 5.273918 4.988374 1.876615 To load corrr package and find the sequence of correlation between variables in df1, add the following code to the above snippet − library(corrr) df1%>% + correlate() %>% + stretch() %>% + arrange(r) Correlation method: 'pearson' Missing treated using: 'pairwise.complete.obs' # A tibble: 16 x 3 If you execute all the above given snippets as a single program, it generates the following output − x y r <chr> <chr> <dbl> 1 x1 x2 -0.284 2 x2 x1 -0.284 3 x3 x4 -0.263 4 x4 x3 -0.263 5 x1 x4 -0.155 6 x4 x1 -0.155 7 x1 x3 -0.137 8 x3 x1 -0.137 9 x2 x4 -0.127 10 x4 x2 -0.127 11 x2 x3 0.185 12 x3 x2 0.185 13 x1 x1 NA 14 x2 x2 NA 15 x3 x3 NA 16 x4 x4 NA Following snippet creates a matrix − M1<-matrix(rpois(100,10),ncol=5) M1 The following matrix is created − [,1][,2][,3][,4][,5] [1,] 10 4 13 4 9 [2,] 14 12 13 15 11 [3,] 11 6 15 10 16 [4,] 6 10 5 9 9 [5,] 9 6 20 10 10 [6,] 7 10 6 10 12 [7,] 13 15 6 13 8 [8,] 3 14 11 9 8 [9,] 13 10 7 9 11 [10,] 10 7 16 13 12 [11,] 8 7 9 7 14 [12,] 7 6 9 16 6 [13,] 7 14 7 7 12 [14,] 8 7 7 5 10 [15,] 4 9 13 11 7 [16,] 15 9 14 11 8 [17,] 9 12 7 9 15 [18,] 11 10 3 14 10 [19,] 8 5 13 17 11 [20,] 7 13 10 12 7 To find the sequence of correlation between variables in M1, add the following code to the above snippet − M1%>% + correlate()%>% + stretch() %>% + arrange(r) Correlation method: 'pearson' Missing treated using: 'pairwise.complete.obs' # A tibble: 25 x 3 If you execute all the above given snippets as a single program, it generates the following output − x y r <chr> <chr> <dbl> 1 V2 V3 -0.473 2 V3 V2 -0.473 3 V4 V5 -0.233 4 V5 V4 -0.233 5 V2 V5 -0.136 6 V5 V2 -0.136 7 V1 V2 -0.0355 8 V2 V1 -0.0355 9 V3 V5 0.0261 10 V5 V3 0.0261
[ { "code": null, "e": 1208, "s": 1062, "text": "To find the sequence of correlation between variables in an R data frame or matrix, we can use correlate and stretch function from corrr package." }, { "code": null, "e": 1359, "s": 1208, "text": "For example, if we have a data frame called df then we can find the sequence of correlation between variables in df by using the below given command −" }, { "code": null, "e": 1406, "s": 1359, "text": "df%>%\ncorrelate() %>%\nstretch() %>%\narrange(r)" }, { "code": null, "e": 1454, "s": 1406, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 1564, "s": 1454, "text": "x1<-rnorm(20)\nx2<-rnorm(20,5,0.2)\nx3<-rnorm(20,5,0.005)\nx4<-rnorm(20,2,0.14)\ndf1<-data.frame(x1,x2,x3,x4)\ndf1" }, { "code": null, "e": 1601, "s": 1564, "text": "The following dataframe is created −" }, { "code": null, "e": 2479, "s": 1601, "text": " x1 x2 x3 x4\n1 0.6808273 5.100547 5.008409 1.903267\n2 -0.8982181 5.236966 5.003451 1.885443\n3 1.7004141 4.938643 4.998515 2.078969\n4 -0.5556164 5.086777 5.000830 1.836611\n5 -0.3700080 5.180180 4.999621 2.066981\n6 -0.6171065 5.218265 5.006482 2.012696\n7 1.3167304 4.886068 5.005309 1.697461\n8 -1.0291898 5.082370 4.996527 1.876241\n9 0.3552824 5.354599 5.004550 2.010306\n10 -0.8318924 4.943031 4.999007 2.097666\n11 -0.3643198 5.287603 4.996394 2.119303\n12 -0.6422962 4.864442 4.998594 2.105324\n13 3.3631619 4.675183 4.999328 1.878981\n14 1.7794186 4.769273 4.997484 2.027005\n15 -0.5102582 5.140516 5.001077 1.830695\n16 1.1652416 4.586822 4.996408 2.101790\n17 -0.4535449 5.046426 5.004014 1.906526\n18 -2.0166857 4.666686 4.996425 2.011478\n19 -0.9543124 4.956333 5.002519 1.984997\n20 1.5101443 5.273918 4.988374 1.876615" }, { "code": null, "e": 2610, "s": 2479, "text": "To load corrr package and find the sequence of correlation between variables in df1, add the following code to the above snippet −" }, { "code": null, "e": 2777, "s": 2610, "text": "library(corrr)\ndf1%>%\n+ correlate() %>%\n+ stretch() %>%\n+ arrange(r)\n\nCorrelation method: 'pearson'\nMissing treated using: 'pairwise.complete.obs'\n\n# A tibble: 16 x 3" }, { "code": null, "e": 2878, "s": 2777, "text": "If you execute all the above given snippets as a single program, it generates the following output −" }, { "code": null, "e": 3206, "s": 2878, "text": " x y r\n <chr> <chr> <dbl>\n1 x1 x2 -0.284\n2 x2 x1 -0.284\n3 x3 x4 -0.263\n4 x4 x3 -0.263\n5 x1 x4 -0.155\n6 x4 x1 -0.155\n7 x1 x3 -0.137\n8 x3 x1 -0.137\n9 x2 x4 -0.127\n10 x4 x2 -0.127\n11 x2 x3 0.185\n12 x3 x2 0.185\n13 x1 x1 NA\n14 x2 x2 NA\n15 x3 x3 NA\n16 x4 x4 NA" }, { "code": null, "e": 3243, "s": 3206, "text": "Following snippet creates a matrix −" }, { "code": null, "e": 3279, "s": 3243, "text": "M1<-matrix(rpois(100,10),ncol=5)\nM1" }, { "code": null, "e": 3313, "s": 3279, "text": "The following matrix is created −" }, { "code": null, "e": 3860, "s": 3313, "text": " [,1][,2][,3][,4][,5]\n[1,] 10 4 13 4 9\n[2,] 14 12 13 15 11\n[3,] 11 6 15 10 16\n[4,] 6 10 5 9 9\n[5,] 9 6 20 10 10\n[6,] 7 10 6 10 12\n[7,] 13 15 6 13 8\n[8,] 3 14 11 9 8\n[9,] 13 10 7 9 11\n[10,] 10 7 16 13 12\n[11,] 8 7 9 7 14\n[12,] 7 6 9 16 6\n[13,] 7 14 7 7 12\n[14,] 8 7 7 5 10\n[15,] 4 9 13 11 7\n[16,] 15 9 14 11 8\n[17,] 9 12 7 9 15\n[18,] 11 10 3 14 10\n[19,] 8 5 13 17 11\n[20,] 7 13 10 12 7" }, { "code": null, "e": 3967, "s": 3860, "text": "To find the sequence of correlation between variables in M1, add the following code to the above snippet −" }, { "code": null, "e": 4117, "s": 3967, "text": "M1%>%\n+ correlate()%>%\n+ stretch() %>%\n+ arrange(r)\n\nCorrelation method: 'pearson'\nMissing treated using: 'pairwise.complete.obs'\n\n# A tibble: 25 x 3" }, { "code": null, "e": 4218, "s": 4117, "text": "If you execute all the above given snippets as a single program, it generates the following output −" }, { "code": null, "e": 4438, "s": 4218, "text": " x y r\n <chr> <chr> <dbl>\n1 V2 V3 -0.473\n2 V3 V2 -0.473\n3 V4 V5 -0.233\n4 V5 V4 -0.233\n5 V2 V5 -0.136\n6 V5 V2 -0.136\n7 V1 V2 -0.0355\n8 V2 V1 -0.0355\n9 V3 V5 0.0261\n10 V5 V3 0.0261" } ]
Lucky Numbers
Lucky numbers are some special integer numbers. From basic numbers, some special numbers are eliminated by their position. Instead of their value, for their position, the numbers are eliminated. The numbers which are not deleted, they are the lucky numbers. The number deletion follows some rule. At first, every second number are deleted, after that, all 3rd numbers are deleted and so on. Here is some example − 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 (1 – 25 all) 1 3 5 7 9 11 13 15 17 19 21 23 25 (deleting all 2nd numbers) 1 3 7 9 13 15 19 21 25 (All 3rd numbers are deleted, starting from 5) 1 3 7 9 13 15 21 25 (All 7th numbers are deleted starting from 19) Input: Put a number to check whether it is lucky or not. Let the number is 13 Output: 13 is a lucky number. isLuckyNumber(number) Input − A number. Output − Check the number is lucky or not. Begin counter := 2 (It is static data, not be initialized again in recursion call) if counter > n, then return 1 if n mod counter = 0, then return 0 n := n – (n / counter) counter := counter + 1 isLuckyNumber(n) End #include <iostream> using namespace std; int counter = 2; //used during recursion bool isLuckyNumber(int n) { if(counter > n) return 1; if(n%counter == 0) return 0; n -= n/counter; //n will be next position for recursion counter++; return isLuckyNumber(n); } int main() { int x = 13; if(isLuckyNumber(x)) cout << x<<" is a lucky number."; else cout << x<<" is not a lucky number."; } 13 is a lucky number.
[ { "code": null, "e": 1320, "s": 1062, "text": "Lucky numbers are some special integer numbers. From basic numbers, some special numbers are eliminated by their position. Instead of their value, for their position, the numbers are eliminated. The numbers which are not deleted, they are the lucky numbers." }, { "code": null, "e": 1453, "s": 1320, "text": "The number deletion follows some rule. At first, every second number are deleted, after that, all 3rd numbers are deleted and so on." }, { "code": null, "e": 1476, "s": 1453, "text": "Here is some example −" }, { "code": null, "e": 1753, "s": 1476, "text": "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 (1 – 25 all)\n1 3 5 7 9 11 13 15 17 19 21 23 25 (deleting all 2nd numbers)\n1 3 7 9 13 15 19 21 25 (All 3rd numbers are deleted, starting from 5)\n1 3 7 9 13 15 21 25 (All 7th numbers are deleted starting from 19)" }, { "code": null, "e": 1861, "s": 1753, "text": "Input: Put a number to check whether it is lucky or not. Let the number is 13 Output: 13 is a lucky number." }, { "code": null, "e": 1883, "s": 1861, "text": "isLuckyNumber(number)" }, { "code": null, "e": 1901, "s": 1883, "text": "Input − A number." }, { "code": null, "e": 1944, "s": 1901, "text": "Output − Check the number is lucky or not." }, { "code": null, "e": 2190, "s": 1944, "text": "Begin\n counter := 2 (It is static data, not be initialized again in recursion call)\n if counter > n, then\n return 1\n if n mod counter = 0, then\n return 0\n n := n – (n / counter)\n counter := counter + 1\n isLuckyNumber(n)\nEnd" }, { "code": null, "e": 2636, "s": 2190, "text": "#include <iostream>\nusing namespace std;\n\nint counter = 2; //used during recursion\n\nbool isLuckyNumber(int n) {\n if(counter > n)\n return 1;\n if(n%counter == 0)\n return 0;\n \n n -= n/counter; //n will be next position for recursion\n counter++;\n return isLuckyNumber(n);\n}\n\nint main() {\n int x = 13;\n\n if(isLuckyNumber(x))\n cout << x<<\" is a lucky number.\";\n else\n cout << x<<\" is not a lucky number.\";\n}" }, { "code": null, "e": 2658, "s": 2636, "text": "13 is a lucky number." } ]
Create a MySQL stored procedure that generates five random numbers?
With the help of the following query we can create a stored procedure to generate five random numbers − mysql> DELIMITER // mysql> DROP PROCEDURE IF EXISTS RandomNumbers; -> CREATE PROCEDURE RandomNumbers() -> BEGIN -> SET @i = 0; -> REPEAT -> SELECT RAND() AS 'Random Number'; -> SET @i = @i + 1; -> UNTIL @i >=5 END REPEAT; -> END -> // Query OK, 0 rows affected (0.16 sec) Query OK, 0 rows affected (0.16 sec) Now, invoke the procedure to get the result − mysql> DELIMITER ; mysql> CALL RandomNumbers(); +---------------------+ | Random Number | +---------------------+ | 0.25968261739209536 | +---------------------+ 1 row in set (0.00 sec) +--------------------+ | Random Number | +--------------------+ | 0.1659662734400167 | +--------------------+ 1 row in set (0.01 sec) +---------------------+ | Random Number | +---------------------+ | 0.05078354575744229 | +---------------------+ 1 row in set (0.01 sec) +--------------------+ | Random Number | +--------------------+ | 0.7560189392008064 | +--------------------+ 1 row in set (0.04 sec) +------------------+ | Random Number | +------------------+ | 0.62774408946535 | +------------------+ 1 row in set (0.04 sec) Query OK, 0 rows affected (0.05 sec)
[ { "code": null, "e": 1166, "s": 1062, "text": "With the help of the following query we can create a stored procedure to generate five random numbers −" }, { "code": null, "e": 1512, "s": 1166, "text": "mysql> DELIMITER //\nmysql> DROP PROCEDURE IF EXISTS RandomNumbers;\n -> CREATE PROCEDURE RandomNumbers()\n -> BEGIN\n -> SET @i = 0;\n -> REPEAT\n -> SELECT RAND() AS 'Random Number';\n -> SET @i = @i + 1;\n -> UNTIL @i >=5 END REPEAT;\n -> END\n -> //\nQuery OK, 0 rows affected (0.16 sec)\n\nQuery OK, 0 rows affected (0.16 sec)" }, { "code": null, "e": 1558, "s": 1512, "text": "Now, invoke the procedure to get the result −" }, { "code": null, "e": 2338, "s": 1558, "text": "mysql> DELIMITER ;\nmysql> CALL RandomNumbers();\n+---------------------+\n| Random Number |\n+---------------------+\n| 0.25968261739209536 |\n+---------------------+\n1 row in set (0.00 sec)\n\n+--------------------+\n| Random Number |\n+--------------------+\n| 0.1659662734400167 |\n+--------------------+\n1 row in set (0.01 sec)\n\n+---------------------+\n| Random Number |\n+---------------------+\n| 0.05078354575744229 |\n+---------------------+\n1 row in set (0.01 sec)\n\n+--------------------+\n| Random Number |\n+--------------------+\n| 0.7560189392008064 |\n+--------------------+\n1 row in set (0.04 sec)\n\n+------------------+\n| Random Number |\n+------------------+\n| 0.62774408946535 |\n+------------------+\n1 row in set (0.04 sec)\n\nQuery OK, 0 rows affected (0.05 sec)" } ]
C program to interchange the diagonal elements in given matrix
We need to write a code to interchange the main diagonal elements with the secondary diagonal elements. The size of the matrix is given at runtime. If the size of matrix m and n values are not equal, then it prints that the given matrix is not a square. Only a square matrix can interchange the main diagonal elements and can interchange with the secondary diagonal elements. The solution to write a C program to interchange the diagonal elements in given matrix is as follows − The logic to interchange the diagonal elements is explained below − for (i=0;i<m;++i){ a = ma[i][i]; ma[i][i] = ma[i][m-i-1]; ma[i][m-i-1] = a; } Following is the C program to interchange the diagonal elements in given matrix − Live Demo #include<stdio.h> main (){ int i,j,m,n,a; static int ma[10][10]; printf ("Enter the order of the matrix m and n\n"); scanf ("%dx%d",&m,&n); if (m==n){ printf ("Enter the co-efficients of the matrix\n"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ scanf ("%d",&ma[i][j]); } } printf ("The given matrix is \n"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ printf (" %d",ma[i][j]); } printf ("\n"); } for (i=0;i<m;++i){ a = ma[i][i]; ma[i][i] = ma[i][m-i-1]; ma[i][m-i-1] = a; } printf ("Matrix after changing the \n"); printf ("Main & secondary diagonal\n"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ printf (" %d",ma[i][j]); } printf ("\n"); } } else printf ("The given order is not square matrix\n"); } When the above program is executed, it produces the following result − Run 1: Enter the order of the matrix m and n 3x3 Enter the co-efficient of the matrix 1 2 3 4 5 6 7 8 9 The given matrix is 1 2 3 4 5 6 7 8 9 Matrix after changing the Main & secondary diagonal 3 2 1 4 5 6 9 8 7 Run 2: Enter the order of the matrix m and n 4x3 The given order is not square matrix
[ { "code": null, "e": 1210, "s": 1062, "text": "We need to write a code to interchange the main diagonal elements with the secondary diagonal elements. The size of the matrix is given at runtime." }, { "code": null, "e": 1316, "s": 1210, "text": "If the size of matrix m and n values are not equal, then it prints that the given matrix is not a square." }, { "code": null, "e": 1438, "s": 1316, "text": "Only a square matrix can interchange the main diagonal elements and can interchange with the secondary diagonal elements." }, { "code": null, "e": 1541, "s": 1438, "text": "The solution to write a C program to interchange the diagonal elements in given matrix is as follows −" }, { "code": null, "e": 1609, "s": 1541, "text": "The logic to interchange the diagonal elements is explained below −" }, { "code": null, "e": 1696, "s": 1609, "text": "for (i=0;i<m;++i){\n a = ma[i][i];\n ma[i][i] = ma[i][m-i-1];\n ma[i][m-i-1] = a;\n}" }, { "code": null, "e": 1778, "s": 1696, "text": "Following is the C program to interchange the diagonal elements in given matrix −" }, { "code": null, "e": 1789, "s": 1778, "text": " Live Demo" }, { "code": null, "e": 2710, "s": 1789, "text": "#include<stdio.h>\nmain (){\n int i,j,m,n,a;\n static int ma[10][10];\n printf (\"Enter the order of the matrix m and n\\n\");\n scanf (\"%dx%d\",&m,&n);\n if (m==n){\n printf (\"Enter the co-efficients of the matrix\\n\");\n for (i=0;i<m;++i){\n for (j=0;j<n;++j){\n scanf (\"%d\",&ma[i][j]);\n }\n }\n printf (\"The given matrix is \\n\");\n for (i=0;i<m;++i){\n for (j=0;j<n;++j){\n printf (\" %d\",ma[i][j]);\n }\n printf (\"\\n\");\n }\n for (i=0;i<m;++i){\n a = ma[i][i];\n ma[i][i] = ma[i][m-i-1];\n ma[i][m-i-1] = a;\n }\n printf (\"Matrix after changing the \\n\");\n printf (\"Main & secondary diagonal\\n\");\n for (i=0;i<m;++i){\n for (j=0;j<n;++j){\n printf (\" %d\",ma[i][j]);\n }\n printf (\"\\n\");\n }\n }\n else\n printf (\"The given order is not square matrix\\n\");\n}" }, { "code": null, "e": 2781, "s": 2710, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3080, "s": 2781, "text": "Run 1:\nEnter the order of the matrix m and n\n3x3\nEnter the co-efficient of the matrix\n1\n2\n3\n4\n5\n6\n7\n8\n9\nThe given matrix is\n1 2 3\n4 5 6\n7 8 9\nMatrix after changing the\nMain & secondary diagonal\n3 2 1\n4 5 6\n9 8 7\n\nRun 2:\nEnter the order of the matrix m and n\n4x3\nThe given order is not square matrix" } ]
Python - Filtering data with Pandas .query() method
Pandas is a very widely used python library for data cleansing, data analysis etc. In this article we will see how we can use the query method to fetch specific data from a given data set. We can have both single and multiple conditions inside a query. Let’s first read the data into a pandas data frame using the pandas library. The below program just does that. import pandas as pd # Reading data frame from csv file data = pd.read_csv("D:\\heart.csv") print(data) Running the above code gives us the following result − Next we see how we can use the query method with single condition. As you can see only 119 rows from the original 303 rows are returned as a result. import pandas as pd # Data frame from csv file data = pd.read_csv("D:\\heart.csv") data.query('chol < 230', inplace=True) # Result print(data) Running the above code gives us the following result − In a similar approach as above we can apply multiple conditions to the query method. This will restrict the result data set further. Only 79 rows are returned now when we also restrict the age to greater than 60. import pandas as pd # Data frame from csv file data = pd.read_csv("D:\\heart.csv") data.query('chol < 230' and 'age > 60', inplace=True) # Result print(data) Running the above code gives us the following result −
[ { "code": null, "e": 1315, "s": 1062, "text": "Pandas is a very widely used python library for data cleansing, data analysis etc. In this article we will see how we can use the query method to fetch specific data from a given data set. We can have both single and multiple conditions inside a query." }, { "code": null, "e": 1426, "s": 1315, "text": "Let’s first read the data into a pandas data frame using the pandas library. The below program just does that." }, { "code": null, "e": 1531, "s": 1426, "text": "import pandas as pd\n\n# Reading data frame from csv file\ndata = pd.read_csv(\"D:\\\\heart.csv\")\n\nprint(data)" }, { "code": null, "e": 1586, "s": 1531, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1735, "s": 1586, "text": "Next we see how we can use the query method with single condition. As you can see only 119 rows from the original 303 rows are returned as a result." }, { "code": null, "e": 1881, "s": 1735, "text": "import pandas as pd\n\n# Data frame from csv file\ndata = pd.read_csv(\"D:\\\\heart.csv\")\n\ndata.query('chol < 230', inplace=True)\n\n# Result\nprint(data)" }, { "code": null, "e": 1936, "s": 1881, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2149, "s": 1936, "text": "In a similar approach as above we can apply multiple conditions to the query method. This will restrict the result data set further. Only 79 rows are returned now when we also restrict the age to greater than 60." }, { "code": null, "e": 2310, "s": 2149, "text": "import pandas as pd\n\n# Data frame from csv file\ndata = pd.read_csv(\"D:\\\\heart.csv\")\n\ndata.query('chol < 230' and 'age > 60', inplace=True)\n\n# Result\nprint(data)" }, { "code": null, "e": 2365, "s": 2310, "text": "Running the above code gives us the following result −" } ]
Take and convert Screenshot to PDF using Python - GeeksforGeeks
11 Jan, 2022 In order to take and convert a screenshot to PDF, firstly the PyAutoGUI can be used which is an automation library in python which can control mouse, keyboard and can handle many GUI control tasks. Secondly, for the conversion PIL(Python Imaging Library) of python can be used which provides image processing facility and it supports many file formats and their conversion. The second library which can be used for conversion is img2pdf which provides as the name suggests the lossless and faster conversion of image to pdf. For installation of the library use the following commands: PyAutoGUI: pip install PyAutoGUI PIL(Python imaging library): pip install Pillow img2pdf pip install img2pdf In this approach, we are using the PIL library of python. First, the screenshot is taken using the screenshot() function of PyAutoGUI library of python. After that, the output of the screenshot is saved. The open() method of PIL library is used to open the image and then convert() method to convert the image to RGB which is then saved with .pdf extension in the given path. Alternatively, you can also provide the screenshot/image by providing the path inside the open() method. Note: The r’ is used so that the string is treated as a raw string. Implementation: Python3 import pyautoguifrom PIL import Image # Taking ScreenshottakeScreenshot = pyautogui.screenshot() # The path of Screenshot and r' is used for specifying raw stringscreenshotPath = r'C:\Users\Pranjal\Desktop\gfgarticle\PDF\screenshot.png' # Saving the screenshot in the given PathtakeScreenshot.save(screenshotPath) # Opening imageopen_image = Image.open(screenshotPath)convert_image = open_image.convert('RGB') # Output Pdf PathoutputpdfPath = r'C:\Users\Pranjal\Desktop\gfgarticle\PDF\output.pdf' # Saving the pdfopen_image.save(outputpdfPath) Output: In this approach, the img2pdf library is used for the conversion. Firstly, the screenshot is taken using the screenshot() method of PyAutoGUI library of python. After the screenshot is opened using the open() method and “rb” as a parameter is passed for opening the file in the binary format. After that, the output file which is pdf is opened using open() method bt passing the “wb” parameter (used for writing in binary). The write() function is called and convert() method of img2pdf is passed with screenshot object. At last, both objects are closed so that they flush any unwritten information. The main advantage to the method is that it is fast as compared to PIL and it is also lossless conversion with small size. Alternatively, you can also provide the screenshot/image by providing the path inside the open() method. Note: The screenshot/image does not contain an alpha channel since there is no method available that converts the RGBA to RGB in img2pdf. Implementation: Python3 import pyautoguiimport img2pdf # Taking ScreenshottakeScreenshot = pyautogui.screenshot() # The path of Screenshot and r' is used for specifying raw stringscreenshotPath = r'C:\Users\Pranjal\Desktop\gfgarticle\PDF\screenshot.png' # Saving the screenshot in the given PathtakeScreenshot.save(screenshotPath) # Opening Img file objImgFile = open(screenshotPath, "rb") # Opening the Pdf file objPdfFile = open("output.pdf", "wb") # Converting Image File to PDFPdfFile.write(img2pdf.convert(ImgFile)) # Closing Image File ObjectImgFile.close() # Closing PDF File ObjectPdfFile.close() Output: anikakapoor sweetyty Picked python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n11 Jan, 2022" }, { "code": null, "e": 26173, "s": 25647, "text": "In order to take and convert a screenshot to PDF, firstly the PyAutoGUI can be used which is an automation library in python which can control mouse, keyboard and can handle many GUI control tasks. Secondly, for the conversion PIL(Python Imaging Library) of python can be used which provides image processing facility and it supports many file formats and their conversion. The second library which can be used for conversion is img2pdf which provides as the name suggests the lossless and faster conversion of image to pdf. " }, { "code": null, "e": 26233, "s": 26173, "text": "For installation of the library use the following commands:" }, { "code": null, "e": 26244, "s": 26233, "text": "PyAutoGUI:" }, { "code": null, "e": 26266, "s": 26244, "text": "pip install PyAutoGUI" }, { "code": null, "e": 26295, "s": 26266, "text": "PIL(Python imaging library):" }, { "code": null, "e": 26314, "s": 26295, "text": "pip install Pillow" }, { "code": null, "e": 26322, "s": 26314, "text": "img2pdf" }, { "code": null, "e": 26342, "s": 26322, "text": "pip install img2pdf" }, { "code": null, "e": 26823, "s": 26342, "text": "In this approach, we are using the PIL library of python. First, the screenshot is taken using the screenshot() function of PyAutoGUI library of python. After that, the output of the screenshot is saved. The open() method of PIL library is used to open the image and then convert() method to convert the image to RGB which is then saved with .pdf extension in the given path. Alternatively, you can also provide the screenshot/image by providing the path inside the open() method." }, { "code": null, "e": 26891, "s": 26823, "text": "Note: The r’ is used so that the string is treated as a raw string." }, { "code": null, "e": 26907, "s": 26891, "text": "Implementation:" }, { "code": null, "e": 26915, "s": 26907, "text": "Python3" }, { "code": "import pyautoguifrom PIL import Image # Taking ScreenshottakeScreenshot = pyautogui.screenshot() # The path of Screenshot and r' is used for specifying raw stringscreenshotPath = r'C:\\Users\\Pranjal\\Desktop\\gfgarticle\\PDF\\screenshot.png' # Saving the screenshot in the given PathtakeScreenshot.save(screenshotPath) # Opening imageopen_image = Image.open(screenshotPath)convert_image = open_image.convert('RGB') # Output Pdf PathoutputpdfPath = r'C:\\Users\\Pranjal\\Desktop\\gfgarticle\\PDF\\output.pdf' # Saving the pdfopen_image.save(outputpdfPath)", "e": 27459, "s": 26915, "text": null }, { "code": null, "e": 27467, "s": 27459, "text": "Output:" }, { "code": null, "e": 28067, "s": 27467, "text": "In this approach, the img2pdf library is used for the conversion. Firstly, the screenshot is taken using the screenshot() method of PyAutoGUI library of python. After the screenshot is opened using the open() method and “rb” as a parameter is passed for opening the file in the binary format. After that, the output file which is pdf is opened using open() method bt passing the “wb” parameter (used for writing in binary). The write() function is called and convert() method of img2pdf is passed with screenshot object. At last, both objects are closed so that they flush any unwritten information." }, { "code": null, "e": 28295, "s": 28067, "text": "The main advantage to the method is that it is fast as compared to PIL and it is also lossless conversion with small size. Alternatively, you can also provide the screenshot/image by providing the path inside the open() method." }, { "code": null, "e": 28433, "s": 28295, "text": "Note: The screenshot/image does not contain an alpha channel since there is no method available that converts the RGBA to RGB in img2pdf." }, { "code": null, "e": 28449, "s": 28433, "text": "Implementation:" }, { "code": null, "e": 28457, "s": 28449, "text": "Python3" }, { "code": "import pyautoguiimport img2pdf # Taking ScreenshottakeScreenshot = pyautogui.screenshot() # The path of Screenshot and r' is used for specifying raw stringscreenshotPath = r'C:\\Users\\Pranjal\\Desktop\\gfgarticle\\PDF\\screenshot.png' # Saving the screenshot in the given PathtakeScreenshot.save(screenshotPath) # Opening Img file objImgFile = open(screenshotPath, \"rb\") # Opening the Pdf file objPdfFile = open(\"output.pdf\", \"wb\") # Converting Image File to PDFPdfFile.write(img2pdf.convert(ImgFile)) # Closing Image File ObjectImgFile.close() # Closing PDF File ObjectPdfFile.close()", "e": 29038, "s": 28457, "text": null }, { "code": null, "e": 29046, "s": 29038, "text": "Output:" }, { "code": null, "e": 29058, "s": 29046, "text": "anikakapoor" }, { "code": null, "e": 29067, "s": 29058, "text": "sweetyty" }, { "code": null, "e": 29074, "s": 29067, "text": "Picked" }, { "code": null, "e": 29089, "s": 29074, "text": "python-utility" }, { "code": null, "e": 29096, "s": 29089, "text": "Python" }, { "code": null, "e": 29194, "s": 29096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29226, "s": 29194, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29268, "s": 29226, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29310, "s": 29268, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29366, "s": 29310, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29393, "s": 29366, "text": "Python Classes and Objects" }, { "code": null, "e": 29424, "s": 29393, "text": "Python | os.path.join() method" }, { "code": null, "e": 29453, "s": 29424, "text": "Create a directory in Python" }, { "code": null, "e": 29475, "s": 29453, "text": "Defaultdict in Python" }, { "code": null, "e": 29511, "s": 29475, "text": "Python | Pandas dataframe.groupby()" } ]
Convert A Categorical Variable Into Dummy Variables - GeeksforGeeks
11 Dec, 2020 All the statistical and machine learning models are built on the foundation of data. A grouped or composite entity holding the relevant to a particular problem together is called a data set. These data sets are composed of Independent Variables or the features and the Dependent Variables or the Labels. All of these variables can be classified into two types of data: Quantitative and Categorical. In this article, we are going to deal with the various methods to convert Categorical Variables into Dummy Variables which is an essential part of data pre-processing, which in itself is an integral part of the Machine Learning or Statistical Model. The categorical variables can be further subdivided into the following categories : Binary or Dichotomous is essentially the variables that can have only two outcomes such as Win/Lose, On/Off, and so on. Nominal Variables are used to represent groups with no particular ranking such as colors, brands, and so on. Ordinal Variables represent groups with a specified ranking order such as Winners of a race, App Ratings to name a few. Dummy Variables act as indicators of the presence or absence of a category in a Categorical Variable. The usual convention dictates that 0 represents absence while 1 represents presence. The conversion of Categorical Variables into Dummy Variables leads to the formation of the two-dimensional binary matrix where each column represents a particular category. The following example will further clarify the process of conversion. Data set containing categorical variable: Data set containing a dummy variable : Explanation: The above data set comprises four categorical columns: OUTLOOK, TEMPERATURE, HUMIDITY, WINDY. Let’s consider the column WINDY which is composed of two categories: YES and NO. So, in the data set that contains the Dummy Variables, the column WINDY is replaced by two columns which each represent the categories: YES and NO. Now comparing the rows of the columns YES and NO with WINDY, we mark 0 for YES where it is absent and 1 where it is present. The same is done for column NO. This methodology is adopted for all the categorical columns. The important thing to notice is that each categorical column is replaced by the number of unique categories it has in the data set containing dummy variables. We are going to be exploring three approaches to convert Categorical Variables into Dummy Variables in this article. These approaches are as follows: Using the LabelBinarizer from sklearnUsing BinaryEncoder from category_encodersUsing the get_dummies() function of the pandas library Using the LabelBinarizer from sklearn Using BinaryEncoder from category_encoders Using the get_dummies() function of the pandas library The first step is creating the data set. This data set comprises 4 categorical columns which go by the name of OUTLOOK, TEMPERATURE, HUMIDITY, WINDY. The following is the code for the creation of the data set. We make this data set using the pandas.DataFrame() and dictionary. Python3 # code to create the dataset # importing the librariesimport pandas as pd # creating the dictionarydictionary = {'OUTLOOK': ['Rainy', 'Rainy', 'Overcast', 'Sunny', 'Sunny', 'Sunny', 'Overcast', 'Rainy', 'Rainy', 'Sunny', 'Rainy', 'Overcast', 'Overcast', 'Sunny'], 'TEMPERATURE': ['Hot', 'Hot', 'Hot', 'Mild', 'Cool', 'Cool', 'Cool', 'Mild', 'Cool', 'Mild', 'Mild', 'Mild', 'Hot', 'Mild'], 'HUMIDITY': ['High', 'High', 'High', 'High', 'Normal', 'Normal', 'Normal', 'High', 'Normal', 'Normal', 'Normal', 'High', 'Normal', 'High'], 'WINDY': ['No', 'Yes', 'No', 'No', 'No', 'Yes', 'Yes', 'No', 'No', 'No', 'Yes', 'Yes', 'No', 'Yes']} # converting the dictionary to DataFramedf = pd.DataFrame(dictionary) display(df) Output: The above is the data set that we will be using for the approaches ahead. Using this approach, we use LabelBinarizer from sklearn which converts one categorical column to a data frame with dummy variables at a time. This data frame can then be appended to the main data frame in the case of there being more than one Categorical column. Python3 # importing the librariesfrom sklearn.preprocessing import LabelBinarizer # creating a copy of the# original data framedf1 = df.copy() # creating an object # of the LabelBinarizerlabel_binarizer = LabelBinarizer() # fitting the column # TEMPERATURE to LabelBinarizerlabel_binarizer_output = label_binarizer.fit_transform( df1['TEMPERATURE']) # creating a data frame from the objectresult_df = pd.DataFrame(label_binarizer_output, columns = label_binarizer.classes_) display(result_df) Output: Conversion of TEMPERATURE column Similarly, we can transform other categorical columns as well. Using the BinaryEncoder from the category_encoders library. Using this approach we can convert multiple categorical columns into dummy variables in a single go. category_encoders: The category_encoders is a Python library developed under the scikit-learn-transformers library. The primary objective of this library is to convert categorical variables into quantifiable numeric variables. There are various advantages of this library such as being readily compatible with the sklearn transformers which allow them to be readily trained and stored in serializable files such as pickle for later use. This library works great in working with data frames as well which is of great use while dealing with machine learning and statistical models. It provides a great range of methods for the conversion from categorical to numeric variables as well which can be categorized into Supervised and Unsupervised. For installation run this command into the terminal: pip install category_encoders For conda: conda install -c conda-forge category_encoders Code: Python3 # importing the librariesimport category_encoders as cat_encoder # creating a copy of the original data framedf2 = df.copy() # creating an object BinaryEncoder# this code calls all columns# we can specify specific columns as wellencoder = cat_encoder.BinaryEncoder(cols = df2.columns) # fitting the columns to a data framedf_category_encoder = encoder.fit_transform( df2 ) display(df_category_encoder) Output: Data Frame created from all the Categorical Columns Under this approach, we deploy the simplest way to perform the conversion of all possible Categorical Columns in a data frame to Dummy Columns by using the get_dummies() method of the pandas library. We can either specify the columns to get the dummies by default it will convert all the possible categorical columns to their dummy columns. Python3 # importing the librariesimport pandas as pd # creating a copy of the original data framedf3 = df.copy() # calling the get_dummies method# the first parameter mentions the# the name of the data frame to store the# new data frame in# the second parameter is the list of# columns which if not mentioned# returns the dummies for all# categorical columnsdf3 = pd.get_dummies(df3, columns = ['WINDY', 'OUTLOOK']) display(df3) Output: Using the get_dummies() for the columns WINDY and OUTLOOK Python-pandas Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Support Vector Machine Algorithm Intuition of Adam Optimizer Introduction to Recurrent Neural Network CNN | Introduction to Pooling Layer Singular Value Decomposition (SVD) Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25699, "s": 25671, "text": "\n11 Dec, 2020" }, { "code": null, "e": 26098, "s": 25699, "text": "All the statistical and machine learning models are built on the foundation of data. A grouped or composite entity holding the relevant to a particular problem together is called a data set. These data sets are composed of Independent Variables or the features and the Dependent Variables or the Labels. All of these variables can be classified into two types of data: Quantitative and Categorical." }, { "code": null, "e": 26432, "s": 26098, "text": "In this article, we are going to deal with the various methods to convert Categorical Variables into Dummy Variables which is an essential part of data pre-processing, which in itself is an integral part of the Machine Learning or Statistical Model. The categorical variables can be further subdivided into the following categories :" }, { "code": null, "e": 26552, "s": 26432, "text": "Binary or Dichotomous is essentially the variables that can have only two outcomes such as Win/Lose, On/Off, and so on." }, { "code": null, "e": 26661, "s": 26552, "text": "Nominal Variables are used to represent groups with no particular ranking such as colors, brands, and so on." }, { "code": null, "e": 26781, "s": 26661, "text": "Ordinal Variables represent groups with a specified ranking order such as Winners of a race, App Ratings to name a few." }, { "code": null, "e": 27211, "s": 26781, "text": "Dummy Variables act as indicators of the presence or absence of a category in a Categorical Variable. The usual convention dictates that 0 represents absence while 1 represents presence. The conversion of Categorical Variables into Dummy Variables leads to the formation of the two-dimensional binary matrix where each column represents a particular category. The following example will further clarify the process of conversion." }, { "code": null, "e": 27253, "s": 27211, "text": "Data set containing categorical variable:" }, { "code": null, "e": 27292, "s": 27253, "text": "Data set containing a dummy variable :" }, { "code": null, "e": 27305, "s": 27292, "text": "Explanation:" }, { "code": null, "e": 27400, "s": 27305, "text": "The above data set comprises four categorical columns: OUTLOOK, TEMPERATURE, HUMIDITY, WINDY. " }, { "code": null, "e": 28007, "s": 27400, "text": "Let’s consider the column WINDY which is composed of two categories: YES and NO. So, in the data set that contains the Dummy Variables, the column WINDY is replaced by two columns which each represent the categories: YES and NO. Now comparing the rows of the columns YES and NO with WINDY, we mark 0 for YES where it is absent and 1 where it is present. The same is done for column NO. This methodology is adopted for all the categorical columns. The important thing to notice is that each categorical column is replaced by the number of unique categories it has in the data set containing dummy variables." }, { "code": null, "e": 28125, "s": 28007, "text": "We are going to be exploring three approaches to convert Categorical Variables into Dummy Variables in this article. " }, { "code": null, "e": 28158, "s": 28125, "text": "These approaches are as follows:" }, { "code": null, "e": 28292, "s": 28158, "text": "Using the LabelBinarizer from sklearnUsing BinaryEncoder from category_encodersUsing the get_dummies() function of the pandas library" }, { "code": null, "e": 28330, "s": 28292, "text": "Using the LabelBinarizer from sklearn" }, { "code": null, "e": 28373, "s": 28330, "text": "Using BinaryEncoder from category_encoders" }, { "code": null, "e": 28428, "s": 28373, "text": "Using the get_dummies() function of the pandas library" }, { "code": null, "e": 28705, "s": 28428, "text": "The first step is creating the data set. This data set comprises 4 categorical columns which go by the name of OUTLOOK, TEMPERATURE, HUMIDITY, WINDY. The following is the code for the creation of the data set. We make this data set using the pandas.DataFrame() and dictionary." }, { "code": null, "e": 28713, "s": 28705, "text": "Python3" }, { "code": "# code to create the dataset # importing the librariesimport pandas as pd # creating the dictionarydictionary = {'OUTLOOK': ['Rainy', 'Rainy', 'Overcast', 'Sunny', 'Sunny', 'Sunny', 'Overcast', 'Rainy', 'Rainy', 'Sunny', 'Rainy', 'Overcast', 'Overcast', 'Sunny'], 'TEMPERATURE': ['Hot', 'Hot', 'Hot', 'Mild', 'Cool', 'Cool', 'Cool', 'Mild', 'Cool', 'Mild', 'Mild', 'Mild', 'Hot', 'Mild'], 'HUMIDITY': ['High', 'High', 'High', 'High', 'Normal', 'Normal', 'Normal', 'High', 'Normal', 'Normal', 'Normal', 'High', 'Normal', 'High'], 'WINDY': ['No', 'Yes', 'No', 'No', 'No', 'Yes', 'Yes', 'No', 'No', 'No', 'Yes', 'Yes', 'No', 'Yes']} # converting the dictionary to DataFramedf = pd.DataFrame(dictionary) display(df)", "e": 29936, "s": 28713, "text": null }, { "code": null, "e": 29944, "s": 29936, "text": "Output:" }, { "code": null, "e": 30018, "s": 29944, "text": "The above is the data set that we will be using for the approaches ahead." }, { "code": null, "e": 30281, "s": 30018, "text": "Using this approach, we use LabelBinarizer from sklearn which converts one categorical column to a data frame with dummy variables at a time. This data frame can then be appended to the main data frame in the case of there being more than one Categorical column." }, { "code": null, "e": 30289, "s": 30281, "text": "Python3" }, { "code": "# importing the librariesfrom sklearn.preprocessing import LabelBinarizer # creating a copy of the# original data framedf1 = df.copy() # creating an object # of the LabelBinarizerlabel_binarizer = LabelBinarizer() # fitting the column # TEMPERATURE to LabelBinarizerlabel_binarizer_output = label_binarizer.fit_transform( df1['TEMPERATURE']) # creating a data frame from the objectresult_df = pd.DataFrame(label_binarizer_output, columns = label_binarizer.classes_) display(result_df)", "e": 30803, "s": 30289, "text": null }, { "code": null, "e": 30811, "s": 30803, "text": "Output:" }, { "code": null, "e": 30844, "s": 30811, "text": "Conversion of TEMPERATURE column" }, { "code": null, "e": 30907, "s": 30844, "text": "Similarly, we can transform other categorical columns as well." }, { "code": null, "e": 31068, "s": 30907, "text": "Using the BinaryEncoder from the category_encoders library. Using this approach we can convert multiple categorical columns into dummy variables in a single go." }, { "code": null, "e": 31810, "s": 31068, "text": "category_encoders: The category_encoders is a Python library developed under the scikit-learn-transformers library. The primary objective of this library is to convert categorical variables into quantifiable numeric variables. There are various advantages of this library such as being readily compatible with the sklearn transformers which allow them to be readily trained and stored in serializable files such as pickle for later use. This library works great in working with data frames as well which is of great use while dealing with machine learning and statistical models. It provides a great range of methods for the conversion from categorical to numeric variables as well which can be categorized into Supervised and Unsupervised. " }, { "code": null, "e": 31863, "s": 31810, "text": "For installation run this command into the terminal:" }, { "code": null, "e": 31893, "s": 31863, "text": "pip install category_encoders" }, { "code": null, "e": 31904, "s": 31893, "text": "For conda:" }, { "code": null, "e": 31951, "s": 31904, "text": "conda install -c conda-forge category_encoders" }, { "code": null, "e": 31957, "s": 31951, "text": "Code:" }, { "code": null, "e": 31965, "s": 31957, "text": "Python3" }, { "code": "# importing the librariesimport category_encoders as cat_encoder # creating a copy of the original data framedf2 = df.copy() # creating an object BinaryEncoder# this code calls all columns# we can specify specific columns as wellencoder = cat_encoder.BinaryEncoder(cols = df2.columns) # fitting the columns to a data framedf_category_encoder = encoder.fit_transform( df2 ) display(df_category_encoder)", "e": 32371, "s": 31965, "text": null }, { "code": null, "e": 32379, "s": 32371, "text": "Output:" }, { "code": null, "e": 32431, "s": 32379, "text": "Data Frame created from all the Categorical Columns" }, { "code": null, "e": 32631, "s": 32431, "text": "Under this approach, we deploy the simplest way to perform the conversion of all possible Categorical Columns in a data frame to Dummy Columns by using the get_dummies() method of the pandas library." }, { "code": null, "e": 32772, "s": 32631, "text": "We can either specify the columns to get the dummies by default it will convert all the possible categorical columns to their dummy columns." }, { "code": null, "e": 32780, "s": 32772, "text": "Python3" }, { "code": "# importing the librariesimport pandas as pd # creating a copy of the original data framedf3 = df.copy() # calling the get_dummies method# the first parameter mentions the# the name of the data frame to store the# new data frame in# the second parameter is the list of# columns which if not mentioned# returns the dummies for all# categorical columnsdf3 = pd.get_dummies(df3, columns = ['WINDY', 'OUTLOOK']) display(df3)", "e": 33224, "s": 32780, "text": null }, { "code": null, "e": 33232, "s": 33224, "text": "Output:" }, { "code": null, "e": 33290, "s": 33232, "text": "Using the get_dummies() for the columns WINDY and OUTLOOK" }, { "code": null, "e": 33304, "s": 33290, "text": "Python-pandas" }, { "code": null, "e": 33321, "s": 33304, "text": "Machine Learning" }, { "code": null, "e": 33328, "s": 33321, "text": "Python" }, { "code": null, "e": 33345, "s": 33328, "text": "Machine Learning" }, { "code": null, "e": 33443, "s": 33345, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33476, "s": 33443, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 33504, "s": 33476, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 33545, "s": 33504, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 33581, "s": 33545, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 33616, "s": 33581, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 33644, "s": 33616, "text": "Read JSON file using Python" }, { "code": null, "e": 33694, "s": 33644, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 33716, "s": 33694, "text": "Python map() function" } ]
Generate all binary strings from given pattern - GeeksforGeeks
22 Apr, 2022 Given a string containing of ‘0’, ‘1’ and ‘?’ wildcard characters, generate all binary strings that can be formed by replacing each wildcard character by ‘0’ or ‘1’. Example : Input str = "1??0?101" Output: 10000101 10001101 10100101 10101101 11000101 11001101 11100101 11101101 Method 1 (Using Recursion) We pass index of next character to the recursive function. If the current character is a wildcard character ‘?’, we replace it with ‘0’ or ‘1’ and recurse for remaining characters. We print the string if we reach its end. Below is recursive the implementation. C++ Java Python3 C# PHP Javascript // Recursive C++ program to generate all binary strings// formed by replacing each wildcard character by 0 or 1#include <iostream>using namespace std; // Recursive function to generate all binary strings// formed by replacing each wildcard character by 0 or 1void print(string str, int index){ if (index == str.size()) { cout << str << endl; return; } if (str[index] == '?') { // replace '?' by '0' and recurse str[index] = '0'; print(str, index + 1); // replace '?' by '1' and recurse str[index] = '1'; print(str, index + 1); // No need to backtrack as string is passed // by value to the function } else print(str, index + 1);} // Driver code to test above functionint main(){ string str = "1??0?101"; print(str, 0); return 0;} // Recursive Java program to generate all// binary strings formed by replacing// each wildcard character by 0 or 1import java.util.*;import java.lang.*;import java.io.*; class binStr{ // Recursive function to generate all binary // strings formed by replacing each wildcard // character by 0 or 1 public static void print(char str[], int index) { if (index == str.length) { System.out.println(str); return; } if (str[index] == '?') { // replace '?' by '0' and recurse str[index] = '0'; print(str, index + 1); // replace '?' by '1' and recurse str[index] = '1'; print(str, index + 1); // NOTE: Need to backtrack as string // is passed by reference to the // function str[index] = '?'; } else print(str, index + 1); } // driver code public static void main (String[] args) { String input = "1??0?101"; char[] str = input.toCharArray(); print(str, 0); }} // This code is contributed by Chhavi # Recursive Python program to generate all# binary strings formed by replacing# each wildcard character by 0 or 1 # Recursive function to generate all binary# strings formed by replacing each wildcard# character by 0 or 1def _print(string, index): if index == len(string): print(''.join(string)) return if string[index] == "?": # replace '?' by '0' and recurse string[index] = '0' _print(string, index + 1) # replace '?' by '1' and recurse string[index] = '1' _print(string, index + 1) # NOTE: Need to backtrack as string # is passed by reference to the # function string[index] = '?' else: _print(string, index + 1) # Driver codeif __name__ == "__main__": string = "1??0?101" string = list(string) _print(string, 0) # This code is contributed by # sanjeev2552 # Note: function name _print is used because# print is already a predefined function in Python // Recursive C# program to generate all// binary strings formed by replacing// each wildcard character by 0 or 1using System; class GFG{ // Recursive function to generate // all binary strings formed by // replacing each wildcard character // by 0 or 1 public static void print(char []str, int index) { if (index == str.Length) { Console.WriteLine(str); return; } if (str[index] == '?') { // replace '?' by // '0' and recurse str[index] = '0'; print(str, index + 1); // replace '?' by // '1' and recurse str[index] = '1'; print(str, index + 1); // NOTE: Need to backtrack // as string is passed by // reference to the function str[index] = '?'; } else print(str, index + 1); } // Driver Code public static void Main () { string input = "1??0?101"; char []str = input.ToCharArray(); print(str, 0); }} // This code is contributed by nitin mittal. <?php// Recursive PHP program to generate all binary strings// formed by replacing each wildcard character by 0 or 1 // Recursive function to generate all binary strings// formed by replacing each wildcard character by 0 or 1function print1($str, $index){ if ($index == strlen($str)) { echo $str."\n"; return; } if ($str[$index] == '?') { // replace '?' by '0' and recurse $str[$index] = '0'; print1($str, $index + 1); // replace '?' by '1' and recurse $str[$index] = '1'; print1($str, $index + 1); // No need to backtrack as string is passed // by value to the function } else print1($str, $index + 1);} // Driver code $str = "1??0?101"; print1($str, 0); // This code is contributed by chandan_jnu?> <script> // Recursive JavaScript program to generate all // binary strings formed by replacing // each wildcard character by 0 or 1 // Recursive function to generate // all binary strings formed by // replacing each wildcard character // by 0 or 1 function print(str, index) { if (index === str.length) { document.write(str.join("") + "<br>"); return; } if (str[index] === "?") { // replace '?' by // '0' and recurse str[index] = "0"; print(str, index + 1); // replace '?' by // '1' and recurse str[index] = "1"; print(str, index + 1); // NOTE: Need to backtrack // as string is passed by // reference to the function str[index] = "?"; } else print(str, index + 1); } // Driver Code var input = "1??0?101"; var str = input.split(""); print(str, 0); </script> 10000101 10001101 10100101 10101101 11000101 11001101 11100101 11101101 Method 2 (Using Queue) We can also achieve this by using iteration. The idea is to use queue. We find position of first occurrence of wildcard character in the input string and replace it by ‘0’ , then ‘1’ and push both strings into the queue. Then we pop next string from the queue, and repeat the process till queue is empty. If no wildcard characters are left, we simply print the string.Iterative C++ implementation using queue. C++ Javascript // Iterative C++ program to generate all binary// strings formed by replacing each wildcard// character by 0 or 1#include <iostream>#include <queue>using namespace std; // Iterative function to generate all binary strings// formed by replacing each wildcard character by 0// or 1void print(string str){ queue<string> q; q.push(str); while (!q.empty()) { string str = q.front(); // find position of first occurrence of wildcard size_t index = str.find('?'); // If no matches were found, // find returns string::npos if(index != string::npos) { // replace '?' by '0' and push string into queue str[index] = '0'; q.push(str); // replace '?' by '1' and push string into queue str[index] = '1'; q.push(str); } else // If no wildcard characters are left, // print the string. cout << str << endl; q.pop(); }} // Driver code to test above functionint main(){ string str = "1??0?101"; print(str); return 0;} <script> // Iterative JavaScript program to generate all binary// strings formed by replacing each wildcard// character by 0 or 1 // Iterative function to generate all binary strings// formed by replacing each wildcard character by 0// or 1function Print(Str){ let q = [] q.push(Str) while (q.length > 0){ let Str = q[0] // find position of first occurrence of wildcard let index = Str.indexOf('?') // If no matches were found, // find returns -1 if(index != -1) { // replace '?' by '0' and push string into queue Str = Str.replace(Str[index] , '0') q.push(Str) // replace '?' by '1' and push string into queue Str = Str.replace(Str[index] , '1') q.push(Str) } else { // If no wildcard characters are left, // print the string. document.write(Str,"</br>") } q.shift() }} // Driver code to test above functionlet Str = "1??0?101"Print(Str) // This code is contributed by shinjanpatra </script> 10000101 10001101 10100101 10101101 11000101 11001101 11100101 11101101 Method 3 (Using str and Recursion) Python3 Javascript #we store processed strings in all (array)#we see if string as "?", if so, replace it with 0 and 1#and send it back to recursive func until base case is reached#which is no wildcard left res = []def genBin(s): if '?' in s: s1 = s.replace('?','0',1) #only replace once s2 = s.replace('?','1',1) #only replace once genBin(s1) genBin(s2) else: res.append(s) # Driver codegenBin("1??0?101")print(res) # This code is contributed by# divay pandey <script>/* we store processed strings in all (array)we see if string as "?", if so, replace it with 0 and 1and send it back to recursive func until base case is reachedwhich is no wildcard left */ let res = []function genBin(s){ if(s.includes('?')){ let s1 = s.replace(/\?/,'0') //only replace once let s2 = s.replace(/\?/,'1') //only replace once genBin(s1) genBin(s2) }else{ res.push(s) }} // Driver codegenBin("1??0?101")document.write(res) // This code is contributed by// Santanu Panda</script> ['10000101', '10001101', '10100101', '10101101', '11000101', '11001101', '11100101', '11101101'] This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. nitin mittal Chandan_Kumar sanjeev2552 divaypandey rdtank shaantalk shinjanpatra Amazon binary-string Google Strings Amazon Google Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Array of Strings in C++ (5 Different Ways to Create) Different methods to reverse a string in C/C++ Convert string to char array in C++ Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 26519, "s": 26491, "text": "\n22 Apr, 2022" }, { "code": null, "e": 26697, "s": 26519, "text": "Given a string containing of ‘0’, ‘1’ and ‘?’ wildcard characters, generate all binary strings that can be formed by replacing each wildcard character by ‘0’ or ‘1’. Example : " }, { "code": null, "e": 26865, "s": 26697, "text": "Input str = \"1??0?101\"\nOutput: \n 10000101\n 10001101\n 10100101\n 10101101\n 11000101\n 11001101\n 11100101\n 11101101" }, { "code": null, "e": 27157, "s": 26867, "text": "Method 1 (Using Recursion) We pass index of next character to the recursive function. If the current character is a wildcard character ‘?’, we replace it with ‘0’ or ‘1’ and recurse for remaining characters. We print the string if we reach its end. Below is recursive the implementation. " }, { "code": null, "e": 27161, "s": 27157, "text": "C++" }, { "code": null, "e": 27166, "s": 27161, "text": "Java" }, { "code": null, "e": 27174, "s": 27166, "text": "Python3" }, { "code": null, "e": 27177, "s": 27174, "text": "C#" }, { "code": null, "e": 27181, "s": 27177, "text": "PHP" }, { "code": null, "e": 27192, "s": 27181, "text": "Javascript" }, { "code": "// Recursive C++ program to generate all binary strings// formed by replacing each wildcard character by 0 or 1#include <iostream>using namespace std; // Recursive function to generate all binary strings// formed by replacing each wildcard character by 0 or 1void print(string str, int index){ if (index == str.size()) { cout << str << endl; return; } if (str[index] == '?') { // replace '?' by '0' and recurse str[index] = '0'; print(str, index + 1); // replace '?' by '1' and recurse str[index] = '1'; print(str, index + 1); // No need to backtrack as string is passed // by value to the function } else print(str, index + 1);} // Driver code to test above functionint main(){ string str = \"1??0?101\"; print(str, 0); return 0;}", "e": 28034, "s": 27192, "text": null }, { "code": "// Recursive Java program to generate all// binary strings formed by replacing// each wildcard character by 0 or 1import java.util.*;import java.lang.*;import java.io.*; class binStr{ // Recursive function to generate all binary // strings formed by replacing each wildcard // character by 0 or 1 public static void print(char str[], int index) { if (index == str.length) { System.out.println(str); return; } if (str[index] == '?') { // replace '?' by '0' and recurse str[index] = '0'; print(str, index + 1); // replace '?' by '1' and recurse str[index] = '1'; print(str, index + 1); // NOTE: Need to backtrack as string // is passed by reference to the // function str[index] = '?'; } else print(str, index + 1); } // driver code public static void main (String[] args) { String input = \"1??0?101\"; char[] str = input.toCharArray(); print(str, 0); }} // This code is contributed by Chhavi", "e": 29197, "s": 28034, "text": null }, { "code": "# Recursive Python program to generate all# binary strings formed by replacing# each wildcard character by 0 or 1 # Recursive function to generate all binary# strings formed by replacing each wildcard# character by 0 or 1def _print(string, index): if index == len(string): print(''.join(string)) return if string[index] == \"?\": # replace '?' by '0' and recurse string[index] = '0' _print(string, index + 1) # replace '?' by '1' and recurse string[index] = '1' _print(string, index + 1) # NOTE: Need to backtrack as string # is passed by reference to the # function string[index] = '?' else: _print(string, index + 1) # Driver codeif __name__ == \"__main__\": string = \"1??0?101\" string = list(string) _print(string, 0) # This code is contributed by # sanjeev2552 # Note: function name _print is used because# print is already a predefined function in Python", "e": 30174, "s": 29197, "text": null }, { "code": "// Recursive C# program to generate all// binary strings formed by replacing// each wildcard character by 0 or 1using System; class GFG{ // Recursive function to generate // all binary strings formed by // replacing each wildcard character // by 0 or 1 public static void print(char []str, int index) { if (index == str.Length) { Console.WriteLine(str); return; } if (str[index] == '?') { // replace '?' by // '0' and recurse str[index] = '0'; print(str, index + 1); // replace '?' by // '1' and recurse str[index] = '1'; print(str, index + 1); // NOTE: Need to backtrack // as string is passed by // reference to the function str[index] = '?'; } else print(str, index + 1); } // Driver Code public static void Main () { string input = \"1??0?101\"; char []str = input.ToCharArray(); print(str, 0); }} // This code is contributed by nitin mittal.", "e": 31343, "s": 30174, "text": null }, { "code": "<?php// Recursive PHP program to generate all binary strings// formed by replacing each wildcard character by 0 or 1 // Recursive function to generate all binary strings// formed by replacing each wildcard character by 0 or 1function print1($str, $index){ if ($index == strlen($str)) { echo $str.\"\\n\"; return; } if ($str[$index] == '?') { // replace '?' by '0' and recurse $str[$index] = '0'; print1($str, $index + 1); // replace '?' by '1' and recurse $str[$index] = '1'; print1($str, $index + 1); // No need to backtrack as string is passed // by value to the function } else print1($str, $index + 1);} // Driver code $str = \"1??0?101\"; print1($str, 0); // This code is contributed by chandan_jnu?>", "e": 32158, "s": 31343, "text": null }, { "code": "<script> // Recursive JavaScript program to generate all // binary strings formed by replacing // each wildcard character by 0 or 1 // Recursive function to generate // all binary strings formed by // replacing each wildcard character // by 0 or 1 function print(str, index) { if (index === str.length) { document.write(str.join(\"\") + \"<br>\"); return; } if (str[index] === \"?\") { // replace '?' by // '0' and recurse str[index] = \"0\"; print(str, index + 1); // replace '?' by // '1' and recurse str[index] = \"1\"; print(str, index + 1); // NOTE: Need to backtrack // as string is passed by // reference to the function str[index] = \"?\"; } else print(str, index + 1); } // Driver Code var input = \"1??0?101\"; var str = input.split(\"\"); print(str, 0); </script>", "e": 33155, "s": 32158, "text": null }, { "code": null, "e": 33227, "s": 33155, "text": "10000101\n10001101\n10100101\n10101101\n11000101\n11001101\n11100101\n11101101" }, { "code": null, "e": 33664, "s": 33229, "text": "Method 2 (Using Queue) We can also achieve this by using iteration. The idea is to use queue. We find position of first occurrence of wildcard character in the input string and replace it by ‘0’ , then ‘1’ and push both strings into the queue. Then we pop next string from the queue, and repeat the process till queue is empty. If no wildcard characters are left, we simply print the string.Iterative C++ implementation using queue. " }, { "code": null, "e": 33668, "s": 33664, "text": "C++" }, { "code": null, "e": 33679, "s": 33668, "text": "Javascript" }, { "code": "// Iterative C++ program to generate all binary// strings formed by replacing each wildcard// character by 0 or 1#include <iostream>#include <queue>using namespace std; // Iterative function to generate all binary strings// formed by replacing each wildcard character by 0// or 1void print(string str){ queue<string> q; q.push(str); while (!q.empty()) { string str = q.front(); // find position of first occurrence of wildcard size_t index = str.find('?'); // If no matches were found, // find returns string::npos if(index != string::npos) { // replace '?' by '0' and push string into queue str[index] = '0'; q.push(str); // replace '?' by '1' and push string into queue str[index] = '1'; q.push(str); } else // If no wildcard characters are left, // print the string. cout << str << endl; q.pop(); }} // Driver code to test above functionint main(){ string str = \"1??0?101\"; print(str); return 0;}", "e": 34780, "s": 33679, "text": null }, { "code": "<script> // Iterative JavaScript program to generate all binary// strings formed by replacing each wildcard// character by 0 or 1 // Iterative function to generate all binary strings// formed by replacing each wildcard character by 0// or 1function Print(Str){ let q = [] q.push(Str) while (q.length > 0){ let Str = q[0] // find position of first occurrence of wildcard let index = Str.indexOf('?') // If no matches were found, // find returns -1 if(index != -1) { // replace '?' by '0' and push string into queue Str = Str.replace(Str[index] , '0') q.push(Str) // replace '?' by '1' and push string into queue Str = Str.replace(Str[index] , '1') q.push(Str) } else { // If no wildcard characters are left, // print the string. document.write(Str,\"</br>\") } q.shift() }} // Driver code to test above functionlet Str = \"1??0?101\"Print(Str) // This code is contributed by shinjanpatra </script>", "e": 35897, "s": 34780, "text": null }, { "code": null, "e": 35969, "s": 35897, "text": "10000101\n10001101\n10100101\n10101101\n11000101\n11001101\n11100101\n11101101" }, { "code": null, "e": 36008, "s": 35971, "text": "Method 3 (Using str and Recursion) " }, { "code": null, "e": 36016, "s": 36008, "text": "Python3" }, { "code": null, "e": 36027, "s": 36016, "text": "Javascript" }, { "code": "#we store processed strings in all (array)#we see if string as \"?\", if so, replace it with 0 and 1#and send it back to recursive func until base case is reached#which is no wildcard left res = []def genBin(s): if '?' in s: s1 = s.replace('?','0',1) #only replace once s2 = s.replace('?','1',1) #only replace once genBin(s1) genBin(s2) else: res.append(s) # Driver codegenBin(\"1??0?101\")print(res) # This code is contributed by# divay pandey", "e": 36502, "s": 36027, "text": null }, { "code": "<script>/* we store processed strings in all (array)we see if string as \"?\", if so, replace it with 0 and 1and send it back to recursive func until base case is reachedwhich is no wildcard left */ let res = []function genBin(s){ if(s.includes('?')){ let s1 = s.replace(/\\?/,'0') //only replace once let s2 = s.replace(/\\?/,'1') //only replace once genBin(s1) genBin(s2) }else{ res.push(s) }} // Driver codegenBin(\"1??0?101\")document.write(res) // This code is contributed by// Santanu Panda</script>", "e": 37023, "s": 36502, "text": null }, { "code": null, "e": 37120, "s": 37023, "text": "['10000101', '10001101', '10100101', '10101101', '11000101', '11001101', '11100101', '11101101']" }, { "code": null, "e": 37389, "s": 37122, "text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 37402, "s": 37389, "text": "nitin mittal" }, { "code": null, "e": 37416, "s": 37402, "text": "Chandan_Kumar" }, { "code": null, "e": 37428, "s": 37416, "text": "sanjeev2552" }, { "code": null, "e": 37440, "s": 37428, "text": "divaypandey" }, { "code": null, "e": 37447, "s": 37440, "text": "rdtank" }, { "code": null, "e": 37457, "s": 37447, "text": "shaantalk" }, { "code": null, "e": 37470, "s": 37457, "text": "shinjanpatra" }, { "code": null, "e": 37477, "s": 37470, "text": "Amazon" }, { "code": null, "e": 37491, "s": 37477, "text": "binary-string" }, { "code": null, "e": 37498, "s": 37491, "text": "Google" }, { "code": null, "e": 37506, "s": 37498, "text": "Strings" }, { "code": null, "e": 37513, "s": 37506, "text": "Amazon" }, { "code": null, "e": 37520, "s": 37513, "text": "Google" }, { "code": null, "e": 37528, "s": 37520, "text": "Strings" }, { "code": null, "e": 37626, "s": 37528, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37701, "s": 37626, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 37758, "s": 37701, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 37794, "s": 37758, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 37847, "s": 37794, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 37894, "s": 37847, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 37930, "s": 37894, "text": "Convert string to char array in C++" }, { "code": null, "e": 37968, "s": 37930, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 37998, "s": 37968, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 38050, "s": 37998, "text": "Check whether two strings are anagram of each other" } ]
Data Mining Multidimensional Association Rule - GeeksforGeeks
17 Dec, 2020 In this article, we are going to discuss Multidimensional Association Rule. Also, we will discuss examples of each. Let’s discuss one by one. Multidimensional Association Rules : In Multi dimensional association rule Qualities can be absolute or quantitative. Quantitative characteristics are numeric and consolidates order. Numeric traits should be discretized. Multi dimensional affiliation rule comprises of more than one measurement. Example –buys(X, “IBM Laptop computer”)buys(X, “HP Inkjet Printer”) Approaches in mining multi dimensional affiliation rules :Three approaches in mining multi dimensional affiliation rules are as following. Using static discretization of quantitative qualities :Discretization is static and happens preceding mining.Discretized ascribes are treated as unmitigated.Use apriori calculation to locate all k-regular predicate sets(this requires k or k+1 table outputs). Each subset of regular predicate set should be continuous.Example –If in an information block the 3D cuboid (age, pay, purchases) is continuous suggests (age, pay), (age, purchases), (pay, purchases) are likewise regular.Note –Information blocks are appropriate for mining since they make mining quicker. The cells of an n-dimensional information cuboid relate to the predicate cells.Using powerful discretization of quantitative traits :Known as mining Quantitative Association Rules.Numeric properties are progressively discretized.Example –:age(X, "20..25") Λ income(X, "30K..41K")buys ( X, "Laptop Computer") Grid FOR TUPLES :Using distance based discretization with bunching –This id dynamic discretization measure that considers the distance between information focuses. It includes a two stage mining measure as following.Perform bunching to discover the time period included.Get affiliation rules via looking for gatherings of groups that happen together.The resultant guidelines may fulfill –Bunches in the standard precursor are unequivocally connected with groups of rules in the subsequent.Bunches in the forerunner happen together.Bunches in the ensuing happen together. Using static discretization of quantitative qualities :Discretization is static and happens preceding mining.Discretized ascribes are treated as unmitigated.Use apriori calculation to locate all k-regular predicate sets(this requires k or k+1 table outputs). Each subset of regular predicate set should be continuous.Example –If in an information block the 3D cuboid (age, pay, purchases) is continuous suggests (age, pay), (age, purchases), (pay, purchases) are likewise regular.Note –Information blocks are appropriate for mining since they make mining quicker. The cells of an n-dimensional information cuboid relate to the predicate cells. Discretization is static and happens preceding mining. Discretized ascribes are treated as unmitigated. Use apriori calculation to locate all k-regular predicate sets(this requires k or k+1 table outputs). Each subset of regular predicate set should be continuous. Example –If in an information block the 3D cuboid (age, pay, purchases) is continuous suggests (age, pay), (age, purchases), (pay, purchases) are likewise regular. Note –Information blocks are appropriate for mining since they make mining quicker. The cells of an n-dimensional information cuboid relate to the predicate cells. Using powerful discretization of quantitative traits :Known as mining Quantitative Association Rules.Numeric properties are progressively discretized.Example –:age(X, "20..25") Λ income(X, "30K..41K")buys ( X, "Laptop Computer") Known as mining Quantitative Association Rules. Numeric properties are progressively discretized. Example –: age(X, "20..25") Λ income(X, "30K..41K")buys ( X, "Laptop Computer") Grid FOR TUPLES :Using distance based discretization with bunching –This id dynamic discretization measure that considers the distance between information focuses. It includes a two stage mining measure as following.Perform bunching to discover the time period included.Get affiliation rules via looking for gatherings of groups that happen together.The resultant guidelines may fulfill –Bunches in the standard precursor are unequivocally connected with groups of rules in the subsequent.Bunches in the forerunner happen together.Bunches in the ensuing happen together. Perform bunching to discover the time period included. Get affiliation rules via looking for gatherings of groups that happen together. The resultant guidelines may fulfill – Bunches in the standard precursor are unequivocally connected with groups of rules in the subsequent. Bunches in the forerunner happen together. Bunches in the ensuing happen together. data mining DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Trigger | Student Database SQL Interview Questions CTE in SQL Introduction of B-Tree Difference between Clustered and Non-clustered index Introduction of ER Model Introduction of DBMS (Database Management System) | Set 1 SQL | GROUP BY Difference between DELETE, DROP and TRUNCATE SQL | Views
[ { "code": null, "e": 25707, "s": 25679, "text": "\n17 Dec, 2020" }, { "code": null, "e": 25849, "s": 25707, "text": "In this article, we are going to discuss Multidimensional Association Rule. Also, we will discuss examples of each. Let’s discuss one by one." }, { "code": null, "e": 25886, "s": 25849, "text": "Multidimensional Association Rules :" }, { "code": null, "e": 25967, "s": 25886, "text": "In Multi dimensional association rule Qualities can be absolute or quantitative." }, { "code": null, "e": 26032, "s": 25967, "text": "Quantitative characteristics are numeric and consolidates order." }, { "code": null, "e": 26070, "s": 26032, "text": "Numeric traits should be discretized." }, { "code": null, "e": 26145, "s": 26070, "text": "Multi dimensional affiliation rule comprises of more than one measurement." }, { "code": null, "e": 26213, "s": 26145, "text": "Example –buys(X, “IBM Laptop computer”)buys(X, “HP Inkjet Printer”)" }, { "code": null, "e": 26352, "s": 26213, "text": "Approaches in mining multi dimensional affiliation rules :Three approaches in mining multi dimensional affiliation rules are as following." }, { "code": null, "e": 27795, "s": 26352, "text": "Using static discretization of quantitative qualities :Discretization is static and happens preceding mining.Discretized ascribes are treated as unmitigated.Use apriori calculation to locate all k-regular predicate sets(this requires k or k+1 table outputs). Each subset of regular predicate set should be continuous.Example –If in an information block the 3D cuboid (age, pay, purchases) is continuous suggests (age, pay), (age, purchases), (pay, purchases) are likewise regular.Note –Information blocks are appropriate for mining since they make mining quicker. The cells of an n-dimensional information cuboid relate to the predicate cells.Using powerful discretization of quantitative traits :Known as mining Quantitative Association Rules.Numeric properties are progressively discretized.Example –:age(X, \"20..25\") Λ income(X, \"30K..41K\")buys ( X, \"Laptop Computer\") Grid FOR TUPLES :Using distance based discretization with bunching –This id dynamic discretization measure that considers the distance between information focuses. It includes a two stage mining measure as following.Perform bunching to discover the time period included.Get affiliation rules via looking for gatherings of groups that happen together.The resultant guidelines may fulfill –Bunches in the standard precursor are unequivocally connected with groups of rules in the subsequent.Bunches in the forerunner happen together.Bunches in the ensuing happen together." }, { "code": null, "e": 28439, "s": 27795, "text": "Using static discretization of quantitative qualities :Discretization is static and happens preceding mining.Discretized ascribes are treated as unmitigated.Use apriori calculation to locate all k-regular predicate sets(this requires k or k+1 table outputs). Each subset of regular predicate set should be continuous.Example –If in an information block the 3D cuboid (age, pay, purchases) is continuous suggests (age, pay), (age, purchases), (pay, purchases) are likewise regular.Note –Information blocks are appropriate for mining since they make mining quicker. The cells of an n-dimensional information cuboid relate to the predicate cells." }, { "code": null, "e": 28494, "s": 28439, "text": "Discretization is static and happens preceding mining." }, { "code": null, "e": 28543, "s": 28494, "text": "Discretized ascribes are treated as unmitigated." }, { "code": null, "e": 28704, "s": 28543, "text": "Use apriori calculation to locate all k-regular predicate sets(this requires k or k+1 table outputs). Each subset of regular predicate set should be continuous." }, { "code": null, "e": 28868, "s": 28704, "text": "Example –If in an information block the 3D cuboid (age, pay, purchases) is continuous suggests (age, pay), (age, purchases), (pay, purchases) are likewise regular." }, { "code": null, "e": 29032, "s": 28868, "text": "Note –Information blocks are appropriate for mining since they make mining quicker. The cells of an n-dimensional information cuboid relate to the predicate cells." }, { "code": null, "e": 29262, "s": 29032, "text": "Using powerful discretization of quantitative traits :Known as mining Quantitative Association Rules.Numeric properties are progressively discretized.Example –:age(X, \"20..25\") Λ income(X, \"30K..41K\")buys ( X, \"Laptop Computer\") " }, { "code": null, "e": 29310, "s": 29262, "text": "Known as mining Quantitative Association Rules." }, { "code": null, "e": 29360, "s": 29310, "text": "Numeric properties are progressively discretized." }, { "code": null, "e": 29371, "s": 29360, "text": "Example –:" }, { "code": null, "e": 29441, "s": 29371, "text": "age(X, \"20..25\") Λ income(X, \"30K..41K\")buys ( X, \"Laptop Computer\") " }, { "code": null, "e": 30012, "s": 29441, "text": "Grid FOR TUPLES :Using distance based discretization with bunching –This id dynamic discretization measure that considers the distance between information focuses. It includes a two stage mining measure as following.Perform bunching to discover the time period included.Get affiliation rules via looking for gatherings of groups that happen together.The resultant guidelines may fulfill –Bunches in the standard precursor are unequivocally connected with groups of rules in the subsequent.Bunches in the forerunner happen together.Bunches in the ensuing happen together." }, { "code": null, "e": 30067, "s": 30012, "text": "Perform bunching to discover the time period included." }, { "code": null, "e": 30148, "s": 30067, "text": "Get affiliation rules via looking for gatherings of groups that happen together." }, { "code": null, "e": 30187, "s": 30148, "text": "The resultant guidelines may fulfill –" }, { "code": null, "e": 30289, "s": 30187, "text": "Bunches in the standard precursor are unequivocally connected with groups of rules in the subsequent." }, { "code": null, "e": 30332, "s": 30289, "text": "Bunches in the forerunner happen together." }, { "code": null, "e": 30372, "s": 30332, "text": "Bunches in the ensuing happen together." }, { "code": null, "e": 30384, "s": 30372, "text": "data mining" }, { "code": null, "e": 30389, "s": 30384, "text": "DBMS" }, { "code": null, "e": 30394, "s": 30389, "text": "DBMS" }, { "code": null, "e": 30492, "s": 30394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30523, "s": 30492, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 30547, "s": 30523, "text": "SQL Interview Questions" }, { "code": null, "e": 30558, "s": 30547, "text": "CTE in SQL" }, { "code": null, "e": 30581, "s": 30558, "text": "Introduction of B-Tree" }, { "code": null, "e": 30634, "s": 30581, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 30659, "s": 30634, "text": "Introduction of ER Model" }, { "code": null, "e": 30717, "s": 30659, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 30732, "s": 30717, "text": "SQL | GROUP BY" }, { "code": null, "e": 30777, "s": 30732, "text": "Difference between DELETE, DROP and TRUNCATE" } ]
Climb n-th stair with all jumps from 1 to n allowed (Three Different Approaches) - GeeksforGeeks
28 Mar, 2022 A monkey is standing below at a staircase having N steps. Considering it can take a leap of 1 to N steps at a time, calculate how many ways it can reach the top of the staircase? Examples: Input : 2 Output : 2 It can either take (1, 1) or (2) to reach the top. So, total 2 ways Input : 3 Output : 4 Possibilities : (1, 1, 1), (1, 2), (2, 1), (3). So, total 4 ways There are 3 different ways to think of the problem. In all possible solutions, a step is either stepped on by the monkey or can be skipped. So using the fundamental counting principle, the first step has 2 ways to take part, and for each of these, 2nd step also has 2 ways, and so on. but the last step always has to be stepped on. In all possible solutions, a step is either stepped on by the monkey or can be skipped. So using the fundamental counting principle, the first step has 2 ways to take part, and for each of these, 2nd step also has 2 ways, and so on. but the last step always has to be stepped on. 2 x 2 x 2 x .... x 2(N-1 th step) x 1(Nth step) = 2(N-1) different ways. Let’s define a function F(n) for the use case. F(n) denotes all possible way to reach from bottom to top of a staircase having N steps, where min leap is 1 step and max leap is N step. Now, for the monkey, the first move it can make is possible in N different ways ( 1 step, 2 steps, 3 steps .. N steps). If it takes the first leap as 1 step, it will be left with N-1 more steps to conquer, which can be achieved in F(N-1) ways. And if it takes the first leap as 2 steps, it will have N-2 steps more to cover, which can be achieved in F(N-2) ways. Putting together, Let’s define a function F(n) for the use case. F(n) denotes all possible way to reach from bottom to top of a staircase having N steps, where min leap is 1 step and max leap is N step. Now, for the monkey, the first move it can make is possible in N different ways ( 1 step, 2 steps, 3 steps .. N steps). If it takes the first leap as 1 step, it will be left with N-1 more steps to conquer, which can be achieved in F(N-1) ways. And if it takes the first leap as 2 steps, it will have N-2 steps more to cover, which can be achieved in F(N-2) ways. Putting together, F(N) = F(N-1) + F(N-2) + F(N-3) + ... + F(2) + F(1) + F(0) Now, F(0) = 1 F(1) = 1 F(2) = 2 F(3) = 4 Hence, F(N) = 1 + 1 + 2 + 4 + ... + F(n-1) = 1 + 2^0 + 2^1 + 2^2 + ... + 2^(n-2) = 1 + [2^(n-1) - 1] C++ Java Python3 C# PHP Javascript // C++ program to count total number of ways// to reach n-th stair with all jumps allowed#include <iostream> int calculateLeaps(int n){ if (n == 0 || n == 1) { return 1; } else { int leaps = 0; for (int i = 0; i < n; i++) leaps += calculateLeaps(i); return leaps; }} // Driver codeint main(){ int calculateLeaps(int); std::cout << calculateLeaps(4) << std::endl; return 0;} // Java program to count total number of ways// to reach n-th stair with all jumps allowedclass GFG { static int calculateLeaps(int n) { if (n == 0 || n == 1) { return 1; } else { int leaps = 0; for (int i = 0; i < n; i++) leaps += calculateLeaps(i); return leaps; } } // Driver code public static void main(String[] args) { System.out.println(calculateLeaps(4)); }}// This code is contributed by Anant Agarwal. # Python program to count# total number of ways# to reach n-th stair with# all jumps allowed def calculateLeaps(n): if n == 0 or n == 1: return 1; else: leaps = 0; for i in range(0,n): leaps = leaps + calculateLeaps(i); return leaps; # Driver codeprint(calculateLeaps(4)); # This code is contributed by mits // C# program to count total number of ways// to reach n-th stair with all jumps allowedusing System; class GFG { // Function to calculate leaps static int calculateLeaps(int n) { if (n == 0 || n == 1) { return 1; } else { int leaps = 0; for (int i = 0; i < n; i++) leaps += calculateLeaps(i); return leaps; } } // Driver code public static void Main() { Console.WriteLine(calculateLeaps(4)); }} // This code is contributed by vt_m. <?php// PHP program to count total// number of ways to reach// n-th stair with all// jumps allowed // function return the// number of waysfunction calculateLeaps($n){ if ($n == 0 || $n == 1) { return 1; } else { $leaps = 0; for ($i = 0; $i < $n; $i++) $leaps += calculateLeaps($i); return $leaps; }} // Driver Code echo calculateLeaps(4), "\n"; // This code is contributed by ajit?> <script> // Javascript program to count total number of ways // to reach n-th stair with all jumps allowed // Function to calculate leaps function calculateLeaps(n) { if (n == 0 || n == 1) { return 1; } else { let leaps = 0; for (let i = 0; i < n; i++) leaps += calculateLeaps(i); return leaps; } } document.write(calculateLeaps(4)); </script> Output: Output: 8 2. The above solution can be improved by using Dynamic programming (Bottom-Up Approach) Leaps(3) 3/ 2| 1\ Leaps(0) Leaps(1) Leaps(2) / | \ 3/ 2| 1\ Leaps(-3) Leaps(-2) Leaps(-1) Lepas(-1) Leaps(0) Leaps(1) C++ Python3 Javascript // C++ program to count total number of ways// to reach n-th stair with all jumps allowed #include <iostream>using namespace std; int calculateLeaps(int n, int dp[]){ if(n == 0){ return 1 ; }else if(n < 0){ return 0 ; } if(dp[n] != 0 ){ return dp[n] ; } int count = 0; for(int i = 0 ; i < n ; i++ ){ count += calculateLeaps(i, dp) ; } dp[n] = count ; return count ; }int main() { int n = 4 ; int dp[n+1] = {0} ; cout<<calculateLeaps(n,dp) ; return 0; } # Python program to count total number of ways# to reach n-th stair with all jumps alloweddef calculateLeaps(n, dp): if(n == 0): return 1 elif(n < 0): return 0 if(dp[n] != 0 ): return dp[n] count = 0 for i in range(n): count += calculateLeaps(i, dp) dp[n] = count return count # driver coden = 4dp = [0]*(n+1)print(calculateLeaps(n,dp)) # This code is contributed by shinjanpatra <script> // JavaScript program to count total number of ways// to reach n-th stair with all jumps allowedfunction calculateLeaps(n, dp){ if(n == 0){ return 1 }else if(n < 0){ return 0 } if(dp[n] != 0 ){ return dp[n] } let count = 0 for(let i = 0 ; i < n ; i++ ){ count += calculateLeaps(i, dp) } dp[n] = count return count } // driver codelet n = 4let dp = new Array(n+1).fill(0)document.write(calculateLeaps(n,dp)) // This code is contributed by shinjanpatra </script> 3. Let’s break this problem into small subproblems. The monkey has to step on the last step, the first N-1 steps are optional. The monkey can step on 0 steps before reaching the top step, which is the biggest leap to the top. Or it can decide to step on only once in between, which can be achieved in n-1 ways [ (N-1)C1 ]. And so on, it can step on only 2 steps before reaching the top in (N-1)C2 ways. Putting together..F(N) = (N-1)C0 + (N-1)C1 + (N-1)C2 + ... + (N-1)C(N-2) + (N-1)C(N-1) Which is sum of binomial coefficient. = 2^(n-1) C++ Java Python3 C# PHP Javascript // C++ program to count total number of ways// to reach n-th stair with all jumps allowed#include <bits/stdc++.h>using namespace std; int calculateLeaps(int n) { if (n == 0) return 1; return (1 << (n - 1)); } // Driver codeint main(){ int calculateLeaps(int); std::cout << calculateLeaps(4) << std::endl; return 0;} // This code is contributed by shivanisinghss2110. // Java program to count total number of ways// to reach n-th stair with all jumps allowedclass GFG { static int calculateLeaps(int n) { if (n == 0) return 1; return (1 << (n - 1)); } // Driver code public static void main(String[] args) { System.out.println(calculateLeaps(4)); }}// This code is contributed by Anant Agarwal. # python3 program to count# total number of ways# to reach n-th stair with# all jumps allowed def calculateLeaps(n): if (n == 0): return 1; return (1 << (n - 1)); # Driver codeprint(calculateLeaps(4)); # This code is contributed# by mits // C# program to count total number of ways// to reach n-th stair with all jumps allowedusing System; class GFG { // Function to calculate leaps static int calculateLeaps(int n) { if (n == 0) return 1; return (1 << (n - 1)); } // Driver code public static void Main() { Console.WriteLine(calculateLeaps(4)); }} // This code is contributed by vt_m. <?php// PHP program to count total// number of ways to reach n-th// stair with all jumps allowed // Function to calculate leapsfunction calculateLeaps($n){ if ($n == 0) return 1; return (1 << ($n - 1));} // Driver codeecho calculateLeaps(4); // This code is contributed by Sam007?> <script> // javascript program to count total number of ways// to reach n-th stair with all jumps allowed function calculateLeaps(n){ if (n == 0) return 1; return (1 << (n - 1));} // Driver codedocument.write(calculateLeaps(4)); // This code is contributed by Amit Katiyar</script> Output: 8 This article is contributed by Partha Pratim Mallik. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m jit_t Sam007 Mithun Kumar amit143katiyar suresh07 sumitgumber28 shivanisinghss2110 prasanna1995 shinjanpatra Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Algorithm to solve Rubik's Cube Modular multiplicative inverse Program to multiply two matrices Program to convert a given number to words Count ways to reach the n'th stair Fizz Buzz Implementation Singular Value Decomposition (SVD) Program to print prime numbers from 1 to N. Find first and last digits of a number Check if a number is Palindrome
[ { "code": null, "e": 24638, "s": 24610, "text": "\n28 Mar, 2022" }, { "code": null, "e": 24817, "s": 24638, "text": "A monkey is standing below at a staircase having N steps. Considering it can take a leap of 1 to N steps at a time, calculate how many ways it can reach the top of the staircase?" }, { "code": null, "e": 24828, "s": 24817, "text": "Examples: " }, { "code": null, "e": 25005, "s": 24828, "text": "Input : 2\nOutput : 2\nIt can either take (1, 1) or (2) to\nreach the top. So, total 2 ways\n\nInput : 3\nOutput : 4\nPossibilities : (1, 1, 1), (1, 2), (2, 1),\n(3). So, total 4 ways " }, { "code": null, "e": 25058, "s": 25005, "text": "There are 3 different ways to think of the problem. " }, { "code": null, "e": 25338, "s": 25058, "text": "In all possible solutions, a step is either stepped on by the monkey or can be skipped. So using the fundamental counting principle, the first step has 2 ways to take part, and for each of these, 2nd step also has 2 ways, and so on. but the last step always has to be stepped on." }, { "code": null, "e": 25618, "s": 25338, "text": "In all possible solutions, a step is either stepped on by the monkey or can be skipped. So using the fundamental counting principle, the first step has 2 ways to take part, and for each of these, 2nd step also has 2 ways, and so on. but the last step always has to be stepped on." }, { "code": null, "e": 25697, "s": 25618, "text": " 2 x 2 x 2 x .... x 2(N-1 th step) x 1(Nth step) \n = 2(N-1) different ways. " }, { "code": null, "e": 26263, "s": 25697, "text": "Let’s define a function F(n) for the use case. F(n) denotes all possible way to reach from bottom to top of a staircase having N steps, where min leap is 1 step and max leap is N step. Now, for the monkey, the first move it can make is possible in N different ways ( 1 step, 2 steps, 3 steps .. N steps). If it takes the first leap as 1 step, it will be left with N-1 more steps to conquer, which can be achieved in F(N-1) ways. And if it takes the first leap as 2 steps, it will have N-2 steps more to cover, which can be achieved in F(N-2) ways. Putting together," }, { "code": null, "e": 26829, "s": 26263, "text": "Let’s define a function F(n) for the use case. F(n) denotes all possible way to reach from bottom to top of a staircase having N steps, where min leap is 1 step and max leap is N step. Now, for the monkey, the first move it can make is possible in N different ways ( 1 step, 2 steps, 3 steps .. N steps). If it takes the first leap as 1 step, it will be left with N-1 more steps to conquer, which can be achieved in F(N-1) ways. And if it takes the first leap as 2 steps, it will have N-2 steps more to cover, which can be achieved in F(N-2) ways. Putting together," }, { "code": null, "e": 27066, "s": 26829, "text": "F(N) = F(N-1) + F(N-2) + F(N-3) + ... + \n F(2) + F(1) + F(0) \nNow, \nF(0) = 1\nF(1) = 1\nF(2) = 2\nF(3) = 4\n\nHence,\nF(N) = 1 + 1 + 2 + 4 + ... + F(n-1)\n = 1 + 2^0 + 2^1 + 2^2 + ... + 2^(n-2)\n = 1 + [2^(n-1) - 1]" }, { "code": null, "e": 27070, "s": 27066, "text": "C++" }, { "code": null, "e": 27075, "s": 27070, "text": "Java" }, { "code": null, "e": 27083, "s": 27075, "text": "Python3" }, { "code": null, "e": 27086, "s": 27083, "text": "C#" }, { "code": null, "e": 27090, "s": 27086, "text": "PHP" }, { "code": null, "e": 27101, "s": 27090, "text": "Javascript" }, { "code": "// C++ program to count total number of ways// to reach n-th stair with all jumps allowed#include <iostream> int calculateLeaps(int n){ if (n == 0 || n == 1) { return 1; } else { int leaps = 0; for (int i = 0; i < n; i++) leaps += calculateLeaps(i); return leaps; }} // Driver codeint main(){ int calculateLeaps(int); std::cout << calculateLeaps(4) << std::endl; return 0;}", "e": 27535, "s": 27101, "text": null }, { "code": "// Java program to count total number of ways// to reach n-th stair with all jumps allowedclass GFG { static int calculateLeaps(int n) { if (n == 0 || n == 1) { return 1; } else { int leaps = 0; for (int i = 0; i < n; i++) leaps += calculateLeaps(i); return leaps; } } // Driver code public static void main(String[] args) { System.out.println(calculateLeaps(4)); }}// This code is contributed by Anant Agarwal.", "e": 28063, "s": 27535, "text": null }, { "code": "# Python program to count# total number of ways# to reach n-th stair with# all jumps allowed def calculateLeaps(n): if n == 0 or n == 1: return 1; else: leaps = 0; for i in range(0,n): leaps = leaps + calculateLeaps(i); return leaps; # Driver codeprint(calculateLeaps(4)); # This code is contributed by mits", "e": 28416, "s": 28063, "text": null }, { "code": "// C# program to count total number of ways// to reach n-th stair with all jumps allowedusing System; class GFG { // Function to calculate leaps static int calculateLeaps(int n) { if (n == 0 || n == 1) { return 1; } else { int leaps = 0; for (int i = 0; i < n; i++) leaps += calculateLeaps(i); return leaps; } } // Driver code public static void Main() { Console.WriteLine(calculateLeaps(4)); }} // This code is contributed by vt_m.", "e": 28969, "s": 28416, "text": null }, { "code": "<?php// PHP program to count total// number of ways to reach// n-th stair with all// jumps allowed // function return the// number of waysfunction calculateLeaps($n){ if ($n == 0 || $n == 1) { return 1; } else { $leaps = 0; for ($i = 0; $i < $n; $i++) $leaps += calculateLeaps($i); return $leaps; }} // Driver Code echo calculateLeaps(4), \"\\n\"; // This code is contributed by ajit?>", "e": 29416, "s": 28969, "text": null }, { "code": "<script> // Javascript program to count total number of ways // to reach n-th stair with all jumps allowed // Function to calculate leaps function calculateLeaps(n) { if (n == 0 || n == 1) { return 1; } else { let leaps = 0; for (let i = 0; i < n; i++) leaps += calculateLeaps(i); return leaps; } } document.write(calculateLeaps(4)); </script>", "e": 29882, "s": 29416, "text": null }, { "code": null, "e": 29890, "s": 29882, "text": "Output:" }, { "code": null, "e": 29898, "s": 29890, "text": "Output:" }, { "code": null, "e": 29900, "s": 29898, "text": "8" }, { "code": null, "e": 29988, "s": 29900, "text": "2. The above solution can be improved by using Dynamic programming (Bottom-Up Approach)" }, { "code": null, "e": 30273, "s": 29988, "text": " Leaps(3)\n 3/ 2| 1\\\n Leaps(0) Leaps(1) Leaps(2)\n / | \\ 3/ 2| 1\\\n Leaps(-3) Leaps(-2) Leaps(-1) Lepas(-1) Leaps(0) Leaps(1)" }, { "code": null, "e": 30277, "s": 30273, "text": "C++" }, { "code": null, "e": 30285, "s": 30277, "text": "Python3" }, { "code": null, "e": 30296, "s": 30285, "text": "Javascript" }, { "code": "// C++ program to count total number of ways// to reach n-th stair with all jumps allowed #include <iostream>using namespace std; int calculateLeaps(int n, int dp[]){ if(n == 0){ return 1 ; }else if(n < 0){ return 0 ; } if(dp[n] != 0 ){ return dp[n] ; } int count = 0; for(int i = 0 ; i < n ; i++ ){ count += calculateLeaps(i, dp) ; } dp[n] = count ; return count ; }int main() { int n = 4 ; int dp[n+1] = {0} ; cout<<calculateLeaps(n,dp) ; return 0; }", "e": 30847, "s": 30296, "text": null }, { "code": "# Python program to count total number of ways# to reach n-th stair with all jumps alloweddef calculateLeaps(n, dp): if(n == 0): return 1 elif(n < 0): return 0 if(dp[n] != 0 ): return dp[n] count = 0 for i in range(n): count += calculateLeaps(i, dp) dp[n] = count return count # driver coden = 4dp = [0]*(n+1)print(calculateLeaps(n,dp)) # This code is contributed by shinjanpatra", "e": 31291, "s": 30847, "text": null }, { "code": "<script> // JavaScript program to count total number of ways// to reach n-th stair with all jumps allowedfunction calculateLeaps(n, dp){ if(n == 0){ return 1 }else if(n < 0){ return 0 } if(dp[n] != 0 ){ return dp[n] } let count = 0 for(let i = 0 ; i < n ; i++ ){ count += calculateLeaps(i, dp) } dp[n] = count return count } // driver codelet n = 4let dp = new Array(n+1).fill(0)document.write(calculateLeaps(n,dp)) // This code is contributed by shinjanpatra </script>", "e": 31833, "s": 31291, "text": null }, { "code": null, "e": 32371, "s": 31833, "text": "3. Let’s break this problem into small subproblems. The monkey has to step on the last step, the first N-1 steps are optional. The monkey can step on 0 steps before reaching the top step, which is the biggest leap to the top. Or it can decide to step on only once in between, which can be achieved in n-1 ways [ (N-1)C1 ]. And so on, it can step on only 2 steps before reaching the top in (N-1)C2 ways. Putting together..F(N) = (N-1)C0 + (N-1)C1 + (N-1)C2 + ... + (N-1)C(N-2) + (N-1)C(N-1) Which is sum of binomial coefficient. = 2^(n-1)" }, { "code": null, "e": 32375, "s": 32371, "text": "C++" }, { "code": null, "e": 32380, "s": 32375, "text": "Java" }, { "code": null, "e": 32388, "s": 32380, "text": "Python3" }, { "code": null, "e": 32391, "s": 32388, "text": "C#" }, { "code": null, "e": 32395, "s": 32391, "text": "PHP" }, { "code": null, "e": 32406, "s": 32395, "text": "Javascript" }, { "code": "// C++ program to count total number of ways// to reach n-th stair with all jumps allowed#include <bits/stdc++.h>using namespace std; int calculateLeaps(int n) { if (n == 0) return 1; return (1 << (n - 1)); } // Driver codeint main(){ int calculateLeaps(int); std::cout << calculateLeaps(4) << std::endl; return 0;} // This code is contributed by shivanisinghss2110.", "e": 32818, "s": 32406, "text": null }, { "code": "// Java program to count total number of ways// to reach n-th stair with all jumps allowedclass GFG { static int calculateLeaps(int n) { if (n == 0) return 1; return (1 << (n - 1)); } // Driver code public static void main(String[] args) { System.out.println(calculateLeaps(4)); }}// This code is contributed by Anant Agarwal.", "e": 33199, "s": 32818, "text": null }, { "code": "# python3 program to count# total number of ways# to reach n-th stair with# all jumps allowed def calculateLeaps(n): if (n == 0): return 1; return (1 << (n - 1)); # Driver codeprint(calculateLeaps(4)); # This code is contributed# by mits", "e": 33450, "s": 33199, "text": null }, { "code": "// C# program to count total number of ways// to reach n-th stair with all jumps allowedusing System; class GFG { // Function to calculate leaps static int calculateLeaps(int n) { if (n == 0) return 1; return (1 << (n - 1)); } // Driver code public static void Main() { Console.WriteLine(calculateLeaps(4)); }} // This code is contributed by vt_m.", "e": 33856, "s": 33450, "text": null }, { "code": "<?php// PHP program to count total// number of ways to reach n-th// stair with all jumps allowed // Function to calculate leapsfunction calculateLeaps($n){ if ($n == 0) return 1; return (1 << ($n - 1));} // Driver codeecho calculateLeaps(4); // This code is contributed by Sam007?>", "e": 34151, "s": 33856, "text": null }, { "code": "<script> // javascript program to count total number of ways// to reach n-th stair with all jumps allowed function calculateLeaps(n){ if (n == 0) return 1; return (1 << (n - 1));} // Driver codedocument.write(calculateLeaps(4)); // This code is contributed by Amit Katiyar</script>", "e": 34446, "s": 34151, "text": null }, { "code": null, "e": 34456, "s": 34446, "text": "Output: " }, { "code": null, "e": 34458, "s": 34456, "text": "8" }, { "code": null, "e": 34887, "s": 34458, "text": "This article is contributed by Partha Pratim Mallik. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34892, "s": 34887, "text": "vt_m" }, { "code": null, "e": 34898, "s": 34892, "text": "jit_t" }, { "code": null, "e": 34905, "s": 34898, "text": "Sam007" }, { "code": null, "e": 34918, "s": 34905, "text": "Mithun Kumar" }, { "code": null, "e": 34933, "s": 34918, "text": "amit143katiyar" }, { "code": null, "e": 34942, "s": 34933, "text": "suresh07" }, { "code": null, "e": 34956, "s": 34942, "text": "sumitgumber28" }, { "code": null, "e": 34975, "s": 34956, "text": "shivanisinghss2110" }, { "code": null, "e": 34988, "s": 34975, "text": "prasanna1995" }, { "code": null, "e": 35001, "s": 34988, "text": "shinjanpatra" }, { "code": null, "e": 35014, "s": 35001, "text": "Mathematical" }, { "code": null, "e": 35027, "s": 35014, "text": "Mathematical" }, { "code": null, "e": 35125, "s": 35027, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35134, "s": 35125, "text": "Comments" }, { "code": null, "e": 35147, "s": 35134, "text": "Old Comments" }, { "code": null, "e": 35179, "s": 35147, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 35210, "s": 35179, "text": "Modular multiplicative inverse" }, { "code": null, "e": 35243, "s": 35210, "text": "Program to multiply two matrices" }, { "code": null, "e": 35286, "s": 35243, "text": "Program to convert a given number to words" }, { "code": null, "e": 35321, "s": 35286, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 35346, "s": 35321, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 35381, "s": 35346, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 35425, "s": 35381, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 35464, "s": 35425, "text": "Find first and last digits of a number" } ]
C# | Check if an element is in the Collection<T>
01 Feb, 2019 Collection<T>.Contains(T) method is used to determine whether an element is in the Collection<T>. Syntax: public bool Contains (T item); Here, item is the object to locate in the Collection<T>. The value can be null for reference types. Return Value: This method return True if item is found in the Collection<T>, otherwise, False. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to check if an// element is in the Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); myColl.Add("A"); myColl.Add("B"); myColl.Add("C"); myColl.Add("D"); myColl.Add("E"); // Checking if an element is in the Collection // The function returns "True" if the // item is present in Collection // else returns "False" Console.WriteLine(myColl.Contains("A")); }} Output: True Example 2: // C# code to check if an// element is in the Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of ints Collection<int> myColl = new Collection<int>(); myColl.Add(2); myColl.Add(3); myColl.Add(4); myColl.Add(5); // Checking if an element is in the Collection // The function returns "True" if the // item is present in Collection // else returns "False" Console.WriteLine(myColl.Contains(6)); }} Output: False Note: This method performs a linear search. Therefore, this method is an O(n) operation, where n is Count. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.contains?view=netframework-4.7.2 CSharp-Collection-Class CSharp-Collections.ObjectModel-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class HashSet in C# with Examples C# | .NET Framework (Basic Architecture and Component Stack) Switch Statement in C# Partial Classes in C# Lambda Expressions in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2019" }, { "code": null, "e": 126, "s": 28, "text": "Collection<T>.Contains(T) method is used to determine whether an element is in the Collection<T>." }, { "code": null, "e": 134, "s": 126, "text": "Syntax:" }, { "code": null, "e": 166, "s": 134, "text": "public bool Contains (T item);\n" }, { "code": null, "e": 266, "s": 166, "text": "Here, item is the object to locate in the Collection<T>. The value can be null for reference types." }, { "code": null, "e": 361, "s": 266, "text": "Return Value: This method return True if item is found in the Collection<T>, otherwise, False." }, { "code": null, "e": 441, "s": 361, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 452, "s": 441, "text": "Example 1:" }, { "code": "// C# code to check if an// element is in the Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); myColl.Add(\"A\"); myColl.Add(\"B\"); myColl.Add(\"C\"); myColl.Add(\"D\"); myColl.Add(\"E\"); // Checking if an element is in the Collection // The function returns \"True\" if the // item is present in Collection // else returns \"False\" Console.WriteLine(myColl.Contains(\"A\")); }}", "e": 1111, "s": 452, "text": null }, { "code": null, "e": 1119, "s": 1111, "text": "Output:" }, { "code": null, "e": 1125, "s": 1119, "text": "True\n" }, { "code": null, "e": 1136, "s": 1125, "text": "Example 2:" }, { "code": "// C# code to check if an// element is in the Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of ints Collection<int> myColl = new Collection<int>(); myColl.Add(2); myColl.Add(3); myColl.Add(4); myColl.Add(5); // Checking if an element is in the Collection // The function returns \"True\" if the // item is present in Collection // else returns \"False\" Console.WriteLine(myColl.Contains(6)); }}", "e": 1752, "s": 1136, "text": null }, { "code": null, "e": 1760, "s": 1752, "text": "Output:" }, { "code": null, "e": 1767, "s": 1760, "text": "False\n" }, { "code": null, "e": 1874, "s": 1767, "text": "Note: This method performs a linear search. Therefore, this method is an O(n) operation, where n is Count." }, { "code": null, "e": 1885, "s": 1874, "text": "Reference:" }, { "code": null, "e": 2006, "s": 1885, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.contains?view=netframework-4.7.2" }, { "code": null, "e": 2030, "s": 2006, "text": "CSharp-Collection-Class" }, { "code": null, "e": 2071, "s": 2030, "text": "CSharp-Collections.ObjectModel-Namespace" }, { "code": null, "e": 2085, "s": 2071, "text": "CSharp-method" }, { "code": null, "e": 2088, "s": 2085, "text": "C#" }, { "code": null, "e": 2186, "s": 2088, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2229, "s": 2186, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 2278, "s": 2229, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 2301, "s": 2278, "text": "Extension Method in C#" }, { "code": null, "e": 2317, "s": 2301, "text": "C# | List Class" }, { "code": null, "e": 2345, "s": 2317, "text": "HashSet in C# with Examples" }, { "code": null, "e": 2406, "s": 2345, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 2429, "s": 2406, "text": "Switch Statement in C#" }, { "code": null, "e": 2451, "s": 2429, "text": "Partial Classes in C#" }, { "code": null, "e": 2476, "s": 2451, "text": "Lambda Expressions in C#" } ]
\substack - Tex Command
\substack - Used to create multi-line subscripts or superscripts. { \substack} \substack command draws multi-line subscripts or superscripts. \sum_{ \substack{ 1\lt i\lt 3 \\ 1\le j\lt 5 }} a_{ij} ∑1<i<31≤j<5aij ^{\substack{\text{a very} \\ \text{contrived} \\ \text{example} }} {\frac ab}_{\substack{ \text{isn't} \\ \text{it?} }} a verycontrivedexampleabisn'tit? \sum_{ \substack{ 1\lt i\lt 3 \\ 1\le j\lt 5 }} a_{ij} ∑1<i<31≤j<5aij \sum_{ \substack{ 1\lt i\lt 3 \\ 1\le j\lt 5 }} a_{ij} ^{\substack{\text{a very} \\ \text{contrived} \\ \text{example} }} {\frac ab}_{\substack{ \text{isn't} \\ \text{it?} }} a verycontrivedexampleabisn'tit? ^{\substack{\text{a very} \\
[ { "code": null, "e": 8186, "s": 8120, "text": "\\substack - Used to create multi-line subscripts or superscripts." }, { "code": null, "e": 8199, "s": 8186, "text": "{ \\substack}" }, { "code": null, "e": 8262, "s": 8199, "text": "\\substack command draws multi-line subscripts or superscripts." }, { "code": null, "e": 8495, "s": 8262, "text": "\n\\sum_{\n\\substack{\n1\\lt i\\lt 3 \\\\\n1\\le j\\lt 5\n}}\na_{ij}\n\n\n∑1<i<31≤j<5aij\n\n\n^{\\substack{\\text{a very} \\\\\n\\text{contrived} \\\\\n\\text{example}\n}}\n{\\frac ab}_{\\substack{\n\\text{isn't} \\\\\n\\text{it?}\n}}\n\n\na verycontrivedexampleabisn'tit?\n\n\n" }, { "code": null, "e": 8569, "s": 8495, "text": "\\sum_{\n\\substack{\n1\\lt i\\lt 3 \\\\\n1\\le j\\lt 5\n}}\na_{ij}\n\n\n∑1<i<31≤j<5aij\n\n" }, { "code": null, "e": 8625, "s": 8569, "text": "\\sum_{\n\\substack{\n1\\lt i\\lt 3 \\\\\n1\\le j\\lt 5\n}}\na_{ij}\n" }, { "code": null, "e": 8782, "s": 8625, "text": "^{\\substack{\\text{a very} \\\\\n\\text{contrived} \\\\\n\\text{example}\n}}\n{\\frac ab}_{\\substack{\n\\text{isn't} \\\\\n\\text{it?}\n}}\n\n\na verycontrivedexampleabisn'tit?\n\n" } ]
Read a zipped file as a Pandas DataFrame
28 Sep, 2021 In this article, we will try to find out how can we read data from a zip file using a panda data frame. People use related groups of files together and to make files compact, so they are easier and faster to share via the web. Zip files are ideal for archiving since they save storage space. And, they are also useful for securing data using the encryption method. Requirement: zipfile36 module: This module is used to perform various operations on a zip file using a simple python program. It can be installed using the below command: pip install zipfile36 Method #1: Using compression=zip in pandas.read_csv() method. By assigning the compression argument in read_csv() method as zip, then pandas will first decompress the zip and then will create the dataframe from CSV file present in the zipped file. Python3 # import required modulesimport zipfileimport pandas as pd # read the dataset using the compression zipdf = pd.read_csv('test.zip',compression='zip') # display datasetprint(df.head()) Output: Method #2: Opening the zip file to get the CSV file. Here, initially, the zipped file is opened and the CSV file is extracted, and then a dataframe is created from the extracted CSV file. Python3 # import required modulesimport zipfileimport pandas as pd # open zipped datasetwith zipfile.ZipFile("test.zip") as z: # open the csv file in the dataset with z.open("test.csv") as f: # read the dataset train = pd.read_csv(f) # display dataset print(train.head()) Output: surindertarika1234 Python pandas-io Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Sep, 2021" }, { "code": null, "e": 133, "s": 28, "text": "In this article, we will try to find out how can we read data from a zip file using a panda data frame. " }, { "code": null, "e": 394, "s": 133, "text": "People use related groups of files together and to make files compact, so they are easier and faster to share via the web. Zip files are ideal for archiving since they save storage space. And, they are also useful for securing data using the encryption method." }, { "code": null, "e": 408, "s": 394, "text": "Requirement: " }, { "code": null, "e": 566, "s": 408, "text": "zipfile36 module: This module is used to perform various operations on a zip file using a simple python program. It can be installed using the below command:" }, { "code": null, "e": 588, "s": 566, "text": "pip install zipfile36" }, { "code": null, "e": 651, "s": 588, "text": "Method #1: Using compression=zip in pandas.read_csv() method. " }, { "code": null, "e": 838, "s": 651, "text": "By assigning the compression argument in read_csv() method as zip, then pandas will first decompress the zip and then will create the dataframe from CSV file present in the zipped file. " }, { "code": null, "e": 846, "s": 838, "text": "Python3" }, { "code": "# import required modulesimport zipfileimport pandas as pd # read the dataset using the compression zipdf = pd.read_csv('test.zip',compression='zip') # display datasetprint(df.head())", "e": 1030, "s": 846, "text": null }, { "code": null, "e": 1038, "s": 1030, "text": "Output:" }, { "code": null, "e": 1091, "s": 1038, "text": "Method #2: Opening the zip file to get the CSV file." }, { "code": null, "e": 1227, "s": 1091, "text": "Here, initially, the zipped file is opened and the CSV file is extracted, and then a dataframe is created from the extracted CSV file. " }, { "code": null, "e": 1235, "s": 1227, "text": "Python3" }, { "code": "# import required modulesimport zipfileimport pandas as pd # open zipped datasetwith zipfile.ZipFile(\"test.zip\") as z: # open the csv file in the dataset with z.open(\"test.csv\") as f: # read the dataset train = pd.read_csv(f) # display dataset print(train.head())", "e": 1537, "s": 1235, "text": null }, { "code": null, "e": 1545, "s": 1537, "text": "Output:" }, { "code": null, "e": 1564, "s": 1545, "text": "surindertarika1234" }, { "code": null, "e": 1581, "s": 1564, "text": "Python pandas-io" }, { "code": null, "e": 1595, "s": 1581, "text": "Python-pandas" }, { "code": null, "e": 1602, "s": 1595, "text": "Python" }, { "code": null, "e": 1700, "s": 1602, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1732, "s": 1700, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1759, "s": 1732, "text": "Python Classes and Objects" }, { "code": null, "e": 1780, "s": 1759, "text": "Python OOPs Concepts" }, { "code": null, "e": 1803, "s": 1780, "text": "Introduction To PYTHON" }, { "code": null, "e": 1859, "s": 1803, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1890, "s": 1859, "text": "Python | os.path.join() method" }, { "code": null, "e": 1932, "s": 1890, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1974, "s": 1932, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2013, "s": 1974, "text": "Python | Get unique values from a list" } ]
What does .modal(‘dispose’) do in Bootstrap 4 ?
13 Mar, 2020 In Bootstrap 4, .modal(‘dispose’) is a function defined to destroy the modal. The modal remains a part of the DOM even after using .modal(‘dispose’), this function only destroys the current instance of the modal component. Syntax: $("#modalID").modal("dispose"); Example: This example illustrates the use of .modal(‘dispose’) method. When the dispose button is clicked, the jQuery instance of the modal component gets deleted. Hence, none of the other modal functions work after the button has been clicked. <!DOCTYPE html><html lang="en"> <head> <title>Dispose Modal</title> <meta charset="UTF-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"> </script></head> <body> <button id="clickBtn" class="btn btn-primary"> Click Me! </button> <div id="myModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Example Modal</h5> <button id="dismissBtn" type="button" class="close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> Body of the Modal </div> <div class="modal-footer"> <button id="closeBtn" class="btn btn-secondary"> Close </button> <button id="disposeBtn" class="btn btn-secondary"> Dispose </button> </div> </div> </div> </div></body> <script> $(document).ready(function() { $("#clickBtn").click(function() { $("#myModal").modal('show'); }); $("#dismissBtn").click(function() { $("#myModal").modal('hide'); }); $("#closeBtn").click(function() { $("#myModal").modal('hide'); }); $("#disposeBtn").click(function() { $("#myModal").modal('dispose'); }); });</script> </html> Output: Note: To close the modal after using the dispose function, we can modify the above code to hide the modal and remove the fade class along with destroying it. $("#disposeBtn").click(function(){ $("#myModal").removeClass('fade').modal('hide'); $("#myModal").modal("dispose"); }); Bootstrap-Misc Picked Bootstrap Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Mar, 2020" }, { "code": null, "e": 251, "s": 28, "text": "In Bootstrap 4, .modal(‘dispose’) is a function defined to destroy the modal. The modal remains a part of the DOM even after using .modal(‘dispose’), this function only destroys the current instance of the modal component." }, { "code": null, "e": 259, "s": 251, "text": "Syntax:" }, { "code": null, "e": 291, "s": 259, "text": "$(\"#modalID\").modal(\"dispose\");" }, { "code": null, "e": 536, "s": 291, "text": "Example: This example illustrates the use of .modal(‘dispose’) method. When the dispose button is clicked, the jQuery instance of the modal component gets deleted. Hence, none of the other modal functions work after the button has been clicked." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Dispose Modal</title> <meta charset=\"UTF-8\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js\"> </script></head> <body> <button id=\"clickBtn\" class=\"btn btn-primary\"> Click Me! </button> <div id=\"myModal\" class=\"modal fade\"> <div class=\"modal-dialog\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h5 class=\"modal-title\">Example Modal</h5> <button id=\"dismissBtn\" type=\"button\" class=\"close\"> <span aria-hidden=\"true\">×</span> </button> </div> <div class=\"modal-body\"> Body of the Modal </div> <div class=\"modal-footer\"> <button id=\"closeBtn\" class=\"btn btn-secondary\"> Close </button> <button id=\"disposeBtn\" class=\"btn btn-secondary\"> Dispose </button> </div> </div> </div> </div></body> <script> $(document).ready(function() { $(\"#clickBtn\").click(function() { $(\"#myModal\").modal('show'); }); $(\"#dismissBtn\").click(function() { $(\"#myModal\").modal('hide'); }); $(\"#closeBtn\").click(function() { $(\"#myModal\").modal('hide'); }); $(\"#disposeBtn\").click(function() { $(\"#myModal\").modal('dispose'); }); });</script> </html>", "e": 2557, "s": 536, "text": null }, { "code": null, "e": 2565, "s": 2557, "text": "Output:" }, { "code": null, "e": 2723, "s": 2565, "text": "Note: To close the modal after using the dispose function, we can modify the above code to hide the modal and remove the fade class along with destroying it." }, { "code": null, "e": 2854, "s": 2723, "text": "$(\"#disposeBtn\").click(function(){\n $(\"#myModal\").removeClass('fade').modal('hide');\n $(\"#myModal\").modal(\"dispose\");\n});\n" }, { "code": null, "e": 2869, "s": 2854, "text": "Bootstrap-Misc" }, { "code": null, "e": 2876, "s": 2869, "text": "Picked" }, { "code": null, "e": 2886, "s": 2876, "text": "Bootstrap" }, { "code": null, "e": 2903, "s": 2886, "text": "Web Technologies" }, { "code": null, "e": 2930, "s": 2903, "text": "Web technologies Questions" } ]
How to set the Background Color of a ListBox in C#?
11 Jul, 2019 In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. In ListBox, you are allowed to set the background color of the ListBox using BackColor Property of the ListBox which makes your ListBox more attractive. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the background color of the ListBox as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the ListBox control from the ToolBox and drop it on the windows form. You are allowed to place a ListBox control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the ListBox control to set the background color of the ListBox.Output: Output: 2. RunTime: It is a little bit trickier than the above method. In this method, you can set the background color of the ListBox control programmatically with the help of given syntax: public override System.Drawing.Color BackColor { get; set; } Here, Color indicates the background color of the ListBox. The following steps show how to set the background color of the ListBox dynamically: Step 1: Create a list box using the ListBox() constructor is provided by the ListBox class.// Creating ListBox using // ListBox class constructor ListBox mylist = new ListBox(); // Creating ListBox using // ListBox class constructor ListBox mylist = new ListBox(); Step 2: After creating ListBox, set the BackColor Property of the ListBox provided by the ListBox class.// Setting the background color mylist.BackColor = Color.LightCyan; // Setting the background color mylist.BackColor = Color.LightCyan; Step 3: And last add this ListBox control to the form using Add() method.// Add this ListBox to the form this.Controls.Add(mylist); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.BackColor = Color.LightCyan; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox // control to the form this.Controls.Add(mylist); }}}Output: // Add this ListBox to the form this.Controls.Add(mylist); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.BackColor = Color.LightCyan; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox // control to the form this.Controls.Add(mylist); }}} Output: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Introduction to .NET Framework Differences Between .NET Core and .NET Framework C# | Delegates C# | Data Types C# | String.IndexOf( ) Method | Set - 1 C# | Constructors C# | Class and Object C# | Replace() Method C# | Arrays
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jul, 2019" }, { "code": null, "e": 421, "s": 28, "text": "In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. In ListBox, you are allowed to set the background color of the ListBox using BackColor Property of the ListBox which makes your ListBox more attractive. You can set this property in two different ways:" }, { "code": null, "e": 535, "s": 421, "text": "1. Design-Time: It is the easiest way to set the background color of the ListBox as shown in the following steps:" }, { "code": null, "e": 651, "s": 535, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 709, "s": 651, "text": "Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 888, "s": 709, "text": "Step 2: Drag the ListBox control from the ToolBox and drop it on the windows form. You are allowed to place a ListBox control anywhere on the windows form according to your need." }, { "code": null, "e": 1020, "s": 888, "text": "Step 3: After drag and drop you will go to the properties of the ListBox control to set the background color of the ListBox.Output:" }, { "code": null, "e": 1028, "s": 1020, "text": "Output:" }, { "code": null, "e": 1211, "s": 1028, "text": "2. RunTime: It is a little bit trickier than the above method. In this method, you can set the background color of the ListBox control programmatically with the help of given syntax:" }, { "code": null, "e": 1272, "s": 1211, "text": "public override System.Drawing.Color BackColor { get; set; }" }, { "code": null, "e": 1416, "s": 1272, "text": "Here, Color indicates the background color of the ListBox. The following steps show how to set the background color of the ListBox dynamically:" }, { "code": null, "e": 1596, "s": 1416, "text": "Step 1: Create a list box using the ListBox() constructor is provided by the ListBox class.// Creating ListBox using \n// ListBox class constructor\nListBox mylist = new ListBox();\n" }, { "code": null, "e": 1685, "s": 1596, "text": "// Creating ListBox using \n// ListBox class constructor\nListBox mylist = new ListBox();\n" }, { "code": null, "e": 1858, "s": 1685, "text": "Step 2: After creating ListBox, set the BackColor Property of the ListBox provided by the ListBox class.// Setting the background color\nmylist.BackColor = Color.LightCyan;\n" }, { "code": null, "e": 1927, "s": 1858, "text": "// Setting the background color\nmylist.BackColor = Color.LightCyan;\n" }, { "code": null, "e": 2901, "s": 1927, "text": "Step 3: And last add this ListBox control to the form using Add() method.// Add this ListBox to the form\nthis.Controls.Add(mylist);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.BackColor = Color.LightCyan; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox // control to the form this.Controls.Add(mylist); }}}Output:" }, { "code": null, "e": 2961, "s": 2901, "text": "// Add this ListBox to the form\nthis.Controls.Add(mylist);\n" }, { "code": null, "e": 2970, "s": 2961, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.BackColor = Color.LightCyan; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox // control to the form this.Controls.Add(mylist); }}}", "e": 3797, "s": 2970, "text": null }, { "code": null, "e": 3805, "s": 3797, "text": "Output:" }, { "code": null, "e": 3808, "s": 3805, "text": "C#" }, { "code": null, "e": 3906, "s": 3808, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3949, "s": 3906, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 3980, "s": 3949, "text": "Introduction to .NET Framework" }, { "code": null, "e": 4029, "s": 3980, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 4044, "s": 4029, "text": "C# | Delegates" }, { "code": null, "e": 4060, "s": 4044, "text": "C# | Data Types" }, { "code": null, "e": 4100, "s": 4060, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 4118, "s": 4100, "text": "C# | Constructors" }, { "code": null, "e": 4140, "s": 4118, "text": "C# | Class and Object" }, { "code": null, "e": 4162, "s": 4140, "text": "C# | Replace() Method" } ]
Converting Color video to grayscale using OpenCV in Python
20 Oct, 2021 OpenCV is a huge open-source library for computer vision, machine learning, and image processing. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will see how to convert a colored video to a gray-scale format. Approach: Import the cv2 module.Read the video file to be converted using the cv2.VideoCapture() method.Run an infinite loop.Inside the loop extract the frames of the video using the read() method.Pass the frame to the cv2.cvtColor() method with cv2.COLOR_BGR2GRAY as a parameter to convert it into gray-scale.Display the frame using the cv2.imshow() method. Import the cv2 module. Read the video file to be converted using the cv2.VideoCapture() method. Run an infinite loop. Inside the loop extract the frames of the video using the read() method. Pass the frame to the cv2.cvtColor() method with cv2.COLOR_BGR2GRAY as a parameter to convert it into gray-scale. Display the frame using the cv2.imshow() method. Example: Suppose we have the video file CountdownTimer.mov as the input. Python3 # importing the moduleimport cv2 # reading the videosource = cv2.VideoCapture('Countdown Timer.mov') # running the loopwhile True: # extracting the frames ret, img = source.read() # converting to gray-scale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # displaying the video cv2.imshow("Live", gray) # exiting the loop key = cv2.waitKey(1) if key == ord("q"): break # closing the windowcv2.destroyAllWindows()source.release() Output: simmytarika5 Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts 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": "\n20 Oct, 2021" }, { "code": null, "e": 307, "s": 28, "text": "OpenCV is a huge open-source library for computer vision, machine learning, and image processing. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will see how to convert a colored video to a gray-scale format." }, { "code": null, "e": 317, "s": 307, "text": "Approach:" }, { "code": null, "e": 666, "s": 317, "text": "Import the cv2 module.Read the video file to be converted using the cv2.VideoCapture() method.Run an infinite loop.Inside the loop extract the frames of the video using the read() method.Pass the frame to the cv2.cvtColor() method with cv2.COLOR_BGR2GRAY as a parameter to convert it into gray-scale.Display the frame using the cv2.imshow() method." }, { "code": null, "e": 689, "s": 666, "text": "Import the cv2 module." }, { "code": null, "e": 762, "s": 689, "text": "Read the video file to be converted using the cv2.VideoCapture() method." }, { "code": null, "e": 784, "s": 762, "text": "Run an infinite loop." }, { "code": null, "e": 857, "s": 784, "text": "Inside the loop extract the frames of the video using the read() method." }, { "code": null, "e": 971, "s": 857, "text": "Pass the frame to the cv2.cvtColor() method with cv2.COLOR_BGR2GRAY as a parameter to convert it into gray-scale." }, { "code": null, "e": 1020, "s": 971, "text": "Display the frame using the cv2.imshow() method." }, { "code": null, "e": 1093, "s": 1020, "text": "Example: Suppose we have the video file CountdownTimer.mov as the input." }, { "code": null, "e": 1101, "s": 1093, "text": "Python3" }, { "code": "# importing the moduleimport cv2 # reading the videosource = cv2.VideoCapture('Countdown Timer.mov') # running the loopwhile True: # extracting the frames ret, img = source.read() # converting to gray-scale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # displaying the video cv2.imshow(\"Live\", gray) # exiting the loop key = cv2.waitKey(1) if key == ord(\"q\"): break # closing the windowcv2.destroyAllWindows()source.release()", "e": 1573, "s": 1101, "text": null }, { "code": null, "e": 1585, "s": 1577, "text": "Output:" }, { "code": null, "e": 1602, "s": 1589, "text": "simmytarika5" }, { "code": null, "e": 1616, "s": 1602, "text": "Python-OpenCV" }, { "code": null, "e": 1623, "s": 1616, "text": "Python" }, { "code": null, "e": 1721, "s": 1623, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1753, "s": 1721, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1780, "s": 1753, "text": "Python Classes and Objects" }, { "code": null, "e": 1811, "s": 1780, "text": "Python | os.path.join() method" }, { "code": null, "e": 1834, "s": 1811, "text": "Introduction To PYTHON" }, { "code": null, "e": 1855, "s": 1834, "text": "Python OOPs Concepts" }, { "code": null, "e": 1911, "s": 1855, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1953, "s": 1911, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1995, "s": 1953, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2034, "s": 1995, "text": "Python | Get unique values from a list" } ]
Matplotlib.axes.Axes.streamplot() in Python
16 Jun, 2022 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.streamplot() function in axes module of matplotlib library is also used to draw streamlines of a vector flow.. Syntax: Axes.streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None, cmap=None, norm=None, arrowsize=1, arrowstyle=’-|>’, minlength=0.1, transform=None, zorder=None, start_points=None, maxlength=4.0, integration_direction=’both’, *, data=None) Parameters: This method accept the following parameters that are described below: X, Y : These parameter are the x and y coordinates of the evenly spaced grid. U, V: This parameter is the number of rows and columns must match the length of y and x. density : This parameter is used to controls the closeness of streamlines. linewidth : This parameter is the width of the stream lines. color : This parameter is the streamline color. cmap : This parameter is used to plot streamlines and arrows. norm : This parameter is used to normalize object used to scale luminance data to 0, 1. arrowsize : This parameter is the scaling factor for the arrow size. minlength : This parameter is the minimum length of streamline in axes coordinates.. maxlength : This parameter is the maximum length of streamline in axes coordinates. zorder : This parameter is the zorder of the stream lines and arrows. Returns:This method returns the following: stream_container :This returns the StreamplotSet Container object with attributes Below examples illustrate the matplotlib.axes.Axes.streamplot() function in matplotlib.axes: Example 1: Python3 # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2), np.arange(0, 2 * np.pi, .2))U = np.cos(X**2)V = np.sin(Y**2) fig, ax = plt.subplots()ax.streamplot(X, Y, U, V, density =[0.5, 1]) ax.set_title('matplotlib.axes.Axes.streamplot()\ Example\n', fontsize = 14, fontweight ='bold')plt.show() Output: Example 2: Python3 # Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2), np.arange(0, 2 * np.pi, .2))U = np.cos(X**2)V = np.sin(Y**2) fig, (ax, ax1)= plt.subplots(nrows = 2, ncols = 1)ax.streamplot(X, Y, U, V, density =[0.5, 1], color = V * U, linewidth = 2, cmap ='autumn')val = np.array([[2, 1, 0, 1, 2, 1], [2, 1, 0, 1, 2, 2]]) ax1.streamplot(X, Y, U, V, color = V * U, linewidth = 2, cmap ='autumn', start_points = val.T) ax.set_title('matplotlib.axes.Axes.streamplot() \Example\n', fontsize = 14, fontweight ='bold')plt.show() Output: surinderdawra388 Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jun, 2022" }, { "code": null, "e": 328, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 448, "s": 328, "text": "The Axes.streamplot() function in axes module of matplotlib library is also used to draw streamlines of a vector flow.." }, { "code": null, "e": 786, "s": 448, "text": "Syntax: Axes.streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None, cmap=None, norm=None, arrowsize=1, arrowstyle=’-|>’, minlength=0.1, transform=None, zorder=None, start_points=None, maxlength=4.0, integration_direction=’both’, *, data=None) Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 864, "s": 786, "text": "X, Y : These parameter are the x and y coordinates of the evenly spaced grid." }, { "code": null, "e": 953, "s": 864, "text": "U, V: This parameter is the number of rows and columns must match the length of y and x." }, { "code": null, "e": 1028, "s": 953, "text": "density : This parameter is used to controls the closeness of streamlines." }, { "code": null, "e": 1089, "s": 1028, "text": "linewidth : This parameter is the width of the stream lines." }, { "code": null, "e": 1137, "s": 1089, "text": "color : This parameter is the streamline color." }, { "code": null, "e": 1199, "s": 1137, "text": "cmap : This parameter is used to plot streamlines and arrows." }, { "code": null, "e": 1287, "s": 1199, "text": "norm : This parameter is used to normalize object used to scale luminance data to 0, 1." }, { "code": null, "e": 1356, "s": 1287, "text": "arrowsize : This parameter is the scaling factor for the arrow size." }, { "code": null, "e": 1441, "s": 1356, "text": "minlength : This parameter is the minimum length of streamline in axes coordinates.." }, { "code": null, "e": 1525, "s": 1441, "text": "maxlength : This parameter is the maximum length of streamline in axes coordinates." }, { "code": null, "e": 1595, "s": 1525, "text": "zorder : This parameter is the zorder of the stream lines and arrows." }, { "code": null, "e": 1638, "s": 1595, "text": "Returns:This method returns the following:" }, { "code": null, "e": 1720, "s": 1638, "text": "stream_container :This returns the StreamplotSet Container object with attributes" }, { "code": null, "e": 1825, "s": 1720, "text": "Below examples illustrate the matplotlib.axes.Axes.streamplot() function in matplotlib.axes: Example 1: " }, { "code": null, "e": 1833, "s": 1825, "text": "Python3" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2), np.arange(0, 2 * np.pi, .2))U = np.cos(X**2)V = np.sin(Y**2) fig, ax = plt.subplots()ax.streamplot(X, Y, U, V, density =[0.5, 1]) ax.set_title('matplotlib.axes.Axes.streamplot()\\ Example\\n', fontsize = 14, fontweight ='bold')plt.show()", "e": 2229, "s": 1833, "text": null }, { "code": null, "e": 2250, "s": 2229, "text": "Output: Example 2: " }, { "code": null, "e": 2258, "s": 2250, "text": "Python3" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2), np.arange(0, 2 * np.pi, .2))U = np.cos(X**2)V = np.sin(Y**2) fig, (ax, ax1)= plt.subplots(nrows = 2, ncols = 1)ax.streamplot(X, Y, U, V, density =[0.5, 1], color = V * U, linewidth = 2, cmap ='autumn')val = np.array([[2, 1, 0, 1, 2, 1], [2, 1, 0, 1, 2, 2]]) ax1.streamplot(X, Y, U, V, color = V * U, linewidth = 2, cmap ='autumn', start_points = val.T) ax.set_title('matplotlib.axes.Axes.streamplot() \\Example\\n', fontsize = 14, fontweight ='bold')plt.show()", "e": 2947, "s": 2258, "text": null }, { "code": null, "e": 2956, "s": 2947, "text": "Output: " }, { "code": null, "e": 2973, "s": 2956, "text": "surinderdawra388" }, { "code": null, "e": 2991, "s": 2973, "text": "Python-matplotlib" }, { "code": null, "e": 2998, "s": 2991, "text": "Python" } ]
Java Program to Print Right Triangle Star Pattern
09 Mar, 2021 In this article, we will learn about printing Right Triangle Star Pattern. Examples: Input : n = 5 Output: * * * * * * * * * * * * * * * Right Triangle Star Pattern: Java import java.io.*; // Java code to demonstrate right star trianglepublic class GeeksForGeeks { // Function to demonstrate printing pattern public static void StarRightTriangle(int n) { int a, b; // outer loop to handle number of rows // k in this case for (a = 0; a < n; a++) { // inner loop to handle number of columns // values changing acc. to outer loop for (b = 0; b <= a; b++) { // printing stars System.out.print("* "); } // end-line System.out.println(); } } // Driver Function public static void main(String args[]) { int k = 5; StarRightTriangle(k); }} * * * * * * * * * * * * * * * Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Mar, 2021" }, { "code": null, "e": 129, "s": 54, "text": "In this article, we will learn about printing Right Triangle Star Pattern." }, { "code": null, "e": 139, "s": 129, "text": "Examples:" }, { "code": null, "e": 198, "s": 139, "text": "Input : n = 5\nOutput: \n* \n* * \n* * * \n* * * * \n* * * * * " }, { "code": null, "e": 227, "s": 198, "text": "Right Triangle Star Pattern:" }, { "code": null, "e": 232, "s": 227, "text": "Java" }, { "code": "import java.io.*; // Java code to demonstrate right star trianglepublic class GeeksForGeeks { // Function to demonstrate printing pattern public static void StarRightTriangle(int n) { int a, b; // outer loop to handle number of rows // k in this case for (a = 0; a < n; a++) { // inner loop to handle number of columns // values changing acc. to outer loop for (b = 0; b <= a; b++) { // printing stars System.out.print(\"* \"); } // end-line System.out.println(); } } // Driver Function public static void main(String args[]) { int k = 5; StarRightTriangle(k); }}", "e": 972, "s": 232, "text": null }, { "code": null, "e": 1007, "s": 972, "text": "* \n* * \n* * * \n* * * * \n* * * * * " }, { "code": null, "e": 1014, "s": 1007, "text": "Picked" }, { "code": null, "e": 1019, "s": 1014, "text": "Java" }, { "code": null, "e": 1033, "s": 1019, "text": "Java Programs" }, { "code": null, "e": 1038, "s": 1033, "text": "Java" } ]
Difference between data type and data structure
27 Dec, 2019 Data Type A data type is the most basic and the most common classification of data. It is this through which the compiler gets to know the form or the type of information that will be used throughout the code. So basically data type is a type of information transmitted between the programmer and the compiler where the programmer informs the compiler about what type of data is to be stored and also tells how much space it requires in the memory. Some basic examples are int, string etc. It is the type of any variable used in the code. #include <iostream.h>using namespace std; void main(){ int a; a = 5; float b; b = 5.0; char c; c = 'A'; char d[10]; d = "example";} As seen from the theory explained above we come to know that in the above code, the variable ‘a’ is of data type integer which is denoted by int a. So the variable ‘a’ will be used as an integer type variable throughout the process of the code. And, in the same way, the variables ‘b’, ‘c’ and ‘d’ are of type float, character and string respectively. And all these are kinds of data types. Data Structure A data structure is a collection of different forms and different types of data that has a set of specific operations that can be performed. It is a collection of data types. It is a way of organizing the items in terms of memory, and also the way of accessing each item through some defined logic. Some examples of data structures are stacks, queues, linked lists, binary tree and many more. Data structures perform some special operations only like insertion, deletion and traversal. For example, you have to store data for many employees where each employee has his name, employee id and a mobile number. So this kind of data requires complex data management, which means it requires data structure comprised of multiple primitive data types. So data structures are one of the most important aspects when implementing coding concepts in real-world applications. Difference between data type and data structure: HarshitHiremath Picked Data Structures Difference Between Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Advantages and Disadvantages of Linked List Data Structures | Array | Question 2 Data Structures | Binary Search Trees | Question 8 Data Structures | Queue | Question 2 Class method vs Static method in Python Difference between BFS and DFS Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Dec, 2019" }, { "code": null, "e": 64, "s": 54, "text": "Data Type" }, { "code": null, "e": 593, "s": 64, "text": "A data type is the most basic and the most common classification of data. It is this through which the compiler gets to know the form or the type of information that will be used throughout the code. So basically data type is a type of information transmitted between the programmer and the compiler where the programmer informs the compiler about what type of data is to be stored and also tells how much space it requires in the memory. Some basic examples are int, string etc. It is the type of any variable used in the code." }, { "code": "#include <iostream.h>using namespace std; void main(){ int a; a = 5; float b; b = 5.0; char c; c = 'A'; char d[10]; d = \"example\";}", "e": 756, "s": 593, "text": null }, { "code": null, "e": 1147, "s": 756, "text": "As seen from the theory explained above we come to know that in the above code, the variable ‘a’ is of data type integer which is denoted by int a. So the variable ‘a’ will be used as an integer type variable throughout the process of the code. And, in the same way, the variables ‘b’, ‘c’ and ‘d’ are of type float, character and string respectively. And all these are kinds of data types." }, { "code": null, "e": 1162, "s": 1147, "text": "Data Structure" }, { "code": null, "e": 1555, "s": 1162, "text": "A data structure is a collection of different forms and different types of data that has a set of specific operations that can be performed. It is a collection of data types. It is a way of organizing the items in terms of memory, and also the way of accessing each item through some defined logic. Some examples of data structures are stacks, queues, linked lists, binary tree and many more." }, { "code": null, "e": 2027, "s": 1555, "text": "Data structures perform some special operations only like insertion, deletion and traversal. For example, you have to store data for many employees where each employee has his name, employee id and a mobile number. So this kind of data requires complex data management, which means it requires data structure comprised of multiple primitive data types. So data structures are one of the most important aspects when implementing coding concepts in real-world applications." }, { "code": null, "e": 2076, "s": 2027, "text": "Difference between data type and data structure:" }, { "code": null, "e": 2092, "s": 2076, "text": "HarshitHiremath" }, { "code": null, "e": 2099, "s": 2092, "text": "Picked" }, { "code": null, "e": 2115, "s": 2099, "text": "Data Structures" }, { "code": null, "e": 2134, "s": 2115, "text": "Difference Between" }, { "code": null, "e": 2150, "s": 2134, "text": "Data Structures" }, { "code": null, "e": 2248, "s": 2150, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2280, "s": 2248, "text": "Introduction to Data Structures" }, { "code": null, "e": 2324, "s": 2280, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 2361, "s": 2324, "text": "Data Structures | Array | Question 2" }, { "code": null, "e": 2412, "s": 2361, "text": "Data Structures | Binary Search Trees | Question 8" }, { "code": null, "e": 2449, "s": 2412, "text": "Data Structures | Queue | Question 2" }, { "code": null, "e": 2489, "s": 2449, "text": "Class method vs Static method in Python" }, { "code": null, "e": 2520, "s": 2489, "text": "Difference between BFS and DFS" }, { "code": null, "e": 2581, "s": 2520, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2649, "s": 2581, "text": "Difference Between Method Overloading and Method Overriding in Java" } ]
Python program to split and join a string?
Python program provides built in function for string joining and split of a string. split Str.split() join Str1.join(str2) Step 1: Input a string. Step 2: here we use split method for splitting and for joining use join function. Step 3: display output. #split of string str1=input("Enter first String with space :: ") print(str1.split()) #splits at space str2=input("Enter second String with (,) :: ") print(str2.split(',')) #splits at ',' str3=input("Enter third String with (:) :: ") print(str3.split(':')) #splits at ':' str4=input("Enter fourth String with (;) :: ") print(str4.split(';')) #splits at ';' str5=input("Enter fifth String without space :: ") print([str5[i:i+2]for i in range(0,len(str5),2)]) #splits at position 2 Enter first String with space :: python program ['python', 'program'] Enter second String with (,) :: python, program ['python', 'program'] Enter third String with (:) :: python: program ['python', 'program'] Enter fourth String with (;) :: python; program ['python', 'program'] Enter fifth String without space :: python program ['py', 'th', 'on', 'pr', 'og', 'ra', 'm'] #string joining str1=input("Enter first String :: ") str2=input("Enter second String :: ") str=str2.join(str1) #each character of str1 is concatenated to the #front of str2 print(“AFTER JOINING OF TWO STRING ::>”,str) Enter first String :: AAA Enter second String :: BBB AFTER JOINING OF TWO STRING ::>ABBBABBBA
[ { "code": null, "e": 1271, "s": 1187, "text": "Python program provides built in function for string joining and split of a string." }, { "code": null, "e": 1311, "s": 1271, "text": "split\nStr.split()\njoin\nStr1.join(str2)\n" }, { "code": null, "e": 1442, "s": 1311, "text": "Step 1: Input a string.\nStep 2: here we use split method for splitting and for joining use join function.\nStep 3: display output.\n" }, { "code": null, "e": 1940, "s": 1442, "text": "#split of string\nstr1=input(\"Enter first String with space :: \")\nprint(str1.split()) #splits at space\n\nstr2=input(\"Enter second String with (,) :: \")\nprint(str2.split(',')) #splits at ','\n\nstr3=input(\"Enter third String with (:) :: \")\nprint(str3.split(':')) #splits at ':'\n\nstr4=input(\"Enter fourth String with (;) :: \")\nprint(str4.split(';')) #splits at ';'\n\nstr5=input(\"Enter fifth String without space :: \")\nprint([str5[i:i+2]for i in range(0,len(str5),2)]) #splits at position 2" }, { "code": null, "e": 2313, "s": 1940, "text": "Enter first String with space :: python program\n['python', 'program']\nEnter second String with (,) :: python, program\n['python', 'program']\nEnter third String with (:) :: python: program\n['python', 'program']\nEnter fourth String with (;) :: python; program\n['python', 'program']\nEnter fifth String without space :: python program\n['py', 'th', 'on', 'pr', 'og', 'ra', 'm']\n" }, { "code": null, "e": 2538, "s": 2313, "text": "#string joining\nstr1=input(\"Enter first String :: \")\nstr2=input(\"Enter second String :: \")\nstr=str2.join(str1) #each character of str1 is concatenated to the #front of str2\nprint(“AFTER JOINING OF TWO STRING ::>”,str)" }, { "code": null, "e": 2636, "s": 2538, "text": "Enter first String :: AAA\nEnter second String :: BBB\nAFTER JOINING OF TWO STRING ::>ABBBABBBA\n" } ]
How to autoplay audio on chrome ?
05 Jun, 2020 Here we will learn how to auto-play audio on selected devices in web pages. To load the audio in the web page, we use the <audio> tag. There are some attribute of this “audio” tag: controls: This feature is used for audio be visible the controls on the web pages. After using this feature, we can pause or play music, high or low music. autoplay: This feature is used for audio to start audio clip when page load. If you run a web page, the audio file will load and just the audio will play automatically. Example: <!DOCTYPE html> <html> <head> <title> HTML audio autoplay Attribute </title> </head> <body style="text-align: center"> <h1 style="color: green"> GeeksforGeeks </h1> <h2>HTML audio autoplay Attribute</h2> <audio controls autoplay> <source src="GFG.ogg" type="audio/ogg"> <source src="GFG.mp3" type="audio/mpeg"> </audio> </body> </html> Output: HTML-Misc HTML5 Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2020" }, { "code": null, "e": 163, "s": 28, "text": "Here we will learn how to auto-play audio on selected devices in web pages. To load the audio in the web page, we use the <audio> tag." }, { "code": null, "e": 209, "s": 163, "text": "There are some attribute of this “audio” tag:" }, { "code": null, "e": 365, "s": 209, "text": "controls: This feature is used for audio be visible the controls on the web pages. After using this feature, we can pause or play music, high or low music." }, { "code": null, "e": 534, "s": 365, "text": "autoplay: This feature is used for audio to start audio clip when page load. If you run a web page, the audio file will load and just the audio will play automatically." }, { "code": null, "e": 543, "s": 534, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML audio autoplay Attribute </title> </head> <body style=\"text-align: center\"> <h1 style=\"color: green\"> GeeksforGeeks </h1> <h2>HTML audio autoplay Attribute</h2> <audio controls autoplay> <source src=\"GFG.ogg\" type=\"audio/ogg\"> <source src=\"GFG.mp3\" type=\"audio/mpeg\"> </audio> </body> </html>", "e": 955, "s": 543, "text": null }, { "code": null, "e": 963, "s": 955, "text": "Output:" }, { "code": null, "e": 973, "s": 963, "text": "HTML-Misc" }, { "code": null, "e": 979, "s": 973, "text": "HTML5" }, { "code": null, "e": 986, "s": 979, "text": "Picked" }, { "code": null, "e": 991, "s": 986, "text": "HTML" }, { "code": null, "e": 1008, "s": 991, "text": "Web Technologies" }, { "code": null, "e": 1013, "s": 1008, "text": "HTML" } ]
Output of Java Programs | Set 42 (Arrays)
29 Sep, 2017 Prerequisite : Java Arrays Question 1. What is the output of this question? class Test1 {public static void main(String[] args) { int arr[] = new int[5]; int arr2[] = new int['a']; byte bt = 10; int arr3[] = new int[bt]; System.out.println(arr.length); System.out.println(arr2.length); System.out.println(arr3.length); }} OptionA) ErrorB) Runtime ExceptionC) 59710D) 56510 Output: C Explanation : To specify array size allowed data type are – byte, short, int, char and all of these are valid data types here. Question 2. What is the output of this question? class Test2 {public static void main(String[] args) { int a[] = new int[5]; // line 1 int[] a11 = new int[]; // line 2 }} OptionA) ErrorB) ExceptionC) Run successfullyD) None Output: A Explanation : One Dimension array have size declaration as compulsory feature. Error : array dimension missing int []a11 = new int[]; // line 2 Question 3. Which of the following declarations are invalid? class Test3 {public static void main(String[] args) { int[][] arr1 = new int[2][3]; // Line 1 int[][] arr2 = new int[2][]; // line 2 int[][] arr3 = new int[][]; // line 3 int[][] arr4 = new int[][2]; // line 4 }} OptionA) AllB) line 1, 3, 4C) line 3, 4D) line 2, 3, 4 Output: C Explanation : First two declarations are allowed and so no error. line 3 and 4 have zero and last dimension respectively.error: array dimension missing int [][]arr3=new int[][];//line 3 ^ error: ']' expected int [][]arr4=new int[][2];//line 4 ^ error: ';' expected int [][]arr4=new int[][2];//line 4 Question 4. Which of the following lines give error? class Test4 {public static void main(String[] args) { int[][][] arr1 = new int[1][2][3]; // Line 1 int[][][] arr2 = new int[1][2][]; // Line 2 int[][][] arr3 = new int[2][][]; // Line 3 int[][][] arr4 = new int[][][]; // Line 4 int[][][] arr5 = new int[][2][3]; // Line 5 int[][][] arr6 = new int[][][3]; // Line 6 int[][][] arr7 = new int[][2][]; // Line 7 }} OptionA) line 4, 5, 6, 7B) AllC) No ErrorD) line 4, 7 Output: A Explanation : In three dimensional array have first two dimension declaration is compulsory other wise we will get compile time error:illegal startup expression. Question 5. What is the output of this question? class Test5 {public static void main(String[] args) { int arr[] = new int[5]; System.out.println(arr); System.out.println(arr[0]); }} OptionA) 00B)[I@6bc7c0540C) 0 0 0 0 00D) none Output: B Explanation : arr : It is giving the base address of arrayarr[0] : It is giving value of array element at 0th location. This article is contributed by Shivakant Jaiswal. 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-Arrays Java-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Output of Java Programs | Set 12 Output of C programs | Set 59 (Loops and Control Statements) unsigned specifier (%u) in C with Examples Output of C++ Program | Set 2 How to show full column content in a PySpark Dataframe ? Output of C programs | Set 31 (Pointers) Output of C programs | Set 35 (Loops) Output of C programs | Set 64 (Pointers) Output of Java Programs | Set 14 (Constructors) Output of C Programs | Set 5
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Sep, 2017" }, { "code": null, "e": 81, "s": 54, "text": "Prerequisite : Java Arrays" }, { "code": null, "e": 130, "s": 81, "text": "Question 1. What is the output of this question?" }, { "code": "class Test1 {public static void main(String[] args) { int arr[] = new int[5]; int arr2[] = new int['a']; byte bt = 10; int arr3[] = new int[bt]; System.out.println(arr.length); System.out.println(arr2.length); System.out.println(arr3.length); }}", "e": 434, "s": 130, "text": null }, { "code": null, "e": 485, "s": 434, "text": "OptionA) ErrorB) Runtime ExceptionC) 59710D) 56510" }, { "code": null, "e": 496, "s": 485, "text": "Output: C\n" }, { "code": null, "e": 623, "s": 496, "text": "Explanation : To specify array size allowed data type are – byte, short, int, char and all of these are valid data types here." }, { "code": null, "e": 672, "s": 623, "text": "Question 2. What is the output of this question?" }, { "code": "class Test2 {public static void main(String[] args) { int a[] = new int[5]; // line 1 int[] a11 = new int[]; // line 2 }}", "e": 817, "s": 672, "text": null }, { "code": null, "e": 870, "s": 817, "text": "OptionA) ErrorB) ExceptionC) Run successfullyD) None" }, { "code": null, "e": 881, "s": 870, "text": "Output: A\n" }, { "code": null, "e": 960, "s": 881, "text": "Explanation : One Dimension array have size declaration as compulsory feature." }, { "code": null, "e": 1025, "s": 960, "text": "Error : array dimension missing\nint []a11 = new int[]; // line 2" }, { "code": null, "e": 1086, "s": 1025, "text": "Question 3. Which of the following declarations are invalid?" }, { "code": "class Test3 {public static void main(String[] args) { int[][] arr1 = new int[2][3]; // Line 1 int[][] arr2 = new int[2][]; // line 2 int[][] arr3 = new int[][]; // line 3 int[][] arr4 = new int[][2]; // line 4 }}", "e": 1336, "s": 1086, "text": null }, { "code": null, "e": 1391, "s": 1336, "text": "OptionA) AllB) line 1, 3, 4C) line 3, 4D) line 2, 3, 4" }, { "code": null, "e": 1402, "s": 1391, "text": "Output: C\n" }, { "code": null, "e": 1554, "s": 1402, "text": "Explanation : First two declarations are allowed and so no error. line 3 and 4 have zero and last dimension respectively.error: array dimension missing" }, { "code": null, "e": 1757, "s": 1554, "text": "int [][]arr3=new int[][];//line 3\n ^\nerror: ']' expected\n int [][]arr4=new int[][2];//line 4\n ^\nerror: ';' expected\n int [][]arr4=new int[][2];//line 4" }, { "code": null, "e": 1810, "s": 1757, "text": "Question 4. Which of the following lines give error?" }, { "code": "class Test4 {public static void main(String[] args) { int[][][] arr1 = new int[1][2][3]; // Line 1 int[][][] arr2 = new int[1][2][]; // Line 2 int[][][] arr3 = new int[2][][]; // Line 3 int[][][] arr4 = new int[][][]; // Line 4 int[][][] arr5 = new int[][2][3]; // Line 5 int[][][] arr6 = new int[][][3]; // Line 6 int[][][] arr7 = new int[][2][]; // Line 7 }}", "e": 2229, "s": 1810, "text": null }, { "code": null, "e": 2283, "s": 2229, "text": "OptionA) line 4, 5, 6, 7B) AllC) No ErrorD) line 4, 7" }, { "code": null, "e": 2294, "s": 2283, "text": "Output: A\n" }, { "code": null, "e": 2456, "s": 2294, "text": "Explanation : In three dimensional array have first two dimension declaration is compulsory other wise we will get compile time error:illegal startup expression." }, { "code": null, "e": 2505, "s": 2456, "text": "Question 5. What is the output of this question?" }, { "code": "class Test5 {public static void main(String[] args) { int arr[] = new int[5]; System.out.println(arr); System.out.println(arr[0]); }}", "e": 2669, "s": 2505, "text": null }, { "code": null, "e": 2715, "s": 2669, "text": "OptionA) 00B)[I@6bc7c0540C) 0 0 0 0 00D) none" }, { "code": null, "e": 2726, "s": 2715, "text": "Output: B\n" }, { "code": null, "e": 2846, "s": 2726, "text": "Explanation : arr : It is giving the base address of arrayarr[0] : It is giving value of array element at 0th location." }, { "code": null, "e": 3151, "s": 2846, "text": "This article is contributed by Shivakant Jaiswal. 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": 3276, "s": 3151, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3288, "s": 3276, "text": "Java-Arrays" }, { "code": null, "e": 3300, "s": 3288, "text": "Java-Output" }, { "code": null, "e": 3315, "s": 3300, "text": "Program Output" }, { "code": null, "e": 3413, "s": 3315, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3446, "s": 3413, "text": "Output of Java Programs | Set 12" }, { "code": null, "e": 3507, "s": 3446, "text": "Output of C programs | Set 59 (Loops and Control Statements)" }, { "code": null, "e": 3550, "s": 3507, "text": "unsigned specifier (%u) in C with Examples" }, { "code": null, "e": 3580, "s": 3550, "text": "Output of C++ Program | Set 2" }, { "code": null, "e": 3637, "s": 3580, "text": "How to show full column content in a PySpark Dataframe ?" }, { "code": null, "e": 3678, "s": 3637, "text": "Output of C programs | Set 31 (Pointers)" }, { "code": null, "e": 3716, "s": 3678, "text": "Output of C programs | Set 35 (Loops)" }, { "code": null, "e": 3757, "s": 3716, "text": "Output of C programs | Set 64 (Pointers)" }, { "code": null, "e": 3805, "s": 3757, "text": "Output of Java Programs | Set 14 (Constructors)" } ]
How to Push Notification in Android using Firebase Cloud Messaging?
01 Sep, 2020 Firebase Cloud Messaging is a real-time solution for sending notifications to client apps without any kind of charges. FCM can reliably transfer notifications of up to 4Kb of payload. In this article, a sample app showing how this service can be availed is developed. Though FCM also allows sending out notifications using an app server, here Firebase admin SDK is used. Follow the complete article to implement an example of FCM. Step 1: Add Firebase to the project and the required permissions To add firebase to the project please refer Adding Firebase to Android App. The following is the gist of adding FCM to the app. Go to Tools -> Firebase -> Cloud Messaging -> Set up Firebase Cloud Messaging Connect your app to Firebase: Complete the three steps of creating a Firebase project.Add FCM to the app. Connect your app to Firebase: Complete the three steps of creating a Firebase project. Add FCM to the app. Since receiving FCM notifications require the use of the internet, add the following permission to the AndroidManifest.xml file anywhere between the </application> and </manifest> tags. <uses-permission android:name=”android.permission.INTERNET” /> Note:compile ‘.....’this format for setting up dependencies is deprecated, instead, useimplementation ‘.....’to declare dependencies in case of any discrepancy. Step 2: Add all the required drawable resources Here, the following icon has been used as a drawable resource. Add all the drawable resources to the drawable resource folder. Step 3: Customize the activity_main.xml Here, the home screen of the app just holds a TextView, however, one can customize the app as per the requirements. activity_main.xml <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="20dp" android:text="Welcome to GeeksforGeeks!" android:textColor="#006600" android:textSize="40dp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 4: Create the Notification Layout Create a new notification.xml file to design the layout for the Notification. This step is stated as optional because the content and title too can be directly set too without customizing the appearance of the notification, however here the notification has the following layout. Here the Notification consists of: An ImageViewA TextView for the TitleA TextView for the Message. An ImageView A TextView for the Title A TextView for the Message. notification.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linear_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="20dp"> <!-- Parent Layout of ImageView --> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <!--Image to be displayed beside the notification text--> <ImageView android:id="@+id/icon" android:layout_width="50dp" android:layout_height="50dp" android:padding="5dp" android:src="@drawable/gfg" /> </LinearLayout> <!-- Parent layout for holding the Title and the Body--> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical" android:padding="5dp"> <!-- TextView for Title --> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Title" android:textColor="#000" android:textStyle="bold" /> <!-- TextView for Body --> <TextView android:id="@+id/message" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Message" android:textSize="15sp" /> </LinearLayout> </LinearLayout> Step 5: Create the message receiving class Create a FirebaseMessageReceiver.java class. This class extends the FirebaseMessagingService. Add the following code to the AndroidManifest.xml file between the </activity> and </application> tags to recognise the FirebaseMessagingService as a service in the app. AndroidManifest.xml <service android:name=".FirebaseMessageReceiver"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter></service> Here the attribute ‘android: name’ is assigned the name of the Java file that extends the FirebaseMessagingService so pass the class name FirebaseMessageReceiver. This service is required to do any type of message handling beyond just receiving notifications, while the client app runs in the background. It also serves the purpose of receiving notifications in foreground apps and much more. The complete AndroidManifest.xml file is given below. AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.pushnotification"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".FirebaseMessageReceiver"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> </application> </manifest> Step 6: Working with FirebaseMessageReceiver.java class FirebaseMessageReceiver.java class overrides the onMessageReceived() method to handle 2 events: If Notification contains any data payload, i.e it is received from the app server.If Notification contains any notification payload, i.e. it is sent via the Firebase Admin SDK. If Notification contains any data payload, i.e it is received from the app server. If Notification contains any notification payload, i.e. it is sent via the Firebase Admin SDK. This method takes RemoteMessage as a parameter. RemoteMessage is a class that extends Object Class and implements Parcelable interface. It is nothing but the object of the message passed using FCM. The above method then calls a user-defined method showNotification() which in turn accepts two parameters. A detailed explanation is provided via comments in the code itself. A notification channel is required for Notifications in Android Versions greater than Oreo. In this example, since a customized notification is designed, a method getCustomDesign() is defined and called to set the resources accordingly. This method sets the custom layout for the display of the notification received. Assuming that only title and body are received from the notification, it appropriately maps the TextViews according to the IDs and sets the image resource for the notification. The complete code for this file is given below. FirebaseMessageReceiver.java package com.example.fcmnotfication_gfg; import android.app.NotificationChannel;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.Context;import android.content.Intent;import android.os.Build;import android.widget.RemoteViews; import androidx.core.app.NotificationCompat; import com.google.firebase.messaging.FirebaseMessagingService;import com.google.firebase.messaging.RemoteMessage; public class FirebaseMessageReceiver extends FirebaseMessagingService { // Override onMessageReceived() method to extract the // title and // body from the message passed in FCM @Override public void onMessageReceived(RemoteMessage remoteMessage) { // First case when notifications are received via // data event // Here, 'title' and 'message' are the assumed names // of JSON // attributes. Since here we do not have any data // payload, This section is commented out. It is // here only for reference purposes. /*if(remoteMessage.getData().size()>0){ showNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("message")); }*/ // Second case when notification payload is // received. if (remoteMessage.getNotification() != null) { // Since the notification is received directly from // FCM, the title and the body can be fetched // directly as below. showNotification( remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody()); } } // Method to get the custom Design for the display of // notification. private RemoteViews getCustomDesign(String title, String message) { RemoteViews remoteViews = new RemoteViews( getApplicationContext().getPackageName(), R.layout.notification); remoteViews.setTextViewText(R.id.title, title); remoteViews.setTextViewText(R.id.message, message); remoteViews.setImageViewResource(R.id.icon, R.drawable.gfg); return remoteViews; } // Method to display the notifications public void showNotification(String title, String message) { // Pass the intent to switch to the MainActivity Intent intent = new Intent(this, MainActivity.class); // Assign channel ID String channel_id = "notification_channel"; // Here FLAG_ACTIVITY_CLEAR_TOP flag is set to clear // the activities present in the activity stack, // on the top of the Activity that is to be launched intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Pass the intent to PendingIntent to start the // next Activity PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_ONE_SHOT); // Create a Builder object using NotificationCompat // class. This will allow control over all the flags NotificationCompat.Builder builder = new NotificationCompat .Builder(getApplicationContext(), channel_id) .setSmallIcon(R.drawable.gfg) .setAutoCancel(true) .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}) .setOnlyAlertOnce(true) .setContentIntent(pendingIntent); // A customized design for the notification can be // set only for Android versions 4.1 and above. Thus // condition for the same is checked here. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { builder = builder.setContent( getCustomDesign(title, message)); } // If Android Version is lower than Jelly Beans, // customized layout cannot be used and thus the // layout is set as follows else { builder = builder.setContentTitle(title) .setContentText(message) .setSmallIcon(R.drawable.gfg); } // Create an object of NotificationManager class to // notify the // user of events that happen in the background. NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); // Check if the Android Version is greater than Oreo if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel( channel_id, "web_app", NotificationManager.IMPORTANCE_HIGH); notificationManager.createNotificationChannel( notificationChannel); } notificationManager.notify(0, builder.build()); }} Note: The notification when clicked will always redirect to the launcher activity of the app when the app is in the background and to the activity passed in the intent if it is in the foreground. To redirect the user always to some other activity than the launcher, you’ll have to send data payload using a server app, sending messaging using Firebase SDK does not support this. Step 7: Complete the MainActivity.java file Since here nothing much is presented in the activity_main.xml, the MainActivity file does not need any additional code. MainActivity.java package com.example.fcmnotfication_gfg; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }} Now run the app on your emulator or in your mobile device. Step 8: Send the notification using FCM Go to Firebase console and choose the appropriate project. Choose Cloud Messaging. Choose Send your First Message. The following window pops up. Fill out the details. While the text field is compulsory, rest all is optional. One can also add an image using a link or upload it, however uploading an image cost additional storage charges. In the target section, choose the app domain. One can either send out the notification now or schedule it for some time in the future. Rest all the other fields are optional and can be left empty. Click on Review and then Publish. android Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android SDK and it's Components Navigation Drawer in Android Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java For-each loop in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Sep, 2020" }, { "code": null, "e": 485, "s": 54, "text": "Firebase Cloud Messaging is a real-time solution for sending notifications to client apps without any kind of charges. FCM can reliably transfer notifications of up to 4Kb of payload. In this article, a sample app showing how this service can be availed is developed. Though FCM also allows sending out notifications using an app server, here Firebase admin SDK is used. Follow the complete article to implement an example of FCM." }, { "code": null, "e": 550, "s": 485, "text": "Step 1: Add Firebase to the project and the required permissions" }, { "code": null, "e": 756, "s": 550, "text": "To add firebase to the project please refer Adding Firebase to Android App. The following is the gist of adding FCM to the app. Go to Tools -> Firebase -> Cloud Messaging -> Set up Firebase Cloud Messaging" }, { "code": null, "e": 862, "s": 756, "text": "Connect your app to Firebase: Complete the three steps of creating a Firebase project.Add FCM to the app." }, { "code": null, "e": 949, "s": 862, "text": "Connect your app to Firebase: Complete the three steps of creating a Firebase project." }, { "code": null, "e": 969, "s": 949, "text": "Add FCM to the app." }, { "code": null, "e": 1155, "s": 969, "text": "Since receiving FCM notifications require the use of the internet, add the following permission to the AndroidManifest.xml file anywhere between the </application> and </manifest> tags." }, { "code": null, "e": 1218, "s": 1155, "text": "<uses-permission android:name=”android.permission.INTERNET” />" }, { "code": null, "e": 1379, "s": 1218, "text": "Note:compile ‘.....’this format for setting up dependencies is deprecated, instead, useimplementation ‘.....’to declare dependencies in case of any discrepancy." }, { "code": null, "e": 1427, "s": 1379, "text": "Step 2: Add all the required drawable resources" }, { "code": null, "e": 1554, "s": 1427, "text": "Here, the following icon has been used as a drawable resource. Add all the drawable resources to the drawable resource folder." }, { "code": null, "e": 1594, "s": 1554, "text": "Step 3: Customize the activity_main.xml" }, { "code": null, "e": 1710, "s": 1594, "text": "Here, the home screen of the app just holds a TextView, however, one can customize the app as per the requirements." }, { "code": null, "e": 1728, "s": 1710, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:padding=\"20dp\" android:text=\"Welcome to GeeksforGeeks!\" android:textColor=\"#006600\" android:textSize=\"40dp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 2641, "s": 1728, "text": null }, { "code": null, "e": 2680, "s": 2641, "text": "Step 4: Create the Notification Layout" }, { "code": null, "e": 2995, "s": 2680, "text": "Create a new notification.xml file to design the layout for the Notification. This step is stated as optional because the content and title too can be directly set too without customizing the appearance of the notification, however here the notification has the following layout. Here the Notification consists of:" }, { "code": null, "e": 3059, "s": 2995, "text": "An ImageViewA TextView for the TitleA TextView for the Message." }, { "code": null, "e": 3072, "s": 3059, "text": "An ImageView" }, { "code": null, "e": 3097, "s": 3072, "text": "A TextView for the Title" }, { "code": null, "e": 3125, "s": 3097, "text": "A TextView for the Message." }, { "code": null, "e": 3142, "s": 3125, "text": "notification.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/linear_layout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\" android:padding=\"20dp\"> <!-- Parent Layout of ImageView --> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\"> <!--Image to be displayed beside the notification text--> <ImageView android:id=\"@+id/icon\" android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:padding=\"5dp\" android:src=\"@drawable/gfg\" /> </LinearLayout> <!-- Parent layout for holding the Title and the Body--> <LinearLayout android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:orientation=\"vertical\" android:padding=\"5dp\"> <!-- TextView for Title --> <TextView android:id=\"@+id/title\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Title\" android:textColor=\"#000\" android:textStyle=\"bold\" /> <!-- TextView for Body --> <TextView android:id=\"@+id/message\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Message\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout>", "e": 4716, "s": 3142, "text": null }, { "code": null, "e": 4759, "s": 4716, "text": "Step 5: Create the message receiving class" }, { "code": null, "e": 5023, "s": 4759, "text": "Create a FirebaseMessageReceiver.java class. This class extends the FirebaseMessagingService. Add the following code to the AndroidManifest.xml file between the </activity> and </application> tags to recognise the FirebaseMessagingService as a service in the app." }, { "code": null, "e": 5043, "s": 5023, "text": "AndroidManifest.xml" }, { "code": " <service android:name=\".FirebaseMessageReceiver\"> <intent-filter> <action android:name=\"com.google.firebase.MESSAGING_EVENT\" /> </intent-filter></service>", "e": 5238, "s": 5043, "text": null }, { "code": null, "e": 5685, "s": 5238, "text": "Here the attribute ‘android: name’ is assigned the name of the Java file that extends the FirebaseMessagingService so pass the class name FirebaseMessageReceiver. This service is required to do any type of message handling beyond just receiving notifications, while the client app runs in the background. It also serves the purpose of receiving notifications in foreground apps and much more. The complete AndroidManifest.xml file is given below." }, { "code": null, "e": 5705, "s": 5685, "text": "AndroidManifest.xml" }, { "code": " <?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.pushnotification\"> <uses-permission android:name=\"android.permission.INTERNET\" /> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> <service android:name=\".FirebaseMessageReceiver\"> <intent-filter> <action android:name=\"com.google.firebase.MESSAGING_EVENT\" /> </intent-filter> </service> </application> </manifest>", "e": 6716, "s": 5705, "text": null }, { "code": null, "e": 6772, "s": 6716, "text": "Step 6: Working with FirebaseMessageReceiver.java class" }, { "code": null, "e": 6868, "s": 6772, "text": "FirebaseMessageReceiver.java class overrides the onMessageReceived() method to handle 2 events:" }, { "code": null, "e": 7045, "s": 6868, "text": "If Notification contains any data payload, i.e it is received from the app server.If Notification contains any notification payload, i.e. it is sent via the Firebase Admin SDK." }, { "code": null, "e": 7128, "s": 7045, "text": "If Notification contains any data payload, i.e it is received from the app server." }, { "code": null, "e": 7223, "s": 7128, "text": "If Notification contains any notification payload, i.e. it is sent via the Firebase Admin SDK." }, { "code": null, "e": 7689, "s": 7223, "text": "This method takes RemoteMessage as a parameter. RemoteMessage is a class that extends Object Class and implements Parcelable interface. It is nothing but the object of the message passed using FCM. The above method then calls a user-defined method showNotification() which in turn accepts two parameters. A detailed explanation is provided via comments in the code itself. A notification channel is required for Notifications in Android Versions greater than Oreo." }, { "code": null, "e": 8140, "s": 7689, "text": "In this example, since a customized notification is designed, a method getCustomDesign() is defined and called to set the resources accordingly. This method sets the custom layout for the display of the notification received. Assuming that only title and body are received from the notification, it appropriately maps the TextViews according to the IDs and sets the image resource for the notification. The complete code for this file is given below." }, { "code": null, "e": 8169, "s": 8140, "text": "FirebaseMessageReceiver.java" }, { "code": "package com.example.fcmnotfication_gfg; import android.app.NotificationChannel;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.Context;import android.content.Intent;import android.os.Build;import android.widget.RemoteViews; import androidx.core.app.NotificationCompat; import com.google.firebase.messaging.FirebaseMessagingService;import com.google.firebase.messaging.RemoteMessage; public class FirebaseMessageReceiver extends FirebaseMessagingService { // Override onMessageReceived() method to extract the // title and // body from the message passed in FCM @Override public void onMessageReceived(RemoteMessage remoteMessage) { // First case when notifications are received via // data event // Here, 'title' and 'message' are the assumed names // of JSON // attributes. Since here we do not have any data // payload, This section is commented out. It is // here only for reference purposes. /*if(remoteMessage.getData().size()>0){ showNotification(remoteMessage.getData().get(\"title\"), remoteMessage.getData().get(\"message\")); }*/ // Second case when notification payload is // received. if (remoteMessage.getNotification() != null) { // Since the notification is received directly from // FCM, the title and the body can be fetched // directly as below. showNotification( remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody()); } } // Method to get the custom Design for the display of // notification. private RemoteViews getCustomDesign(String title, String message) { RemoteViews remoteViews = new RemoteViews( getApplicationContext().getPackageName(), R.layout.notification); remoteViews.setTextViewText(R.id.title, title); remoteViews.setTextViewText(R.id.message, message); remoteViews.setImageViewResource(R.id.icon, R.drawable.gfg); return remoteViews; } // Method to display the notifications public void showNotification(String title, String message) { // Pass the intent to switch to the MainActivity Intent intent = new Intent(this, MainActivity.class); // Assign channel ID String channel_id = \"notification_channel\"; // Here FLAG_ACTIVITY_CLEAR_TOP flag is set to clear // the activities present in the activity stack, // on the top of the Activity that is to be launched intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Pass the intent to PendingIntent to start the // next Activity PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_ONE_SHOT); // Create a Builder object using NotificationCompat // class. This will allow control over all the flags NotificationCompat.Builder builder = new NotificationCompat .Builder(getApplicationContext(), channel_id) .setSmallIcon(R.drawable.gfg) .setAutoCancel(true) .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}) .setOnlyAlertOnce(true) .setContentIntent(pendingIntent); // A customized design for the notification can be // set only for Android versions 4.1 and above. Thus // condition for the same is checked here. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { builder = builder.setContent( getCustomDesign(title, message)); } // If Android Version is lower than Jelly Beans, // customized layout cannot be used and thus the // layout is set as follows else { builder = builder.setContentTitle(title) .setContentText(message) .setSmallIcon(R.drawable.gfg); } // Create an object of NotificationManager class to // notify the // user of events that happen in the background. NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); // Check if the Android Version is greater than Oreo if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel( channel_id, \"web_app\", NotificationManager.IMPORTANCE_HIGH); notificationManager.createNotificationChannel( notificationChannel); } notificationManager.notify(0, builder.build()); }}", "e": 13210, "s": 8169, "text": null }, { "code": null, "e": 13589, "s": 13210, "text": "Note: The notification when clicked will always redirect to the launcher activity of the app when the app is in the background and to the activity passed in the intent if it is in the foreground. To redirect the user always to some other activity than the launcher, you’ll have to send data payload using a server app, sending messaging using Firebase SDK does not support this." }, { "code": null, "e": 13633, "s": 13589, "text": "Step 7: Complete the MainActivity.java file" }, { "code": null, "e": 13753, "s": 13633, "text": "Since here nothing much is presented in the activity_main.xml, the MainActivity file does not need any additional code." }, { "code": null, "e": 13771, "s": 13753, "text": "MainActivity.java" }, { "code": "package com.example.fcmnotfication_gfg; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }}", "e": 14111, "s": 13771, "text": null }, { "code": null, "e": 14170, "s": 14111, "text": "Now run the app on your emulator or in your mobile device." }, { "code": null, "e": 14210, "s": 14170, "text": "Step 8: Send the notification using FCM" }, { "code": null, "e": 14269, "s": 14210, "text": "Go to Firebase console and choose the appropriate project." }, { "code": null, "e": 14293, "s": 14269, "text": "Choose Cloud Messaging." }, { "code": null, "e": 14548, "s": 14293, "text": "Choose Send your First Message. The following window pops up. Fill out the details. While the text field is compulsory, rest all is optional. One can also add an image using a link or upload it, however uploading an image cost additional storage charges." }, { "code": null, "e": 14594, "s": 14548, "text": "In the target section, choose the app domain." }, { "code": null, "e": 14683, "s": 14594, "text": "One can either send out the notification now or schedule it for some time in the future." }, { "code": null, "e": 14779, "s": 14683, "text": "Rest all the other fields are optional and can be left empty. Click on Review and then Publish." }, { "code": null, "e": 14787, "s": 14779, "text": "android" }, { "code": null, "e": 14795, "s": 14787, "text": "Android" }, { "code": null, "e": 14800, "s": 14795, "text": "Java" }, { "code": null, "e": 14805, "s": 14800, "text": "Java" }, { "code": null, "e": 14813, "s": 14805, "text": "Android" }, { "code": null, "e": 14911, "s": 14813, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14980, "s": 14911, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 15011, "s": 14980, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 15054, "s": 15011, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 15086, "s": 15054, "text": "Android SDK and it's Components" }, { "code": null, "e": 15115, "s": 15086, "text": "Navigation Drawer in Android" }, { "code": null, "e": 15130, "s": 15115, "text": "Arrays in Java" }, { "code": null, "e": 15174, "s": 15130, "text": "Split() String method in Java with examples" }, { "code": null, "e": 15210, "s": 15174, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 15235, "s": 15210, "text": "Reverse a string in Java" } ]
Strict Aliasing Rule in C with Examples
08 Jul, 2020 Aliasing: Aliasing refers to the situation where the same memory location can be accessed using different names. For Example, if a function takes two pointers A and B which have the same value, then the name A[0] aliases the name B[0] i.e., we say the pointers A and B alias each other. Below is the program to illustrate aliasing in C: C // C program to illustrate aliasing#include <stdio.h> // Function to add 10 to bint gfg(int* a, int* b){ *b = *b + 10; return *a;} // Driver Codeint main(){ // Given data int data = 20; // Function Call with aliasing int result = gfg(&data, &data); // Print the data printf("%d ", result);} 30 Explanation:In the above program, the value of data is 20. When this variable is aliased to function gfg() then the changes made to memory location referred by pointer ‘b’, got reflected in ‘a’ as well. This is done because they referred to the same memory location. Strict Aliasing:GCC compiler makes an assumption that pointers of different types will never point to the same memory location i.e., alias of each other. Strict aliasing rule helps the compiler to optimize the code. The Strict Aliasing rule is enabled by default on optimization levels 2 and beyond, and when one tries to compile a program with aforementioned details the compiler throws warnings, though the program still compiles and can be executed, the output of such a program remains unpredictable. C // C program to illustrate aliasing#include <stdio.h> // Function to change the value of// ptr1 and ptr2int foo(int* ptr1, int* ptr2){ *ptr1 = 10; *ptr2 = 11; return *ptr1;} // Driver Codeint main(){ int data1 = 10, data2 = 20; // Function Call int result = foo(&data1, &data2); // Print result printf("%d ", result); return 0;} 10 Explanation:In the above code, the compiler can not optimize the code to directly return 10, since both pointers ptr1 and ptr2 could be an alias of each other. In that case, it would return 11, not 10. Even if we are sure that both pointers are not an alias of each other, then also optimization could not be performed by the compiler. Now, to solve this problem strict aliasing rule has been introduced. It ensures compiler that pointers of different types can not be an alias of each other. C #include <stdio.h> int foo(int* ptr1, long* ptr2){ *ptr1 = 10; *ptr2 = 21.02; return *ptr1;} int main(){ int a = 11; long b = 20.02; int result = foo(&a, &b); printf("%d ", result); return 0;} 10 Here code can be optimized directly to return 10 since the compiler knows for sure that both pointers would not be an alias of each other. Here, we can observe that the compilers can leverage strict-aliasing rules to generate better-optimized code. Note: Since, both C and C++ allow casting between pointer types, which will eventually create aliases and thus, violate the compiler’s assumption. C #include <stdio.h> int foo(int* ptr1, long* ptr2){ *ptr1 = 10; *ptr2 = 11; return *ptr1;} int main(){ long a = 11.0; int result = foo((int*)&a, &a); printf("%d ", result); return 0;} 11 Another example program that violates the strict aliasing rule: CPP #include <bits/stdc++.h>using namespace std; __uint32_t left(__uint32_t val){ __uint32_t val_temp = val; // can't use static_cast<>, // not legal __uint16_t* ptr = (__uint16_t*)&val_temp; __uint16_t tmp = ptr[0]; ptr[1] = ptr[0]; ptr[0] = 0; return val_temp;} int main(){ __uint32_t val; val = 1; val = left(val); cout << val << endl;} 65536 Explanation: The above code simply left shifts the value of variable val by 16 bits, by swapping the lower 16 bits to the higher 16 bits and setting the higher 16 bits to 0, however here we use __uint16_t pointer ptr to create an alias of ‘val’, this violates the strict aliasing rule, and this may lead to different outputs on different levels of optimizations (i.e. O1, O2 and O3) on a compiler. How To Bypass the Strict Aliasing Rules?: Although the rules are implemented to prevent unexpected behavior, the rules can be bypassed by ignoring the warnings and explicitly using the -fno-strict-aliasing tag while compiling, this ensures no rules are enforced even when level O3, O2 optimizations are applied. Picked C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Unordered Sets in C++ Standard Template Library rand() and srand() in C/C++ Enumeration (or enum) in C What is the purpose of a function prototype?
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jul, 2020" }, { "code": null, "e": 141, "s": 28, "text": "Aliasing: Aliasing refers to the situation where the same memory location can be accessed using different names." }, { "code": null, "e": 315, "s": 141, "text": "For Example, if a function takes two pointers A and B which have the same value, then the name A[0] aliases the name B[0] i.e., we say the pointers A and B alias each other." }, { "code": null, "e": 365, "s": 315, "text": "Below is the program to illustrate aliasing in C:" }, { "code": null, "e": 367, "s": 365, "text": "C" }, { "code": "// C program to illustrate aliasing#include <stdio.h> // Function to add 10 to bint gfg(int* a, int* b){ *b = *b + 10; return *a;} // Driver Codeint main(){ // Given data int data = 20; // Function Call with aliasing int result = gfg(&data, &data); // Print the data printf(\"%d \", result);}", "e": 688, "s": 367, "text": null }, { "code": null, "e": 692, "s": 688, "text": "30\n" }, { "code": null, "e": 959, "s": 692, "text": "Explanation:In the above program, the value of data is 20. When this variable is aliased to function gfg() then the changes made to memory location referred by pointer ‘b’, got reflected in ‘a’ as well. This is done because they referred to the same memory location." }, { "code": null, "e": 1464, "s": 959, "text": "Strict Aliasing:GCC compiler makes an assumption that pointers of different types will never point to the same memory location i.e., alias of each other. Strict aliasing rule helps the compiler to optimize the code. The Strict Aliasing rule is enabled by default on optimization levels 2 and beyond, and when one tries to compile a program with aforementioned details the compiler throws warnings, though the program still compiles and can be executed, the output of such a program remains unpredictable." }, { "code": null, "e": 1466, "s": 1464, "text": "C" }, { "code": "// C program to illustrate aliasing#include <stdio.h> // Function to change the value of// ptr1 and ptr2int foo(int* ptr1, int* ptr2){ *ptr1 = 10; *ptr2 = 11; return *ptr1;} // Driver Codeint main(){ int data1 = 10, data2 = 20; // Function Call int result = foo(&data1, &data2); // Print result printf(\"%d \", result); return 0;}", "e": 1828, "s": 1466, "text": null }, { "code": null, "e": 1832, "s": 1828, "text": "10\n" }, { "code": null, "e": 2034, "s": 1832, "text": "Explanation:In the above code, the compiler can not optimize the code to directly return 10, since both pointers ptr1 and ptr2 could be an alias of each other. In that case, it would return 11, not 10." }, { "code": null, "e": 2325, "s": 2034, "text": "Even if we are sure that both pointers are not an alias of each other, then also optimization could not be performed by the compiler. Now, to solve this problem strict aliasing rule has been introduced. It ensures compiler that pointers of different types can not be an alias of each other." }, { "code": null, "e": 2327, "s": 2325, "text": "C" }, { "code": "#include <stdio.h> int foo(int* ptr1, long* ptr2){ *ptr1 = 10; *ptr2 = 21.02; return *ptr1;} int main(){ int a = 11; long b = 20.02; int result = foo(&a, &b); printf(\"%d \", result); return 0;}", "e": 2546, "s": 2327, "text": null }, { "code": null, "e": 2550, "s": 2546, "text": "10\n" }, { "code": null, "e": 2799, "s": 2550, "text": "Here code can be optimized directly to return 10 since the compiler knows for sure that both pointers would not be an alias of each other. Here, we can observe that the compilers can leverage strict-aliasing rules to generate better-optimized code." }, { "code": null, "e": 2946, "s": 2799, "text": "Note: Since, both C and C++ allow casting between pointer types, which will eventually create aliases and thus, violate the compiler’s assumption." }, { "code": null, "e": 2948, "s": 2946, "text": "C" }, { "code": "#include <stdio.h> int foo(int* ptr1, long* ptr2){ *ptr1 = 10; *ptr2 = 11; return *ptr1;} int main(){ long a = 11.0; int result = foo((int*)&a, &a); printf(\"%d \", result); return 0;}", "e": 3154, "s": 2948, "text": null }, { "code": null, "e": 3158, "s": 3154, "text": "11\n" }, { "code": null, "e": 3222, "s": 3158, "text": "Another example program that violates the strict aliasing rule:" }, { "code": null, "e": 3226, "s": 3222, "text": "CPP" }, { "code": "#include <bits/stdc++.h>using namespace std; __uint32_t left(__uint32_t val){ __uint32_t val_temp = val; // can't use static_cast<>, // not legal __uint16_t* ptr = (__uint16_t*)&val_temp; __uint16_t tmp = ptr[0]; ptr[1] = ptr[0]; ptr[0] = 0; return val_temp;} int main(){ __uint32_t val; val = 1; val = left(val); cout << val << endl;}", "e": 3607, "s": 3226, "text": null }, { "code": null, "e": 3614, "s": 3607, "text": "65536\n" }, { "code": null, "e": 3627, "s": 3614, "text": "Explanation:" }, { "code": null, "e": 4012, "s": 3627, "text": "The above code simply left shifts the value of variable val by 16 bits, by swapping the lower 16 bits to the higher 16 bits and setting the higher 16 bits to 0, however here we use __uint16_t pointer ptr to create an alias of ‘val’, this violates the strict aliasing rule, and this may lead to different outputs on different levels of optimizations (i.e. O1, O2 and O3) on a compiler." }, { "code": null, "e": 4054, "s": 4012, "text": "How To Bypass the Strict Aliasing Rules?:" }, { "code": null, "e": 4325, "s": 4054, "text": "Although the rules are implemented to prevent unexpected behavior, the rules can be bypassed by ignoring the warnings and explicitly using the -fno-strict-aliasing tag while compiling, this ensures no rules are enforced even when level O3, O2 optimizations are applied." }, { "code": null, "e": 4332, "s": 4325, "text": "Picked" }, { "code": null, "e": 4343, "s": 4332, "text": "C Language" }, { "code": null, "e": 4441, "s": 4343, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4458, "s": 4441, "text": "Substring in C++" }, { "code": null, "e": 4480, "s": 4458, "text": "Function Pointer in C" }, { "code": null, "e": 4515, "s": 4480, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 4561, "s": 4515, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 4606, "s": 4561, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 4631, "s": 4606, "text": "std::string class in C++" }, { "code": null, "e": 4679, "s": 4631, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 4707, "s": 4679, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 4734, "s": 4707, "text": "Enumeration (or enum) in C" } ]
Minimize cost to sort given array by sorting unsorted subarrays
19 Jan, 2022 Given an array arr[] of size N, the task is to minimize the cost to sort the array by sorting any unsorted subarray where the cost of the operation is the difference between the maximum and minimum element of that subarray. This operation can be performed infinite times including 0. Examples: Input: arr[] = {1, 7, 5, 2, 1, 8}Output: 6Explanation: The subarray from index [1,4] can be chosen and can be sorted with cost = 7 – 1 = 6 Input: arr[] = { 1, 4, 3, 5, 6 ,13, 10}Output: 4Explanation: The subarray from index index [1,2] and [5,6] can be sorted with cost of 4 – 3 and 13 – 10 = 1 + 3 = 4 Approach: This can be solved using the greedy approach, the elements already sorted don’t require any cost so only the subarrays that have unsorted elements must be considered to sort. Multiset can be used to store the elements that are not in sorted order and the difference between the last and first element of multiset gives the cost. Follow these steps to solve the above problem: Initialize a vector v and copy the arr into it and assign the size of the vector to the variable n. Now sort the vector v. Initialize 2 multisets m1 and m2 to store the unsorted and sorted subarray respectively and cost = 0 to store the result. Now iterate through the range [0,N) and check If v[i] is not equal to arr[i] Insert arr[i] into m1 and v[i] into m2 When both the multisets are the same add the difference between the last and first element of the set to the cost. Clear both the multisets to make them used by the next unsorted subarray. Print the cost. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum cost// to sort the array in ascending orderint minimum_cost(vector<int> arr){ // Copy the arr into vector and sort it vector<int> sorted = arr; int n = arr.size(); sort(sorted.begin(), sorted.end()); // Initialize the two multisets to store // sorted and the unordered elements multiset<int> m1, m2; // Initialize cost to store final answer int cost = 0; for (int i = 0; i < n; i++) { if (sorted[i] != arr[i]) { m1.insert(arr[i]); m2.insert(sorted[i]); // If both the multisets are equal, // the unordered subarray is sorted if (m1 == m2) { // The cost is difference // between mini and max cost += (*m1.rbegin() - *m2.begin()); // Clear the multisets to make // use of it again m1.clear(); m2.clear(); } } } return cost;} // Driver codeint main(){ // Initialize the queries vector<int> arr = { 1, 7, 5, 2, 1, 8 }; cout << minimum_cost(arr); return 0;} // Java code to implement the above approachimport java.util.*; class GFG { // Function to find the minimum cost // to sort the array in ascending order public static int minimum_cost(int[] arr) { // Copy the arr into vector and sort it int n = arr.length; int[] sorted = new int[n]; sorted = arr.clone(); Arrays.sort(sorted); // Initialize the two multisets to store // sorted and the unordered elements SortedSet<Integer> m1 = new TreeSet<Integer>(); SortedSet<Integer> m2 = new TreeSet<Integer>(); // Initialize cost to store final answer int cost = 0; for (int i = 0; i < n; i++) { if (sorted[i] != arr[i]) { m1.add(arr[i]); m2.add(sorted[i]); // If both the multisets are equal, // the unordered subarray is sorted if (m1.equals(m2)) { // The cost is difference // between mini and max cost += (Collections.max(m1) - Collections.min(m2)); // Clear the multisets to make // use of it again m1.clear(); m2.clear(); } } } return cost; } // Driver code public static void main (String[] args) { // Initialize the queries int[] arr = { 1, 7, 5, 2, 1, 8 }; System.out.println(minimum_cost(arr)); }} // This code is contributed by Shubham Singh # python3 program for the above approach # Function to find the minimum cost# to sort the array in ascending orderdef minimum_cost(arr): # Copy the arr into vector and sort it sorted = arr.copy() n = len(arr) sorted.sort() # Initialize the two multisets to store # sorted and the unordered elements m1 = set() m2 = set() # Initialize cost to store final answer cost = 0 for i in range(0, n): if (sorted[i] != arr[i]): m1.add(arr[i]) m2.add(sorted[i]) # If both the multisets are equal, # the unordered subarray is sorted if (m1 == m2): # The cost is difference # between mini and max cost += (list(m1)[len(list(m1)) - 1] - list(m2)[0]) # Clear the multisets to make # use of it again m1.clear() m2.clear() return cost # Driver codeif __name__ == "__main__": # Initialize the queries arr = [1, 7, 5, 2, 1, 8] print(minimum_cost(arr)) # This code is contributed by rakeshsahni // C# code to implement the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to find the minimum cost // to sort the array in ascending order public static int minimum_cost(int[] arr) { // Copy the arr into vector and sort it int n = arr.Length; int[] sorted = new int[n]; Array.Copy(arr, 0, sorted, 0, n); Array.Sort(sorted); // Initialize the two multisets to store // sorted and the unordered elements SortedSet<int> m1 = new SortedSet<int>(); SortedSet<int> m2 = new SortedSet<int>(); // Initialize cost to store final answer int cost = 0; for (int i = 0; i < n; i++) { if (sorted[i] != arr[i]) { m1.Add(arr[i]); m2.Add(sorted[i]); // If both the multisets are equal, // the unordered subarray is sorted if (m1.SetEquals(m2)) { // The cost is difference // between mini and max cost += (m1.Max - m2.Min); // Clear the multisets to make // use of it again m1.Clear(); m2.Clear(); } } } return cost; } // Driver code public static void Main() { // Initialize the queries int[] arr = { 1, 7, 5, 2, 1, 8 }; Console.Write(minimum_cost(arr)); }} // This code is contributed by Shubham Singh <script> // Javascript program for the above approach // Function to find the minimum cost// to sort the array in ascending orderfunction minimum_cost(arr){ // Copy the arr into vector and sort it var sorted = arr.slice(); var n = arr.length; sorted.sort(); // Initialize the two multisets to store // sorted and the unordered elements var m1 = new Set(); var m2 = new Set(); // Initialize cost to store final answer var cost = 0; let areSetsEqual = (a, b) => a.size === b.size && [...a].every(value => b.has(value)); for (var i = 0; i < n; i++) { if (sorted[i] != arr[i]) { m1.add(arr[i]); m2.add(sorted[i]); // If both the multisets are equal, // the unordered subarray is sorted if (areSetsEqual(m1,m2)) { // The cost is difference // between mini and max cost += (Math.max(...Array.from(m1.values())) - Math.min(...Array.from(m2.values()))); // Clear the multisets to make // use of it again m1.clear(); m2.clear(); } } } return cost;} // Driver code// Initialize the queriesvar arr = [ 1, 7, 5, 2, 1, 8 ];document.write(minimum_cost(arr)); // This code is contributed by Shubham Singh</script> 6 Time Complexity: O(N * logN ) Auxiliary Space: O(N) rakeshsahni shubhamsingh84100 SHUBHAMSINGH10 Algo-Geek 2021 subarray Algo Geek Arrays Greedy Sorting Arrays Greedy Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Number of ways to divide a N elements equally into group of at least 2 Sort strings on the basis of their numeric part Count of ordered pairs (i, j) such that arr[i] and arr[j] concatenates to X Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index Check if the given string is valid English word or not Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jan, 2022" }, { "code": null, "e": 313, "s": 28, "text": "Given an array arr[] of size N, the task is to minimize the cost to sort the array by sorting any unsorted subarray where the cost of the operation is the difference between the maximum and minimum element of that subarray. This operation can be performed infinite times including 0." }, { "code": null, "e": 323, "s": 313, "text": "Examples:" }, { "code": null, "e": 462, "s": 323, "text": "Input: arr[] = {1, 7, 5, 2, 1, 8}Output: 6Explanation: The subarray from index [1,4] can be chosen and can be sorted with cost = 7 – 1 = 6" }, { "code": null, "e": 627, "s": 462, "text": "Input: arr[] = { 1, 4, 3, 5, 6 ,13, 10}Output: 4Explanation: The subarray from index index [1,2] and [5,6] can be sorted with cost of 4 – 3 and 13 – 10 = 1 + 3 = 4" }, { "code": null, "e": 966, "s": 627, "text": "Approach: This can be solved using the greedy approach, the elements already sorted don’t require any cost so only the subarrays that have unsorted elements must be considered to sort. Multiset can be used to store the elements that are not in sorted order and the difference between the last and first element of multiset gives the cost." }, { "code": null, "e": 1013, "s": 966, "text": "Follow these steps to solve the above problem:" }, { "code": null, "e": 1113, "s": 1013, "text": "Initialize a vector v and copy the arr into it and assign the size of the vector to the variable n." }, { "code": null, "e": 1136, "s": 1113, "text": "Now sort the vector v." }, { "code": null, "e": 1259, "s": 1136, "text": "Initialize 2 multisets m1 and m2 to store the unsorted and sorted subarray respectively and cost = 0 to store the result." }, { "code": null, "e": 1305, "s": 1259, "text": "Now iterate through the range [0,N) and check" }, { "code": null, "e": 1337, "s": 1305, "text": "If v[i] is not equal to arr[i] " }, { "code": null, "e": 1376, "s": 1337, "text": "Insert arr[i] into m1 and v[i] into m2" }, { "code": null, "e": 1491, "s": 1376, "text": "When both the multisets are the same add the difference between the last and first element of the set to the cost." }, { "code": null, "e": 1565, "s": 1491, "text": "Clear both the multisets to make them used by the next unsorted subarray." }, { "code": null, "e": 1581, "s": 1565, "text": "Print the cost." }, { "code": null, "e": 1632, "s": 1581, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 1636, "s": 1632, "text": "C++" }, { "code": null, "e": 1641, "s": 1636, "text": "Java" }, { "code": null, "e": 1649, "s": 1641, "text": "Python3" }, { "code": null, "e": 1652, "s": 1649, "text": "C#" }, { "code": null, "e": 1663, "s": 1652, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum cost// to sort the array in ascending orderint minimum_cost(vector<int> arr){ // Copy the arr into vector and sort it vector<int> sorted = arr; int n = arr.size(); sort(sorted.begin(), sorted.end()); // Initialize the two multisets to store // sorted and the unordered elements multiset<int> m1, m2; // Initialize cost to store final answer int cost = 0; for (int i = 0; i < n; i++) { if (sorted[i] != arr[i]) { m1.insert(arr[i]); m2.insert(sorted[i]); // If both the multisets are equal, // the unordered subarray is sorted if (m1 == m2) { // The cost is difference // between mini and max cost += (*m1.rbegin() - *m2.begin()); // Clear the multisets to make // use of it again m1.clear(); m2.clear(); } } } return cost;} // Driver codeint main(){ // Initialize the queries vector<int> arr = { 1, 7, 5, 2, 1, 8 }; cout << minimum_cost(arr); return 0;}", "e": 2893, "s": 1663, "text": null }, { "code": "// Java code to implement the above approachimport java.util.*; class GFG { // Function to find the minimum cost // to sort the array in ascending order public static int minimum_cost(int[] arr) { // Copy the arr into vector and sort it int n = arr.length; int[] sorted = new int[n]; sorted = arr.clone(); Arrays.sort(sorted); // Initialize the two multisets to store // sorted and the unordered elements SortedSet<Integer> m1 = new TreeSet<Integer>(); SortedSet<Integer> m2 = new TreeSet<Integer>(); // Initialize cost to store final answer int cost = 0; for (int i = 0; i < n; i++) { if (sorted[i] != arr[i]) { m1.add(arr[i]); m2.add(sorted[i]); // If both the multisets are equal, // the unordered subarray is sorted if (m1.equals(m2)) { // The cost is difference // between mini and max cost += (Collections.max(m1) - Collections.min(m2)); // Clear the multisets to make // use of it again m1.clear(); m2.clear(); } } } return cost; } // Driver code public static void main (String[] args) { // Initialize the queries int[] arr = { 1, 7, 5, 2, 1, 8 }; System.out.println(minimum_cost(arr)); }} // This code is contributed by Shubham Singh", "e": 4233, "s": 2893, "text": null }, { "code": "# python3 program for the above approach # Function to find the minimum cost# to sort the array in ascending orderdef minimum_cost(arr): # Copy the arr into vector and sort it sorted = arr.copy() n = len(arr) sorted.sort() # Initialize the two multisets to store # sorted and the unordered elements m1 = set() m2 = set() # Initialize cost to store final answer cost = 0 for i in range(0, n): if (sorted[i] != arr[i]): m1.add(arr[i]) m2.add(sorted[i]) # If both the multisets are equal, # the unordered subarray is sorted if (m1 == m2): # The cost is difference # between mini and max cost += (list(m1)[len(list(m1)) - 1] - list(m2)[0]) # Clear the multisets to make # use of it again m1.clear() m2.clear() return cost # Driver codeif __name__ == \"__main__\": # Initialize the queries arr = [1, 7, 5, 2, 1, 8] print(minimum_cost(arr)) # This code is contributed by rakeshsahni", "e": 5356, "s": 4233, "text": null }, { "code": "// C# code to implement the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to find the minimum cost // to sort the array in ascending order public static int minimum_cost(int[] arr) { // Copy the arr into vector and sort it int n = arr.Length; int[] sorted = new int[n]; Array.Copy(arr, 0, sorted, 0, n); Array.Sort(sorted); // Initialize the two multisets to store // sorted and the unordered elements SortedSet<int> m1 = new SortedSet<int>(); SortedSet<int> m2 = new SortedSet<int>(); // Initialize cost to store final answer int cost = 0; for (int i = 0; i < n; i++) { if (sorted[i] != arr[i]) { m1.Add(arr[i]); m2.Add(sorted[i]); // If both the multisets are equal, // the unordered subarray is sorted if (m1.SetEquals(m2)) { // The cost is difference // between mini and max cost += (m1.Max - m2.Min); // Clear the multisets to make // use of it again m1.Clear(); m2.Clear(); } } } return cost; } // Driver code public static void Main() { // Initialize the queries int[] arr = { 1, 7, 5, 2, 1, 8 }; Console.Write(minimum_cost(arr)); }} // This code is contributed by Shubham Singh", "e": 6679, "s": 5356, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find the minimum cost// to sort the array in ascending orderfunction minimum_cost(arr){ // Copy the arr into vector and sort it var sorted = arr.slice(); var n = arr.length; sorted.sort(); // Initialize the two multisets to store // sorted and the unordered elements var m1 = new Set(); var m2 = new Set(); // Initialize cost to store final answer var cost = 0; let areSetsEqual = (a, b) => a.size === b.size && [...a].every(value => b.has(value)); for (var i = 0; i < n; i++) { if (sorted[i] != arr[i]) { m1.add(arr[i]); m2.add(sorted[i]); // If both the multisets are equal, // the unordered subarray is sorted if (areSetsEqual(m1,m2)) { // The cost is difference // between mini and max cost += (Math.max(...Array.from(m1.values())) - Math.min(...Array.from(m2.values()))); // Clear the multisets to make // use of it again m1.clear(); m2.clear(); } } } return cost;} // Driver code// Initialize the queriesvar arr = [ 1, 7, 5, 2, 1, 8 ];document.write(minimum_cost(arr)); // This code is contributed by Shubham Singh</script>", "e": 8043, "s": 6679, "text": null }, { "code": null, "e": 8048, "s": 8046, "text": "6" }, { "code": null, "e": 8102, "s": 8050, "text": "Time Complexity: O(N * logN ) Auxiliary Space: O(N)" }, { "code": null, "e": 8116, "s": 8104, "text": "rakeshsahni" }, { "code": null, "e": 8134, "s": 8116, "text": "shubhamsingh84100" }, { "code": null, "e": 8149, "s": 8134, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 8164, "s": 8149, "text": "Algo-Geek 2021" }, { "code": null, "e": 8173, "s": 8164, "text": "subarray" }, { "code": null, "e": 8183, "s": 8173, "text": "Algo Geek" }, { "code": null, "e": 8190, "s": 8183, "text": "Arrays" }, { "code": null, "e": 8197, "s": 8190, "text": "Greedy" }, { "code": null, "e": 8205, "s": 8197, "text": "Sorting" }, { "code": null, "e": 8212, "s": 8205, "text": "Arrays" }, { "code": null, "e": 8219, "s": 8212, "text": "Greedy" }, { "code": null, "e": 8227, "s": 8219, "text": "Sorting" }, { "code": null, "e": 8325, "s": 8227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8396, "s": 8325, "text": "Number of ways to divide a N elements equally into group of at least 2" }, { "code": null, "e": 8444, "s": 8396, "text": "Sort strings on the basis of their numeric part" }, { "code": null, "e": 8520, "s": 8444, "text": "Count of ordered pairs (i, j) such that arr[i] and arr[j] concatenates to X" }, { "code": null, "e": 8617, "s": 8520, "text": "Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index" }, { "code": null, "e": 8672, "s": 8617, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 8687, "s": 8672, "text": "Arrays in Java" }, { "code": null, "e": 8733, "s": 8687, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 8801, "s": 8733, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 8845, "s": 8801, "text": "Top 50 Array Coding Problems for Interviews" } ]
Node.js os.platform() Method
13 Oct, 2021 The os.platform() method is an inbuilt application programming interface of the os module which is used to get the Operating system platform. Syntax: os.platform() Parameters: This method does not accept any parameters.Return Value: This method returns a string that represents operating system platform. The returned values can be one of these ‘aix’, ‘android’, ‘darwin’, ‘freebsd’, ‘linux’, ‘openbsd’, ‘sunos’, and ‘win32’. This values is set at compile time.Below examples illustrate the use of os.platform() method in Node.js:Example 1: javascript // Node.js program to demonstrate the // os.platform() method // Require os moduleconst os = require('os'); // Printing os.platform() valueconsole.log(os.platform()); Output: linux Example 2: This example is the alternative of first example. javascript // Node.js program to demonstrate the // os.platform() methodconsole.log(process.platform); Output: linux Example 3: javascript // Node.js program to demonstrate the // os.platform() method // Require os moduleconst os = require('os'); // Printing os.platform() valuevar platform = os.platform(); switch(platform) { case 'aix': console.log("IBM AIX platform"); break; case 'android': console.log("Android platform"); break; case 'darwin': console.log("Darwin platform(MacOS, IOS etc)"); break; case 'freebsd': console.log("FreeBSD Platform"); break; case 'linux': console.log("Linux Platform"); break; case 'openbsd': console.log("OpenBSD platform"); break; case 'sunos': console.log("SunOS platform"); break; case 'win32': console.log("windows platform"); break; default: console.log("unknown platform");} Output: Linux Platform Note: The above program will compile and run by using the node index.js command.Reference: https://nodejs.org/api/os.html#os_os_platform simmytarika5 Node.js-Methods Node.js-os-module Node.js 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": "\n13 Oct, 2021" }, { "code": null, "e": 171, "s": 28, "text": "The os.platform() method is an inbuilt application programming interface of the os module which is used to get the Operating system platform. " }, { "code": null, "e": 181, "s": 171, "text": "Syntax: " }, { "code": null, "e": 195, "s": 181, "text": "os.platform()" }, { "code": null, "e": 573, "s": 195, "text": "Parameters: This method does not accept any parameters.Return Value: This method returns a string that represents operating system platform. The returned values can be one of these ‘aix’, ‘android’, ‘darwin’, ‘freebsd’, ‘linux’, ‘openbsd’, ‘sunos’, and ‘win32’. This values is set at compile time.Below examples illustrate the use of os.platform() method in Node.js:Example 1: " }, { "code": null, "e": 584, "s": 573, "text": "javascript" }, { "code": "// Node.js program to demonstrate the // os.platform() method // Require os moduleconst os = require('os'); // Printing os.platform() valueconsole.log(os.platform());", "e": 760, "s": 584, "text": null }, { "code": null, "e": 770, "s": 760, "text": "Output: " }, { "code": null, "e": 776, "s": 770, "text": "linux" }, { "code": null, "e": 838, "s": 776, "text": "Example 2: This example is the alternative of first example. " }, { "code": null, "e": 849, "s": 838, "text": "javascript" }, { "code": "// Node.js program to demonstrate the // os.platform() methodconsole.log(process.platform);", "e": 944, "s": 849, "text": null }, { "code": null, "e": 954, "s": 944, "text": "Output: " }, { "code": null, "e": 960, "s": 954, "text": "linux" }, { "code": null, "e": 972, "s": 960, "text": "Example 3: " }, { "code": null, "e": 983, "s": 972, "text": "javascript" }, { "code": "// Node.js program to demonstrate the // os.platform() method // Require os moduleconst os = require('os'); // Printing os.platform() valuevar platform = os.platform(); switch(platform) { case 'aix': console.log(\"IBM AIX platform\"); break; case 'android': console.log(\"Android platform\"); break; case 'darwin': console.log(\"Darwin platform(MacOS, IOS etc)\"); break; case 'freebsd': console.log(\"FreeBSD Platform\"); break; case 'linux': console.log(\"Linux Platform\"); break; case 'openbsd': console.log(\"OpenBSD platform\"); break; case 'sunos': console.log(\"SunOS platform\"); break; case 'win32': console.log(\"windows platform\"); break; default: console.log(\"unknown platform\");}", "e": 1759, "s": 983, "text": null }, { "code": null, "e": 1769, "s": 1759, "text": "Output: " }, { "code": null, "e": 1784, "s": 1769, "text": "Linux Platform" }, { "code": null, "e": 1921, "s": 1784, "text": "Note: The above program will compile and run by using the node index.js command.Reference: https://nodejs.org/api/os.html#os_os_platform" }, { "code": null, "e": 1934, "s": 1921, "text": "simmytarika5" }, { "code": null, "e": 1950, "s": 1934, "text": "Node.js-Methods" }, { "code": null, "e": 1968, "s": 1950, "text": "Node.js-os-module" }, { "code": null, "e": 1976, "s": 1968, "text": "Node.js" }, { "code": null, "e": 1993, "s": 1976, "text": "Web Technologies" } ]
C++program to delete the content of a Binary File
11 Nov, 2019 This article explains how to delete the content of a Binary File. Given a binary file that contains the records of students, the task is to delete the record of the specified student. If the record of no such student exists, then print “record not found”. Examples: Input: roll no: 1 Output The deleted record is roll no: 1 name: vinay record successfully deleted Input: roll no: 2 Output: record not found Approach:In this example, the existing roll number of the student whose record is to be deleted is taken from the user and we will create a new file in which we will write all the records of the first file except the record to be deleted and then delete the first file and rename new file with the name of the first file Below are the various steps on how to do so: Step 1:Opening the file from which the record is to be deleted in reading mode here “he.dat” Step 2: Opening the file to which the new content is to be written in writing mode here “temp.dat” Step 3:Reading the file and Comparing the record roll no with that to be deleted Step 4: If during reading the roll number to be deleted exists then display it else write the record in temp.dat Step 5: Finally after reading the complete file delete the file “he.dat” and rename the new file “temp.dat” with “he.dat” Step 6: If in the file record exist then print the record and print record successfully deleted Step 7: If the roll number does not exists then print “record not found”. Standard Library Functions used: // to remove the file remove("name_of_file"); // to rename file1 as file2 rename("name-of_file1", "name_of_file2"); Below is the implementation of the above approach: // C++ program to delete the record// of a binary file #include <bits/stdc++.h> using namespace std; class abc { int roll; char name[20]; public: void deleteit(int); void testcase1(); void testcase2(); void putdata();}; // Code to display the data of the// data of the objectvoid abc::putdata(){ cout << "roll no: "; cout << roll; cout << "\nname: "; cout << name;} // code to delete// the content of the binary filevoid abc::deleteit(int rno){ int pos, flag = 0; ifstream ifs; ifs.open("he.dat", ios::in | ios::binary); ofstream ofs; ofs.open("temp.dat", ios::out | ios::binary); while (!ifs.eof()) { ifs.read((char*)this, sizeof(abc)); // if(ifs)checks the buffer record in the file if (ifs) { // comparing the roll no with // roll no of record to be deleted if (rno == roll) { flag = 1; cout << "The deleted record is \n"; // display the record putdata(); } else { // copy the record of "he" file to "temp" file ofs.write((char*)this, sizeof(abc)); } } } ofs.close(); ifs.close(); // delete the old file remove("he.dat"); // rename new file to the older file rename("temp.dat", "he.dat"); if (flag == 1) cout << "\nrecord successfully deleted \n"; else cout << "\nrecord not found \n";} // Sample input 1void abc::testcase1(){ int rno; // roll no to be searched rno = 1; // call deleteit function // with the roll no. of record to be deleted deleteit(rno);} // Sample input 2void abc::testcase2(){ int rno; // roll no to be searched rno = 4; // call deleteit function // with the roll no of record to be deleted deleteit(rno);} // Driver codeint main(){ abc s; // sample case 1 s.testcase1(); // sample case 2 s.testcase2(); return 0;} Output: to delete the record of the file C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Nov, 2019" }, { "code": null, "e": 94, "s": 28, "text": "This article explains how to delete the content of a Binary File." }, { "code": null, "e": 284, "s": 94, "text": "Given a binary file that contains the records of students, the task is to delete the record of the specified student. If the record of no such student exists, then print “record not found”." }, { "code": null, "e": 294, "s": 284, "text": "Examples:" }, { "code": null, "e": 439, "s": 294, "text": "Input:\nroll no: 1\nOutput\nThe deleted record is \nroll no: 1\nname: vinay\nrecord successfully deleted\n\nInput:\nroll no: 2\nOutput:\nrecord not found \n" }, { "code": null, "e": 760, "s": 439, "text": "Approach:In this example, the existing roll number of the student whose record is to be deleted is taken from the user and we will create a new file in which we will write all the records of the first file except the record to be deleted and then delete the first file and rename new file with the name of the first file" }, { "code": null, "e": 805, "s": 760, "text": "Below are the various steps on how to do so:" }, { "code": null, "e": 898, "s": 805, "text": "Step 1:Opening the file from which the record is to be deleted in reading mode here “he.dat”" }, { "code": null, "e": 997, "s": 898, "text": "Step 2: Opening the file to which the new content is to be written in writing mode here “temp.dat”" }, { "code": null, "e": 1078, "s": 997, "text": "Step 3:Reading the file and Comparing the record roll no with that to be deleted" }, { "code": null, "e": 1191, "s": 1078, "text": "Step 4: If during reading the roll number to be deleted exists then display it else write the record in temp.dat" }, { "code": null, "e": 1313, "s": 1191, "text": "Step 5: Finally after reading the complete file delete the file “he.dat” and rename the new file “temp.dat” with “he.dat”" }, { "code": null, "e": 1409, "s": 1313, "text": "Step 6: If in the file record exist then print the record and print record successfully deleted" }, { "code": null, "e": 1483, "s": 1409, "text": "Step 7: If the roll number does not exists then print “record not found”." }, { "code": null, "e": 1516, "s": 1483, "text": "Standard Library Functions used:" }, { "code": null, "e": 1634, "s": 1516, "text": "// to remove the file\nremove(\"name_of_file\");\n\n// to rename file1 as file2\nrename(\"name-of_file1\", \"name_of_file2\");\n" }, { "code": null, "e": 1685, "s": 1634, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ program to delete the record// of a binary file #include <bits/stdc++.h> using namespace std; class abc { int roll; char name[20]; public: void deleteit(int); void testcase1(); void testcase2(); void putdata();}; // Code to display the data of the// data of the objectvoid abc::putdata(){ cout << \"roll no: \"; cout << roll; cout << \"\\nname: \"; cout << name;} // code to delete// the content of the binary filevoid abc::deleteit(int rno){ int pos, flag = 0; ifstream ifs; ifs.open(\"he.dat\", ios::in | ios::binary); ofstream ofs; ofs.open(\"temp.dat\", ios::out | ios::binary); while (!ifs.eof()) { ifs.read((char*)this, sizeof(abc)); // if(ifs)checks the buffer record in the file if (ifs) { // comparing the roll no with // roll no of record to be deleted if (rno == roll) { flag = 1; cout << \"The deleted record is \\n\"; // display the record putdata(); } else { // copy the record of \"he\" file to \"temp\" file ofs.write((char*)this, sizeof(abc)); } } } ofs.close(); ifs.close(); // delete the old file remove(\"he.dat\"); // rename new file to the older file rename(\"temp.dat\", \"he.dat\"); if (flag == 1) cout << \"\\nrecord successfully deleted \\n\"; else cout << \"\\nrecord not found \\n\";} // Sample input 1void abc::testcase1(){ int rno; // roll no to be searched rno = 1; // call deleteit function // with the roll no. of record to be deleted deleteit(rno);} // Sample input 2void abc::testcase2(){ int rno; // roll no to be searched rno = 4; // call deleteit function // with the roll no of record to be deleted deleteit(rno);} // Driver codeint main(){ abc s; // sample case 1 s.testcase1(); // sample case 2 s.testcase2(); return 0;}", "e": 3700, "s": 1685, "text": null }, { "code": null, "e": 3708, "s": 3700, "text": "Output:" }, { "code": null, "e": 3741, "s": 3708, "text": "to delete the record of the file" }, { "code": null, "e": 3754, "s": 3741, "text": "C++ Programs" } ]
How to plot Andrews curves using Pandas in Python? - GeeksforGeeks
01 Aug, 2020 Andrews curves are used for visualizing high-dimensional data by mapping each observation onto a function. It preserves means, distance, and variances. It is given by formula: T(n) = x_1/sqrt(2) + x_2 sin(n) + x_3 cos(n) + x_4 sin(2n) + x_5 cos(2n) + ... Plotting Andrews curves on a graph can be done using the andrews_curves() method of the plotting module. This function generates a matplotlib plot of Andrews curves, for visualising clusters of multivariate data. Syntax: andrews_curves(frame, class_column, ax=None, samples=200, color=None, colormap=None, **kwargs) Parameters: frame: It is the data to be plotted. class_column: This is the name of the column containing class names. ax: This parameter is a matplotlib axes object. Its default value is None. samples: This parameter is the number of points to plot in each curve. color: This parameter is an optional parameter and it is the list or tuple of colors to use for the different classes. colormap: This parameter is the string/matplotlib colormap object. Its default value is None. Returns: This function returns an object of class matplotlip.axis.Axes Example 1: In the following example, A data frame is made from the CSV file and the data frame is used to plot andrews_curves. The used CSV file is here. Python3 # importing various packageimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt # making data frame from csv filedf = pd.read_csv( 'C:\\Users\\digital india\\Desktop\\pand.csv') # Creating Andrews curvesx = pd.plotting.andrews_curves(df, 'animal') # ploting the Curvex.plot() # Displayplt.show() Output: Example 2: Python3 # importing various packageimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt # making data frame from csv filedf = pd.read_csv( 'https://raw.github.com/pandas-dev/' 'pandas/master/pandas/tests/io/data/csv/iris.csv') # Creating Andrews curvesx = pd.plotting.andrews_curves(df, 'Name') # ploting the Curvex.plot() # Displayplt.show() Output: Python pandas-plotting Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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 Python | Get unique values from a list Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n01 Aug, 2020" }, { "code": null, "e": 24468, "s": 24292, "text": "Andrews curves are used for visualizing high-dimensional data by mapping each observation onto a function. It preserves means, distance, and variances. It is given by formula:" }, { "code": null, "e": 24547, "s": 24468, "text": "T(n) = x_1/sqrt(2) + x_2 sin(n) + x_3 cos(n) + x_4 sin(2n) + x_5 cos(2n) + ..." }, { "code": null, "e": 24760, "s": 24547, "text": "Plotting Andrews curves on a graph can be done using the andrews_curves() method of the plotting module. This function generates a matplotlib plot of Andrews curves, for visualising clusters of multivariate data." }, { "code": null, "e": 24863, "s": 24760, "text": "Syntax: andrews_curves(frame, class_column, ax=None, samples=200, color=None, colormap=None, **kwargs)" }, { "code": null, "e": 24875, "s": 24863, "text": "Parameters:" }, { "code": null, "e": 24912, "s": 24875, "text": "frame: It is the data to be plotted." }, { "code": null, "e": 24981, "s": 24912, "text": "class_column: This is the name of the column containing class names." }, { "code": null, "e": 25056, "s": 24981, "text": "ax: This parameter is a matplotlib axes object. Its default value is None." }, { "code": null, "e": 25127, "s": 25056, "text": "samples: This parameter is the number of points to plot in each curve." }, { "code": null, "e": 25246, "s": 25127, "text": "color: This parameter is an optional parameter and it is the list or tuple of colors to use for the different classes." }, { "code": null, "e": 25340, "s": 25246, "text": "colormap: This parameter is the string/matplotlib colormap object. Its default value is None." }, { "code": null, "e": 25411, "s": 25340, "text": "Returns: This function returns an object of class matplotlip.axis.Axes" }, { "code": null, "e": 25565, "s": 25411, "text": "Example 1: In the following example, A data frame is made from the CSV file and the data frame is used to plot andrews_curves. The used CSV file is here." }, { "code": null, "e": 25573, "s": 25565, "text": "Python3" }, { "code": "# importing various packageimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt # making data frame from csv filedf = pd.read_csv( 'C:\\\\Users\\\\digital india\\\\Desktop\\\\pand.csv') # Creating Andrews curvesx = pd.plotting.andrews_curves(df, 'animal') # ploting the Curvex.plot() # Displayplt.show()", "e": 25892, "s": 25573, "text": null }, { "code": null, "e": 25900, "s": 25892, "text": "Output:" }, { "code": null, "e": 25912, "s": 25900, "text": "Example 2: " }, { "code": null, "e": 25920, "s": 25912, "text": "Python3" }, { "code": "# importing various packageimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt # making data frame from csv filedf = pd.read_csv( 'https://raw.github.com/pandas-dev/' 'pandas/master/pandas/tests/io/data/csv/iris.csv') # Creating Andrews curvesx = pd.plotting.andrews_curves(df, 'Name') # ploting the Curvex.plot() # Displayplt.show()", "e": 26281, "s": 25920, "text": null }, { "code": null, "e": 26289, "s": 26281, "text": "Output:" }, { "code": null, "e": 26312, "s": 26289, "text": "Python pandas-plotting" }, { "code": null, "e": 26326, "s": 26312, "text": "Python-pandas" }, { "code": null, "e": 26333, "s": 26326, "text": "Python" }, { "code": null, "e": 26431, "s": 26333, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26463, "s": 26431, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26519, "s": 26463, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26561, "s": 26519, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26603, "s": 26561, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26625, "s": 26603, "text": "Defaultdict in Python" }, { "code": null, "e": 26664, "s": 26625, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26695, "s": 26664, "text": "Python | os.path.join() method" }, { "code": null, "e": 26750, "s": 26695, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26779, "s": 26750, "text": "Create a directory in Python" } ]
Does MySQL converts bool to tinyint(1) internally?
Yes, MySQL internally convert bool to tinyint(1) because tinyint is the smallest integer data type. You can also say the bool is synonym for tinyint(1). Let us first create a sample table: mysql> create table boolToTinyIntDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(20), -> isAgeGreaterThan18 bool -> ); Query OK, 0 rows affected (1.02 sec) Let us now check the description of table: mysql> desc boolToTinyIntDemo; This will produce the following output +--------------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------------+-------------+------+-----+---------+----------------+ | Id | int(11) | NO | PRI | NULL | auto_increment | | Name | varchar(20) | YES | | NULL | | | isAgeGreaterThan18 | tinyint(1) | YES | | NULL | | +--------------------+-------------+------+-----+---------+----------------+ 3 rows in set (0.00 sec) Look at the above sample output, the column isAgeGreaterThan18 data type is converted from bool to tinyint(1) internally. Following is the query to insert some records in the table using insert command: mysql> insert into boolToTinyIntDemo(Name,isAgeGreaterThan18) values('Larry',true); Query OK, 1 row affected (0.18 sec) mysql> insert into boolToTinyIntDemo(Name,isAgeGreaterThan18) values('Sam',false); Query OK, 1 row affected (0.14 sec) Following is the query to display records from the table using select command: mysql> select *from boolToTinyIntDemo; This will produce the following output +----+-------+--------------------+ | Id | Name | isAgeGreaterThan18 | +----+-------+--------------------+ | 1 | Larry | 1 | | 2 | Sam | 0 | +----+-------+--------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1162, "s": 1062, "text": "Yes, MySQL internally convert bool to tinyint(1) because tinyint is the smallest integer data type." }, { "code": null, "e": 1251, "s": 1162, "text": "You can also say the bool is synonym for tinyint(1). Let us first create a sample table:" }, { "code": null, "e": 1447, "s": 1251, "text": "mysql> create table boolToTinyIntDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Name varchar(20),\n -> isAgeGreaterThan18 bool\n -> );\nQuery OK, 0 rows affected (1.02 sec)" }, { "code": null, "e": 1490, "s": 1447, "text": "Let us now check the description of table:" }, { "code": null, "e": 1521, "s": 1490, "text": "mysql> desc boolToTinyIntDemo;" }, { "code": null, "e": 1560, "s": 1521, "text": "This will produce the following output" }, { "code": null, "e": 2124, "s": 1560, "text": "+--------------------+-------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------------+-------------+------+-----+---------+----------------+\n| Id | int(11) | NO | PRI | NULL | auto_increment |\n| Name | varchar(20) | YES | | NULL | |\n| isAgeGreaterThan18 | tinyint(1) | YES | | NULL | |\n+--------------------+-------------+------+-----+---------+----------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2246, "s": 2124, "text": "Look at the above sample output, the column isAgeGreaterThan18 data type is converted from bool to tinyint(1) internally." }, { "code": null, "e": 2327, "s": 2246, "text": "Following is the query to insert some records in the table using insert command:" }, { "code": null, "e": 2567, "s": 2327, "text": "mysql> insert into boolToTinyIntDemo(Name,isAgeGreaterThan18) values('Larry',true);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into boolToTinyIntDemo(Name,isAgeGreaterThan18) values('Sam',false);\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 2646, "s": 2567, "text": "Following is the query to display records from the table using select command:" }, { "code": null, "e": 2685, "s": 2646, "text": "mysql> select *from boolToTinyIntDemo;" }, { "code": null, "e": 2724, "s": 2685, "text": "This will produce the following output" }, { "code": null, "e": 2965, "s": 2724, "text": "+----+-------+--------------------+\n| Id | Name | isAgeGreaterThan18 |\n+----+-------+--------------------+\n| 1 | Larry | 1 |\n| 2 | Sam | 0 |\n+----+-------+--------------------+\n2 rows in set (0.00 sec)" } ]
Creating Reports with R Markdown. An explanation of writing a report... | by Jaemin Lee | Towards Data Science
It’s easy to turn python scripts into reports using Jupyter notebook or Google Colab. Did you know that you could also do the same for R scripts? In this tutorial, I’m going to demonstrate how to turn your R script into a report. We need to have two software installed. RR Studio — Free version R R Studio — Free version Make sure to download the package which lets you convert your R Markdown files into reports. You can run the command (shown below) in the console to download the package. install.packages("knitr") Under the “File” tab, click “New File” and “R Markdown”. Name your file and choose the default output format. You can always change the output format later. Once you hit “Ok”, you can now code and write a report on R Markdown. The highlighted section (or the cell) is where you can write your code. ```{r cars}YOU CAN WRITE YOUR CODE HERE``` And the non-highlighted section is where you can write your report. You can run the code in the entire cell by clicking the green run button on the upper right corner in the cell. Alternatively, you can hit Ctrl + Enter to only run the selected code. For you to knit R Markdown files, you may need to install a few packages. R studio will automatically detect that you are missing the necessary packages and it will ask you to download them. There are three ways of outputting your report. HTMLPDFMS Word HTML PDF MS Word HTML Output PDF Output MS Word Output I hope you find this post useful. Thank you for reading it!
[ { "code": null, "e": 318, "s": 172, "text": "It’s easy to turn python scripts into reports using Jupyter notebook or Google Colab. Did you know that you could also do the same for R scripts?" }, { "code": null, "e": 402, "s": 318, "text": "In this tutorial, I’m going to demonstrate how to turn your R script into a report." }, { "code": null, "e": 442, "s": 402, "text": "We need to have two software installed." }, { "code": null, "e": 467, "s": 442, "text": "RR Studio — Free version" }, { "code": null, "e": 469, "s": 467, "text": "R" }, { "code": null, "e": 493, "s": 469, "text": "R Studio — Free version" }, { "code": null, "e": 586, "s": 493, "text": "Make sure to download the package which lets you convert your R Markdown files into reports." }, { "code": null, "e": 664, "s": 586, "text": "You can run the command (shown below) in the console to download the package." }, { "code": null, "e": 690, "s": 664, "text": "install.packages(\"knitr\")" }, { "code": null, "e": 747, "s": 690, "text": "Under the “File” tab, click “New File” and “R Markdown”." }, { "code": null, "e": 847, "s": 747, "text": "Name your file and choose the default output format. You can always change the output format later." }, { "code": null, "e": 917, "s": 847, "text": "Once you hit “Ok”, you can now code and write a report on R Markdown." }, { "code": null, "e": 989, "s": 917, "text": "The highlighted section (or the cell) is where you can write your code." }, { "code": null, "e": 1032, "s": 989, "text": "```{r cars}YOU CAN WRITE YOUR CODE HERE```" }, { "code": null, "e": 1100, "s": 1032, "text": "And the non-highlighted section is where you can write your report." }, { "code": null, "e": 1212, "s": 1100, "text": "You can run the code in the entire cell by clicking the green run button on the upper right corner in the cell." }, { "code": null, "e": 1283, "s": 1212, "text": "Alternatively, you can hit Ctrl + Enter to only run the selected code." }, { "code": null, "e": 1474, "s": 1283, "text": "For you to knit R Markdown files, you may need to install a few packages. R studio will automatically detect that you are missing the necessary packages and it will ask you to download them." }, { "code": null, "e": 1522, "s": 1474, "text": "There are three ways of outputting your report." }, { "code": null, "e": 1537, "s": 1522, "text": "HTMLPDFMS Word" }, { "code": null, "e": 1542, "s": 1537, "text": "HTML" }, { "code": null, "e": 1546, "s": 1542, "text": "PDF" }, { "code": null, "e": 1554, "s": 1546, "text": "MS Word" }, { "code": null, "e": 1566, "s": 1554, "text": "HTML Output" }, { "code": null, "e": 1577, "s": 1566, "text": "PDF Output" }, { "code": null, "e": 1592, "s": 1577, "text": "MS Word Output" } ]
MongoDB $push in nested array?
Here, $push can be used to add new documents in nested array. To understand the above $push concept, let us create a collection with nested array document. The query to create a collection with document is as follows: >db.nestedArrayDemo.insertOne({"EmployeeName":"Larry","EmployeeSalary":9000,"EmployeeDetails": [{"EmployeeDOB":new Date('1990-01-21'),"EmployeeDepartment":"ComputerScience","EmployeeProject": [{"Technology":"C","Duration":6},{"Technology":"Java","Duration":7}]}]}); The following is the output: { "acknowledged" : true, "insertedId" : ObjectId("5c6d73090c3d5054b766a76e") } Now you can display documents from a collection with the help of find() method. The query is as follows: > db.nestedArrayDemo.find().pretty(); The following is the output: { "_id" : ObjectId("5c6d73090c3d5054b766a76e"), "EmployeeName" : "Larry", "EmployeeSalary" : 9000, "EmployeeDetails" : [ { "EmployeeDOB" : ISODate("1990-01-21T00:00:00Z"), "EmployeeDepartment" : "ComputerScience", "EmployeeProject" : [ { "Technology" : "C", "Duration" : 6 }, { "Technology" : "Java", "Duration" : 7 } ] } ] } Here is the demo of $push in nested array to add new documents. The query is as follows: >db.nestedArrayDemo.update({"_id":ObjectId("5c6d73090c3d5054b766a76e"), "EmployeeDetails.EmployeeDepartment":"ComputerScience"}, {"$push": {"EmployeeDetails.$.EmployeeProject": {"Technology":"Python", "Duration":4 }}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) In the above query, I have added a document {"Technology":"Python", "Duration":4 } in nested array. Now display the documents from the collection once again. The query is as follows: > db.nestedArrayDemo.find().pretty(); The following is the output: { "_id" : ObjectId("5c6d73090c3d5054b766a76e"), "EmployeeName" : "Larry", "EmployeeSalary" : 9000, "EmployeeDetails" : [ { "EmployeeDOB" : ISODate("1990-01-21T00:00:00Z"), "EmployeeDepartment" : "ComputerScience", "EmployeeProject" : [ { "Technology" : "C", "Duration" : 6 }, { "Technology" : "Java", "Duration" : 7 }, { "Technology" : "Python", "Duration" : 4 } ] } ] }
[ { "code": null, "e": 1280, "s": 1062, "text": "Here, $push can be used to add new documents in nested array. To understand the above $push concept, let us create a collection with nested array document. The query to create a collection with document is as follows:" }, { "code": null, "e": 1552, "s": 1280, "text": ">db.nestedArrayDemo.insertOne({\"EmployeeName\":\"Larry\",\"EmployeeSalary\":9000,\"EmployeeDetails\":\n [{\"EmployeeDOB\":new Date('1990-01-21'),\"EmployeeDepartment\":\"ComputerScience\",\"EmployeeProject\":\n [{\"Technology\":\"C\",\"Duration\":6},{\"Technology\":\"Java\",\"Duration\":7}]}]});" }, { "code": null, "e": 1581, "s": 1552, "text": "The following is the output:" }, { "code": null, "e": 1666, "s": 1581, "text": "{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6d73090c3d5054b766a76e\")\n}" }, { "code": null, "e": 1771, "s": 1666, "text": "Now you can display documents from a collection with the help of find() method. The query is as follows:" }, { "code": null, "e": 1809, "s": 1771, "text": "> db.nestedArrayDemo.find().pretty();" }, { "code": null, "e": 1838, "s": 1809, "text": "The following is the output:" }, { "code": null, "e": 2335, "s": 1838, "text": "{\n \"_id\" : ObjectId(\"5c6d73090c3d5054b766a76e\"),\n \"EmployeeName\" : \"Larry\",\n \"EmployeeSalary\" : 9000,\n \"EmployeeDetails\" : [\n {\n \"EmployeeDOB\" : ISODate(\"1990-01-21T00:00:00Z\"),\n \"EmployeeDepartment\" : \"ComputerScience\",\n \"EmployeeProject\" : [\n {\n \"Technology\" : \"C\",\n \"Duration\" : 6\n },\n {\n \"Technology\" : \"Java\",\n \"Duration\" : 7\n }\n ]\n }\n ]\n}" }, { "code": null, "e": 2424, "s": 2335, "text": "Here is the demo of $push in nested array to add new documents. The query is as follows:" }, { "code": null, "e": 2719, "s": 2424, "text": ">db.nestedArrayDemo.update({\"_id\":ObjectId(\"5c6d73090c3d5054b766a76e\"),\n \"EmployeeDetails.EmployeeDepartment\":\"ComputerScience\"}, {\"$push\":\n {\"EmployeeDetails.$.EmployeeProject\": {\"Technology\":\"Python\", \"Duration\":4 }}});\n WriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })" }, { "code": null, "e": 2902, "s": 2719, "text": "In the above query, I have added a document {\"Technology\":\"Python\", \"Duration\":4 } in nested array. Now display the documents from the collection once again. The query is as follows:" }, { "code": null, "e": 2940, "s": 2902, "text": "> db.nestedArrayDemo.find().pretty();" }, { "code": null, "e": 2969, "s": 2940, "text": "The following is the output:" }, { "code": null, "e": 3565, "s": 2969, "text": "{\n \"_id\" : ObjectId(\"5c6d73090c3d5054b766a76e\"),\n \"EmployeeName\" : \"Larry\",\n \"EmployeeSalary\" : 9000,\n \"EmployeeDetails\" : [\n {\n \"EmployeeDOB\" : ISODate(\"1990-01-21T00:00:00Z\"),\n \"EmployeeDepartment\" : \"ComputerScience\",\n \"EmployeeProject\" : [\n {\n \"Technology\" : \"C\",\n \"Duration\" : 6\n },\n {\n \"Technology\" : \"Java\",\n \"Duration\" : 7\n },\n {\n \"Technology\" : \"Python\",\n \"Duration\" : 4\n }\n ]\n }\n ]\n}" } ]
Maximum sum of smallest and second smallest in an array - GeeksforGeeks
01 Sep, 2021 Input : arr[] = [4, 3, 1, 5, 6] Output : 11 Subarrays with smallest and second smallest are, [4, 3] smallest = 3 second smallest = 4 [4, 3, 1] smallest = 1 second smallest = 3 [4, 3, 1, 5] smallest = 1 second smallest = 3 [4, 3, 1, 5, 6] smallest = 1 second smallest = 3 [3, 1] smallest = 1 second smallest = 3 [3, 1, 5] smallest = 1 second smallest = 3 [3, 1, 5, 6] smallest = 1 second smallest = 3 [1, 5] smallest = 1 second smallest = 5 [1, 5, 6] smallest = 1 second smallest = 5 [5, 6] smallest = 5 second smallest = 6 Maximum sum among all above choices is, 5 + 6 = 11 Input : arr[] = {5, 4, 3, 1, 6} Output : 9 A simple solution is to generate all subarrays, find sum of smallest and second smallest of every subarray. Finally return maximum of all sums.An efficient solution is based on the observation that this problem reduces to finding a maximum sum of two consecutive elements in array. If (x,y) is the pair ,such that (x+y) is the answer , then x and y must be consecutive elements in the array. For a subarray with 2 elements , 1st and 2nd smallest elements are those 2 elements. Now x and y are present in some subarray such thatthey are the endpoints. Now, x, y must be the smallest 2 elements of that subarray. If there are other elements Z1 , Z2, ......., ZK between x and y, they are greater than or equal to x and y, If there is one element z between x and y , then the smaller subarray with the elements max(x,y) and z , should be the answer , because max(x,y) + z >= x + y If there are more than one elements between x and y , then the subarray within x and y will have all consecutive elements (Zi + Zi+1) >= (x+y), so (x,y) pair can’t be the answer. So, by contradictions, x and y must be consecutive elements in the array. CPP JAVA Python3 C# PHP Javascript // C++ program to get max sum with smallest// and second smallest element from any subarray#include <bits/stdc++.h>using namespace std; /* Method returns maximum obtainable sum value of smallest and the second smallest value taken over all possible subarrays */int pairWithMaxSum(int arr[], int N){ if (N < 2) return -1; // Find two consecutive elements with maximum // sum. int res = arr[0] + arr[1]; for (int i=1; i<N-1; i++) res = max(res, arr[i] + arr[i+1]); return res;} // Driver code to test above methodsint main(){ int arr[] = {4, 3, 1, 5, 6}; int N = sizeof(arr) / sizeof(int); cout << pairWithMaxSum(arr, N) << endl; return 0;} // Java program to get max sum with smallest// and second smallest element from any subarrayimport java.lang.*;class num{ // Method returns maximum obtainable sum value// of smallest and the second smallest value// taken over all possible subarrays */static int pairWithMaxSum(int[] arr, int N){if (N < 2) return -1; // Find two consecutive elements with maximum// sum.int res = arr[0] + arr[1];for (int i=1; i<N-1; i++) res = Math.max(res, arr[i] + arr[i+1]); return res;} // Driver programpublic static void main(String[] args){ int arr[] = {4, 3, 1, 5, 6}; int N = arr.length; System.out.println(pairWithMaxSum(arr, N));}}//This code is contributed by//Smitha Dinesh Semwal # Python 3 program to get max# sum with smallest and second# smallest element from any# subarray # Method returns maximum obtainable# sum value of smallest and the# second smallest value taken# over all possible subarraysdef pairWithMaxSum(arr, N): if (N < 2): return -1 # Find two consecutive elements with # maximum sum. res = arr[0] + arr[1] for i in range(1, N-1): res = max(res, arr[i] + arr[i + 1]) return res # Driver codearr = [4, 3, 1, 5, 6]N = len(arr) print(pairWithMaxSum(arr, N)) # This code is contributed by Smitha Dinesh Semwal // C# program to get max sum with smallest// and second smallest element from any subarrayusing System; class GFG { // Method returns maximum obtainable sum value// of smallest and the second smallest value// taken over all possible subarraysstatic int pairWithMaxSum(int []arr, int N){ if (N < 2) return -1; // Find two consecutive elements// with maximum sum.int res = arr[0] + arr[1];for (int i = 1; i < N - 1; i++) res = Math.Max(res, arr[i] + arr[i + 1]); return res;} // Driver codepublic static void Main(){ int []arr = {4, 3, 1, 5, 6}; int N = arr.Length; Console.Write(pairWithMaxSum(arr, N));}} // This code is contributed by Nitin Mittal. <?php// PHP program to get max sum with smallest// and second smallest element from any subarray /* Method returns maximum obtainable sum value of smallest and the second smallest value taken over all possible subarrays */function pairWithMaxSum( $arr, $N){ if ($N < 2) return -1; // Find two consecutive // elements with maximum // sum. $res = $arr[0] + $arr[1]; for($i = 1; $i < $N - 1; $i++) $res = max($res, $arr[$i] + $arr[$i + 1]); return $res;} // Driver Code $arr = array(4, 3, 1, 5, 6); $N = count($arr); echo pairWithMaxSum($arr, $N); // This code is contributed by anuj_67.?> // javascript program to get max sum with smallest// and second smallest element from any subarray // Method returns maximum obtainable sum value// of smallest and the second smallest value// taken over all possible subarrays function pairWithMaxSum(arr, N){ if (N < 2) return -1; // Find two consecutive elements// with maximum sum. var res = arr[0] + arr[1];for (var i = 1; i < N - 1; i++) res = Math.max(res, arr[i] + arr[i + 1]); return res;} // Driver code var arr = [4, 3, 1, 5, 6] var N = arr.length; document.write(pairWithMaxSum(arr, N)); // This code is contributed by bunnyram19. Output: 11 Time Complexity : O(n)Thanks to Md Mishfaq Ahmed for suggesting this approach.This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal vt_m bunnyram19 sourashis69 Arrays Stack Arrays Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Check for Balanced Brackets in an expression (well-formedness) using Stack Program for Tower of Hanoi
[ { "code": null, "e": 24730, "s": 24702, "text": "\n01 Sep, 2021" }, { "code": null, "e": 25428, "s": 24730, "text": "Input : arr[] = [4, 3, 1, 5, 6]\nOutput : 11\nSubarrays with smallest and second smallest are,\n[4, 3] smallest = 3 second smallest = 4\n[4, 3, 1] smallest = 1 second smallest = 3\n[4, 3, 1, 5] smallest = 1 second smallest = 3\n[4, 3, 1, 5, 6] smallest = 1 second smallest = 3\n[3, 1] smallest = 1 second smallest = 3\n[3, 1, 5] smallest = 1 second smallest = 3\n[3, 1, 5, 6] smallest = 1 second smallest = 3\n[1, 5] smallest = 1 second smallest = 5\n[1, 5, 6] smallest = 1 second smallest = 5\n[5, 6] smallest = 5 second smallest = 6\nMaximum sum among all above choices is, 5 + 6 = 11\n\nInput : arr[] = {5, 4, 3, 1, 6}\nOutput : 9" }, { "code": null, "e": 25713, "s": 25430, "text": "A simple solution is to generate all subarrays, find sum of smallest and second smallest of every subarray. Finally return maximum of all sums.An efficient solution is based on the observation that this problem reduces to finding a maximum sum of two consecutive elements in array. " }, { "code": null, "e": 25823, "s": 25713, "text": "If (x,y) is the pair ,such that (x+y) is the answer , then x and y must be consecutive elements in the array." }, { "code": null, "e": 25908, "s": 25823, "text": "For a subarray with 2 elements , 1st and 2nd smallest elements are those 2 elements." }, { "code": null, "e": 25982, "s": 25908, "text": "Now x and y are present in some subarray such thatthey are the endpoints." }, { "code": null, "e": 26152, "s": 25982, "text": "Now, x, y must be the smallest 2 elements of that subarray. If there are other elements Z1 , Z2, ......., ZK between x and y, they are greater than or equal to x and y," }, { "code": null, "e": 26310, "s": 26152, "text": "If there is one element z between x and y , then the smaller subarray with the elements max(x,y) and z , should be the answer , because max(x,y) + z >= x + y" }, { "code": null, "e": 26492, "s": 26310, "text": "If there are more than one elements between x and y , then the subarray within x and y will have all consecutive elements (Zi + Zi+1) >= (x+y), so (x,y) pair can’t be the answer. " }, { "code": null, "e": 26567, "s": 26492, "text": "So, by contradictions, x and y must be consecutive elements in the array. " }, { "code": null, "e": 26571, "s": 26567, "text": "CPP" }, { "code": null, "e": 26576, "s": 26571, "text": "JAVA" }, { "code": null, "e": 26584, "s": 26576, "text": "Python3" }, { "code": null, "e": 26587, "s": 26584, "text": "C#" }, { "code": null, "e": 26591, "s": 26587, "text": "PHP" }, { "code": null, "e": 26602, "s": 26591, "text": "Javascript" }, { "code": "// C++ program to get max sum with smallest// and second smallest element from any subarray#include <bits/stdc++.h>using namespace std; /* Method returns maximum obtainable sum value of smallest and the second smallest value taken over all possible subarrays */int pairWithMaxSum(int arr[], int N){ if (N < 2) return -1; // Find two consecutive elements with maximum // sum. int res = arr[0] + arr[1]; for (int i=1; i<N-1; i++) res = max(res, arr[i] + arr[i+1]); return res;} // Driver code to test above methodsint main(){ int arr[] = {4, 3, 1, 5, 6}; int N = sizeof(arr) / sizeof(int); cout << pairWithMaxSum(arr, N) << endl; return 0;}", "e": 27285, "s": 26602, "text": null }, { "code": "// Java program to get max sum with smallest// and second smallest element from any subarrayimport java.lang.*;class num{ // Method returns maximum obtainable sum value// of smallest and the second smallest value// taken over all possible subarrays */static int pairWithMaxSum(int[] arr, int N){if (N < 2) return -1; // Find two consecutive elements with maximum// sum.int res = arr[0] + arr[1];for (int i=1; i<N-1; i++) res = Math.max(res, arr[i] + arr[i+1]); return res;} // Driver programpublic static void main(String[] args){ int arr[] = {4, 3, 1, 5, 6}; int N = arr.length; System.out.println(pairWithMaxSum(arr, N));}}//This code is contributed by//Smitha Dinesh Semwal", "e": 27977, "s": 27285, "text": null }, { "code": "# Python 3 program to get max# sum with smallest and second# smallest element from any# subarray # Method returns maximum obtainable# sum value of smallest and the# second smallest value taken# over all possible subarraysdef pairWithMaxSum(arr, N): if (N < 2): return -1 # Find two consecutive elements with # maximum sum. res = arr[0] + arr[1] for i in range(1, N-1): res = max(res, arr[i] + arr[i + 1]) return res # Driver codearr = [4, 3, 1, 5, 6]N = len(arr) print(pairWithMaxSum(arr, N)) # This code is contributed by Smitha Dinesh Semwal", "e": 28573, "s": 27977, "text": null }, { "code": "// C# program to get max sum with smallest// and second smallest element from any subarrayusing System; class GFG { // Method returns maximum obtainable sum value// of smallest and the second smallest value// taken over all possible subarraysstatic int pairWithMaxSum(int []arr, int N){ if (N < 2) return -1; // Find two consecutive elements// with maximum sum.int res = arr[0] + arr[1];for (int i = 1; i < N - 1; i++) res = Math.Max(res, arr[i] + arr[i + 1]); return res;} // Driver codepublic static void Main(){ int []arr = {4, 3, 1, 5, 6}; int N = arr.Length; Console.Write(pairWithMaxSum(arr, N));}} // This code is contributed by Nitin Mittal.", "e": 29242, "s": 28573, "text": null }, { "code": "<?php// PHP program to get max sum with smallest// and second smallest element from any subarray /* Method returns maximum obtainable sum value of smallest and the second smallest value taken over all possible subarrays */function pairWithMaxSum( $arr, $N){ if ($N < 2) return -1; // Find two consecutive // elements with maximum // sum. $res = $arr[0] + $arr[1]; for($i = 1; $i < $N - 1; $i++) $res = max($res, $arr[$i] + $arr[$i + 1]); return $res;} // Driver Code $arr = array(4, 3, 1, 5, 6); $N = count($arr); echo pairWithMaxSum($arr, $N); // This code is contributed by anuj_67.?>", "e": 29917, "s": 29242, "text": null }, { "code": "// javascript program to get max sum with smallest// and second smallest element from any subarray // Method returns maximum obtainable sum value// of smallest and the second smallest value// taken over all possible subarrays function pairWithMaxSum(arr, N){ if (N < 2) return -1; // Find two consecutive elements// with maximum sum. var res = arr[0] + arr[1];for (var i = 1; i < N - 1; i++) res = Math.max(res, arr[i] + arr[i + 1]); return res;} // Driver code var arr = [4, 3, 1, 5, 6] var N = arr.length; document.write(pairWithMaxSum(arr, N)); // This code is contributed by bunnyram19.", "e": 30539, "s": 29917, "text": null }, { "code": null, "e": 30549, "s": 30539, "text": "Output: " }, { "code": null, "e": 30552, "s": 30549, "text": "11" }, { "code": null, "e": 31054, "s": 30552, "text": "Time Complexity : O(n)Thanks to Md Mishfaq Ahmed for suggesting this approach.This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31067, "s": 31054, "text": "nitin mittal" }, { "code": null, "e": 31072, "s": 31067, "text": "vt_m" }, { "code": null, "e": 31083, "s": 31072, "text": "bunnyram19" }, { "code": null, "e": 31095, "s": 31083, "text": "sourashis69" }, { "code": null, "e": 31102, "s": 31095, "text": "Arrays" }, { "code": null, "e": 31108, "s": 31102, "text": "Stack" }, { "code": null, "e": 31115, "s": 31108, "text": "Arrays" }, { "code": null, "e": 31121, "s": 31115, "text": "Stack" }, { "code": null, "e": 31219, "s": 31121, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31287, "s": 31219, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 31335, "s": 31287, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 31379, "s": 31335, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 31411, "s": 31379, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31434, "s": 31411, "text": "Introduction to Arrays" }, { "code": null, "e": 31482, "s": 31434, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 31502, "s": 31482, "text": "Stack Class in Java" }, { "code": null, "e": 31518, "s": 31502, "text": "Stack in Python" }, { "code": null, "e": 31593, "s": 31518, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Tryit Editor v3.7
Tryit: change innerHTML
[]
decimal keyword in C# - GeeksforGeeks
22 Jun, 2020 Keywords are the words in a language that are used for some internal process or represent some predefined actions. decimal is a keyword that is used to declare a variable that can store a floating type value from the range of ±1.0 x 10-28 to ±7.9228 x 1028. It is an alias of System.Decimal and occupies 16 bytes (128 bits) in the memory. Syntax: decimal variable_name = value; We have to use ‘m’ or ‘M’ as a suffix with the literal, to represent a decimal value. Example: Input: 7271.6521M Output: num: 7271.6521 Size of a decimal variable: 16 Input: -371.83436 Output: Type of num: System.Decimal num: -371.83436 Size of a decimal variable: 16 Example 1: // C# program for decimal keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // char variable declaration decimal num1 = 7271.6521M; // to print value Console.WriteLine("num: " + num1); // to print size of a decimal Console.WriteLine("Size of a decimal variable: " + sizeof(decimal)); }} Output: num: 7271.6521 Size of a decimal variable: 16 Example 2: // C# program for decimal keywordusing System;using System.Text; namespace geeks {class GFG { static void Main(string[] args) { // char variable declaration decimal num1 = -371.83436m; // to print type of variable Console.WriteLine("Type of num: " + num1.GetType()); // to print value Console.WriteLine("num: " + num1); // to print size of a decimal Console.WriteLine("Size of a decimal variable: " + sizeof(decimal)); // hit ENTER to exit Console.ReadLine(); }}} Output: Type of num: System.Decimal num: -371.83436 Size of a decimal variable: 16 CSharp-keyword C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Partial Classes in C# C# | Inheritance C# | List Class Difference between Hashtable and Dictionary in C# Lambda Expressions in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n22 Jun, 2020" }, { "code": null, "e": 24417, "s": 24302, "text": "Keywords are the words in a language that are used for some internal process or represent some predefined actions." }, { "code": null, "e": 24641, "s": 24417, "text": "decimal is a keyword that is used to declare a variable that can store a floating type value from the range of ±1.0 x 10-28 to ±7.9228 x 1028. It is an alias of System.Decimal and occupies 16 bytes (128 bits) in the memory." }, { "code": null, "e": 24649, "s": 24641, "text": "Syntax:" }, { "code": null, "e": 24680, "s": 24649, "text": "decimal variable_name = value;" }, { "code": null, "e": 24766, "s": 24680, "text": "We have to use ‘m’ or ‘M’ as a suffix with the literal, to represent a decimal value." }, { "code": null, "e": 24775, "s": 24766, "text": "Example:" }, { "code": null, "e": 24976, "s": 24775, "text": "Input: 7271.6521M\n\nOutput: num: 7271.6521\n Size of a decimal variable: 16\n\nInput: -371.83436\n\nOutput: Type of num: System.Decimal\n num: -371.83436\n Size of a decimal variable: 16\n" }, { "code": null, "e": 24987, "s": 24976, "text": "Example 1:" }, { "code": "// C# program for decimal keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // char variable declaration decimal num1 = 7271.6521M; // to print value Console.WriteLine(\"num: \" + num1); // to print size of a decimal Console.WriteLine(\"Size of a decimal variable: \" + sizeof(decimal)); }}", "e": 25367, "s": 24987, "text": null }, { "code": null, "e": 25375, "s": 25367, "text": "Output:" }, { "code": null, "e": 25422, "s": 25375, "text": "num: 7271.6521\nSize of a decimal variable: 16\n" }, { "code": null, "e": 25433, "s": 25422, "text": "Example 2:" }, { "code": "// C# program for decimal keywordusing System;using System.Text; namespace geeks {class GFG { static void Main(string[] args) { // char variable declaration decimal num1 = -371.83436m; // to print type of variable Console.WriteLine(\"Type of num: \" + num1.GetType()); // to print value Console.WriteLine(\"num: \" + num1); // to print size of a decimal Console.WriteLine(\"Size of a decimal variable: \" + sizeof(decimal)); // hit ENTER to exit Console.ReadLine(); }}}", "e": 25987, "s": 25433, "text": null }, { "code": null, "e": 25995, "s": 25987, "text": "Output:" }, { "code": null, "e": 26071, "s": 25995, "text": "Type of num: System.Decimal\nnum: -371.83436\nSize of a decimal variable: 16\n" }, { "code": null, "e": 26086, "s": 26071, "text": "CSharp-keyword" }, { "code": null, "e": 26089, "s": 26086, "text": "C#" }, { "code": null, "e": 26187, "s": 26089, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26205, "s": 26187, "text": "Destructors in C#" }, { "code": null, "e": 26228, "s": 26205, "text": "Extension Method in C#" }, { "code": null, "e": 26256, "s": 26228, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26296, "s": 26256, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26339, "s": 26296, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 26361, "s": 26339, "text": "Partial Classes in C#" }, { "code": null, "e": 26378, "s": 26361, "text": "C# | Inheritance" }, { "code": null, "e": 26394, "s": 26378, "text": "C# | List Class" }, { "code": null, "e": 26444, "s": 26394, "text": "Difference between Hashtable and Dictionary in C#" } ]
multimap swap() function in C++ STL
In this article, we will be discussing the working, syntax, and examples of multimap swap() function in C++ STL. Multimaps are the associative containers, which are similar to map containers. It also facilitates to store the elements formed by a combination of key-value and mapped value in a specific order. In a multimap container there can be multiple elements associated with the same key. The data is internally always sorted with the help of its associated keys. multimap::swap() function is an inbuilt function in C++ STL, which is defined in <map> header file. swap() is used to swap the content of the two multimap containers. This function swaps the values of two multimap containers irrespective of the size of both the multimap containers. When this function gets called it takes the parameter which is another multimap container and swaps the contents with the associated container. multimap_name.swap(multimap& multimap_name2); The function accepts the following parameter(s) − map_name2 − This is another multimap container’s object whose data we want to swap with the associated multimap container. map_name2 − This is another multimap container’s object whose data we want to swap with the associated multimap container. This function returns nothing. Input std::multimap<char, int> odd, eve; odd.insert(make_pair(‘a’, 1)); odd.insert(make_pair(‘b’, 3)); odd.insert(make_pair(‘c’, 5)); eve.insert(make_pair(‘d’, 2)); eve.insert(make_pair(‘e’, 4)); eve.insert(make_pair(‘f’, 6)); odd.swap(eve); Output Odd: d: 2 e:4 f:6 Eve: a:1 b:3 c:5 Live Demo #include<iostream> #include<map> using namespace std; int main(){ multimap<int,int > mul_1; multimap<int,int> mul_2; //declaring iterator to traverse the elements multimap<int,int>:: iterator i; //inserting elements to multimap1 mul_1.insert({1,10}); mul_1.insert({2,20}); mul_1.insert({3,30}); mul_1.insert({4,40}); mul_1.insert({5,50}); //inserting elements to multimap2 mul_2.insert({6,60}); mul_2.insert({7,70}); mul_2.insert({8,80}); mul_2.insert({9,90}); //calling swap to swap the elements mul_1.swap(mul_2); //elements of multimap1 cout<<"Elements in multimap1 are: "<<"\n"; for( i = mul_1.begin(); i!= mul_1.end(); i++){ cout<<(*i).first<<" "<< (*i).second << "\n"; } //elements of multimap2 cout<<"\nElements in multimap2 are: "; for( i = mul_2.begin(); i!= mul_2.end(); i++){ cout<<(*i).first<<" "<<(*i).second << "\n"; } } If we run the above code it will generate the following output − Elements in multimap1 are: 6 60 7 70 8 80 9 90 Elements in multimap2 are: 1 10 2 20 3 30 4 40 5 50
[ { "code": null, "e": 1175, "s": 1062, "text": "In this article, we will be discussing the working, syntax, and examples of multimap swap() function in C++ STL." }, { "code": null, "e": 1531, "s": 1175, "text": "Multimaps are the associative containers, which are similar to map containers. It also facilitates to store the elements formed by a combination of key-value and mapped value in a specific order. In a multimap container there can be multiple elements associated with the same key. The data is internally always sorted with the help of its associated keys." }, { "code": null, "e": 1814, "s": 1531, "text": "multimap::swap() function is an inbuilt function in C++ STL, which is defined in <map> header file. swap() is used to swap the content of the two multimap containers. This function swaps the values of two multimap containers irrespective of the size of both the multimap containers." }, { "code": null, "e": 1958, "s": 1814, "text": "When this function gets called it takes the parameter which is another multimap container and swaps the contents with the associated container." }, { "code": null, "e": 2004, "s": 1958, "text": "multimap_name.swap(multimap& multimap_name2);" }, { "code": null, "e": 2054, "s": 2004, "text": "The function accepts the following parameter(s) −" }, { "code": null, "e": 2177, "s": 2054, "text": "map_name2 − This is another multimap container’s object whose data we want to swap with the associated multimap container." }, { "code": null, "e": 2300, "s": 2177, "text": "map_name2 − This is another multimap container’s object whose data we want to swap with the associated multimap container." }, { "code": null, "e": 2331, "s": 2300, "text": "This function returns nothing." }, { "code": null, "e": 2338, "s": 2331, "text": "Input " }, { "code": null, "e": 2574, "s": 2338, "text": "std::multimap<char, int> odd, eve;\nodd.insert(make_pair(‘a’, 1));\nodd.insert(make_pair(‘b’, 3));\nodd.insert(make_pair(‘c’, 5));\neve.insert(make_pair(‘d’, 2));\neve.insert(make_pair(‘e’, 4));\neve.insert(make_pair(‘f’, 6));\nodd.swap(eve);" }, { "code": null, "e": 2582, "s": 2574, "text": "Output " }, { "code": null, "e": 2617, "s": 2582, "text": "Odd: d: 2 e:4 f:6\nEve: a:1 b:3 c:5" }, { "code": null, "e": 2628, "s": 2617, "text": " Live Demo" }, { "code": null, "e": 3553, "s": 2628, "text": "#include<iostream>\n#include<map>\nusing namespace std;\nint main(){\n multimap<int,int > mul_1;\n multimap<int,int> mul_2;\n //declaring iterator to traverse the elements\n multimap<int,int>:: iterator i;\n //inserting elements to multimap1\n mul_1.insert({1,10});\n mul_1.insert({2,20});\n mul_1.insert({3,30});\n mul_1.insert({4,40});\n mul_1.insert({5,50});\n //inserting elements to multimap2\n mul_2.insert({6,60});\n mul_2.insert({7,70});\n mul_2.insert({8,80});\n mul_2.insert({9,90});\n //calling swap to swap the elements\n mul_1.swap(mul_2);\n //elements of multimap1\n cout<<\"Elements in multimap1 are: \"<<\"\\n\";\n for( i = mul_1.begin(); i!= mul_1.end(); i++){\n cout<<(*i).first<<\" \"<< (*i).second << \"\\n\";\n }\n //elements of multimap2\n cout<<\"\\nElements in multimap2 are: \";\n for( i = mul_2.begin(); i!= mul_2.end(); i++){\n cout<<(*i).first<<\" \"<<(*i).second << \"\\n\";\n }\n}" }, { "code": null, "e": 3618, "s": 3553, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3717, "s": 3618, "text": "Elements in multimap1 are:\n6 60\n7 70\n8 80\n9 90\nElements in multimap2 are: 1 10\n2 20\n3 30\n4 40\n5 50" } ]
Python | Convert Character Matrix to single String - GeeksforGeeks
30 Dec, 2020 Sometimes, while working with Python strings, we can have an option in which we need to perform the task of converting character matrix to a single string. This can have applications in domains in which we need to work with data. Lets discuss certain ways in which we can perform this task. Method #1 : Using join() + list comprehensionThe combination of above functionalities can be used to perform this task. In this, we just iterate for all lists and join them using join(). # Python3 code to demonstrate working of # Convert Character Matrix to single String# Using join() + list comprehension # initializing listtest_list = [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']] # printing original listprint("The original list is : " + str(test_list)) # Convert Character Matrix to single String# Using join() + list comprehensionres = ''.join(ele for sub in test_list for ele in sub) # printing result print("The String after join : " + res) The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']] The String after join : gfgisbest Method #2 : Using join() + chain()The combination of above functionalities can be used to perform this task. In this, we perform the task performed by list comprehension by chain(). # Python3 code to demonstrate working of # Convert Character Matrix to single String# Using join() + chain()from itertools import chain # initializing listtest_list = [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']] # printing original listprint("The original list is : " + str(test_list)) # Convert Character Matrix to single String# Using join() + chain()res = "".join(chain(*test_list)) # printing result print("The String after join : " + res) The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']] The String after join : gfgisbest Python list-programs Python matrix-program Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary 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 | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not How to print without newline in Python?
[ { "code": null, "e": 24480, "s": 24452, "text": "\n30 Dec, 2020" }, { "code": null, "e": 24771, "s": 24480, "text": "Sometimes, while working with Python strings, we can have an option in which we need to perform the task of converting character matrix to a single string. This can have applications in domains in which we need to work with data. Lets discuss certain ways in which we can perform this task." }, { "code": null, "e": 24958, "s": 24771, "text": "Method #1 : Using join() + list comprehensionThe combination of above functionalities can be used to perform this task. In this, we just iterate for all lists and join them using join()." }, { "code": "# Python3 code to demonstrate working of # Convert Character Matrix to single String# Using join() + list comprehension # initializing listtest_list = [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']] # printing original listprint(\"The original list is : \" + str(test_list)) # Convert Character Matrix to single String# Using join() + list comprehensionres = ''.join(ele for sub in test_list for ele in sub) # printing result print(\"The String after join : \" + res) ", "e": 25431, "s": 24958, "text": null }, { "code": null, "e": 25541, "s": 25431, "text": "The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]\nThe String after join : gfgisbest\n" }, { "code": null, "e": 25725, "s": 25543, "text": "Method #2 : Using join() + chain()The combination of above functionalities can be used to perform this task. In this, we perform the task performed by list comprehension by chain()." }, { "code": "# Python3 code to demonstrate working of # Convert Character Matrix to single String# Using join() + chain()from itertools import chain # initializing listtest_list = [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']] # printing original listprint(\"The original list is : \" + str(test_list)) # Convert Character Matrix to single String# Using join() + chain()res = \"\".join(chain(*test_list)) # printing result print(\"The String after join : \" + res) ", "e": 26181, "s": 25725, "text": null }, { "code": null, "e": 26291, "s": 26181, "text": "The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]\nThe String after join : gfgisbest\n" }, { "code": null, "e": 26312, "s": 26291, "text": "Python list-programs" }, { "code": null, "e": 26334, "s": 26312, "text": "Python matrix-program" }, { "code": null, "e": 26341, "s": 26334, "text": "Python" }, { "code": null, "e": 26357, "s": 26341, "text": "Python Programs" }, { "code": null, "e": 26455, "s": 26357, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26473, "s": 26455, "text": "Python Dictionary" }, { "code": null, "e": 26495, "s": 26473, "text": "Enumerate() in Python" }, { "code": null, "e": 26527, "s": 26495, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26557, "s": 26527, "text": "Iterate over a list in Python" }, { "code": null, "e": 26599, "s": 26557, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26621, "s": 26599, "text": "Defaultdict in Python" }, { "code": null, "e": 26660, "s": 26621, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26698, "s": 26660, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 26755, "s": 26698, "text": "Python program to check whether a number is Prime or not" } ]
Extracting Feature Importances from Scikit-Learn Pipelines | by Rebecca Vickery | Towards Data Science
Scikit-learn pipelines provide a really simple way to chain together the preprocessing steps with the model fitting stages in machine learning development. With pipelines, you can embed these steps so that in one line of code the model will perform all necessary preprocessing steps at the same time as either fitting the model or calling predict. There are many benefits to this besides reducing the lines of code in your project. Using the standard pipeline layouts means that it is very easy for a colleague, or your future self, to quickly understand your workflow. This in turns means that your work is more reproducible. Additionally, with pipelines, you can enforce the order in which transformations happen. There is however one drawback in that, although scikit-learn models have the benefit of being highly explainable. Once you embed the model into a pipeline it becomes difficult to extract elements such as feature importances that make these models so interpretable. I have been spending some time recently looking at this problem. In the following article, I am going to present a simple method I have found to extract feature importances from a pipeline using the python library ELI5. In this article, I am going to be using a dataset from drivendata.org, a machine learning competition website. The dataset can be downloaded here. First I’ll import all the libraries I am using. import pandas as pdimport numpy as npfrom sklearn import preprocessingfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import Pipelinefrom sklearn.impute import SimpleImputerfrom sklearn.preprocessing import StandardScalerfrom sklearn.compose import ColumnTransformerfrom sklearn.metrics import f1_scorefrom sklearn.preprocessing import OneHotEncoderfrom sklearn.base import BaseEstimator, TransformerMixinfrom sklearn.metrics import classification_reportfrom sklearn.linear_model import LogisticRegressionimport eli5 I am then using the pandas library to read in the datasets that I have previously downloaded. The features and target labels are in separate CSV files so I am also using the pandas merge function to combine them into one data frame. train_values = pd.read_csv('train_values.csv')train_labels = pd.read_csv('train_labels.csv')train_data = train_values.merge(train_labels, left_on='building_id', right_on='building_id') If we inspect the data types we can see that there are a mixture of numerical and categorical data. We will, therefore, need to apply some preprocessing before training a model. A pipeline will, therefore, be useful for this dataset. train_data.dtypes Before constructing the pipeline I am dropping the ‘building_id’ column as it will not be needed for training, splitting the data into test and train sets, and defining some variables to identify the categorical and numerical columns. train_data = train_data.drop('building_id', axis=1)numeric_features = train_data.select_dtypes(include=['int64', 'float64']).drop(['damage_grade'], axis=1).columnscategorical_features = train_data.select_dtypes(include=['object']).columnsX = train_data.drop('damage_grade', axis=1)y = train_data['damage_grade']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) I am going to construct a simple pipeline which will chain together the preprocessing and model fitting steps. Additionally, I am going to add an imputer for any missing values. Although the dataset I am using here does not have any missing data it is sensible to add in this step. This is because in the real world if we were deploying this as a machine learning application there is a chance that new data we are trying to predict on may have missing values. It is, therefore, good practice to add this as a safety net. The code below constructs a pipeline that imputes any missing values, applies a standard scaler to the numerical features, converts any categorical features into numerical and then fits a classifier. numeric_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])categorical_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='constant', fill_value='missing')), ('one_hot', OneHotEncoder())])preprocessor = ColumnTransformer( transformers=[ ('num', numeric_transformer, numeric_features), ('cat', categorical_transformer, categorical_features) ])pipe = Pipeline(steps=[('preprocessor', preprocessor), ('classifier', LogisticRegression(class_weight='balanced', random_state=0))]) model = pipe.fit(X_train, y_train) We can inspect the quality of the pipeline by running the below code. target_names = y_test.unique().astype(str)y_pred = model.predict(X_test)print(classification_report(y_test, y_pred, target_names=target_names)) We can see that there is likely to be room for improvement in terms of the performance of the model. One area we would want to explore, besides model selection and hyperparameter optimisation would be feature engineering. However, in order to determine which new features to engineer we first need to have an understanding of which features are most predictive. It is not easy to extract feature importances from this pipeline. However, there is a python library that makes this very simple called ELI5. This library, named after the slang term “explain like I’m 5”, is a package that provides a simple way to explain and interpret machine learning models. It is compatible with most popular machine learning frameworks including scikit-learn, xgboost and keras. The library can be installed via pip or conda. pip install eli5conda install -c conda-forge eli5 Let's use ELI5 to extract feature importances from the pipeline. ELI5 needs to know all feature names in order to construct feature importances. By applying one-hot encoding to the categorical variables in the pipeline we are introducing a number of new features. We therefore first need to extract these feature names and append them to the known list of numerical features. The code below uses the ‘named_steps’ function built into scikit-learn pipelines to do this. onehot_columns = list(pipe.named_steps['preprocessor'].named_transformers_['cat'].named_steps['one_hot'].get_feature_names(input_features=categorical_features))numeric_features_list = list(numeric_features)numeric_features_list.extend(onehot_columns) To extract the feature importances we then simply need to run this line of code. eli5.explain_weights(pipe.named_steps['classifier'], top=50, feature_names=numeric_features_list) Which gives a nicely formatted output. The ELI5 library also provides the ability to explain individual predictions but this is not yet supported for pipelines. In this article, I demonstrated a simple method to extract features importances from a scikit-learn pipeline which provides a good starting point to debug and improve a machine learning model. Thanks for reading!
[ { "code": null, "e": 520, "s": 172, "text": "Scikit-learn pipelines provide a really simple way to chain together the preprocessing steps with the model fitting stages in machine learning development. With pipelines, you can embed these steps so that in one line of code the model will perform all necessary preprocessing steps at the same time as either fitting the model or calling predict." }, { "code": null, "e": 888, "s": 520, "text": "There are many benefits to this besides reducing the lines of code in your project. Using the standard pipeline layouts means that it is very easy for a colleague, or your future self, to quickly understand your workflow. This in turns means that your work is more reproducible. Additionally, with pipelines, you can enforce the order in which transformations happen." }, { "code": null, "e": 1153, "s": 888, "text": "There is however one drawback in that, although scikit-learn models have the benefit of being highly explainable. Once you embed the model into a pipeline it becomes difficult to extract elements such as feature importances that make these models so interpretable." }, { "code": null, "e": 1373, "s": 1153, "text": "I have been spending some time recently looking at this problem. In the following article, I am going to present a simple method I have found to extract feature importances from a pipeline using the python library ELI5." }, { "code": null, "e": 1520, "s": 1373, "text": "In this article, I am going to be using a dataset from drivendata.org, a machine learning competition website. The dataset can be downloaded here." }, { "code": null, "e": 1568, "s": 1520, "text": "First I’ll import all the libraries I am using." }, { "code": null, "e": 2111, "s": 1568, "text": "import pandas as pdimport numpy as npfrom sklearn import preprocessingfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import Pipelinefrom sklearn.impute import SimpleImputerfrom sklearn.preprocessing import StandardScalerfrom sklearn.compose import ColumnTransformerfrom sklearn.metrics import f1_scorefrom sklearn.preprocessing import OneHotEncoderfrom sklearn.base import BaseEstimator, TransformerMixinfrom sklearn.metrics import classification_reportfrom sklearn.linear_model import LogisticRegressionimport eli5" }, { "code": null, "e": 2344, "s": 2111, "text": "I am then using the pandas library to read in the datasets that I have previously downloaded. The features and target labels are in separate CSV files so I am also using the pandas merge function to combine them into one data frame." }, { "code": null, "e": 2529, "s": 2344, "text": "train_values = pd.read_csv('train_values.csv')train_labels = pd.read_csv('train_labels.csv')train_data = train_values.merge(train_labels, left_on='building_id', right_on='building_id')" }, { "code": null, "e": 2763, "s": 2529, "text": "If we inspect the data types we can see that there are a mixture of numerical and categorical data. We will, therefore, need to apply some preprocessing before training a model. A pipeline will, therefore, be useful for this dataset." }, { "code": null, "e": 2781, "s": 2763, "text": "train_data.dtypes" }, { "code": null, "e": 3016, "s": 2781, "text": "Before constructing the pipeline I am dropping the ‘building_id’ column as it will not be needed for training, splitting the data into test and train sets, and defining some variables to identify the categorical and numerical columns." }, { "code": null, "e": 3400, "s": 3016, "text": "train_data = train_data.drop('building_id', axis=1)numeric_features = train_data.select_dtypes(include=['int64', 'float64']).drop(['damage_grade'], axis=1).columnscategorical_features = train_data.select_dtypes(include=['object']).columnsX = train_data.drop('damage_grade', axis=1)y = train_data['damage_grade']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)" }, { "code": null, "e": 3922, "s": 3400, "text": "I am going to construct a simple pipeline which will chain together the preprocessing and model fitting steps. Additionally, I am going to add an imputer for any missing values. Although the dataset I am using here does not have any missing data it is sensible to add in this step. This is because in the real world if we were deploying this as a machine learning application there is a chance that new data we are trying to predict on may have missing values. It is, therefore, good practice to add this as a safety net." }, { "code": null, "e": 4122, "s": 3922, "text": "The code below constructs a pipeline that imputes any missing values, applies a standard scaler to the numerical features, converts any categorical features into numerical and then fits a classifier." }, { "code": null, "e": 4761, "s": 4122, "text": "numeric_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])categorical_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='constant', fill_value='missing')), ('one_hot', OneHotEncoder())])preprocessor = ColumnTransformer( transformers=[ ('num', numeric_transformer, numeric_features), ('cat', categorical_transformer, categorical_features) ])pipe = Pipeline(steps=[('preprocessor', preprocessor), ('classifier', LogisticRegression(class_weight='balanced', random_state=0))]) model = pipe.fit(X_train, y_train)" }, { "code": null, "e": 4831, "s": 4761, "text": "We can inspect the quality of the pipeline by running the below code." }, { "code": null, "e": 4975, "s": 4831, "text": "target_names = y_test.unique().astype(str)y_pred = model.predict(X_test)print(classification_report(y_test, y_pred, target_names=target_names))" }, { "code": null, "e": 5337, "s": 4975, "text": "We can see that there is likely to be room for improvement in terms of the performance of the model. One area we would want to explore, besides model selection and hyperparameter optimisation would be feature engineering. However, in order to determine which new features to engineer we first need to have an understanding of which features are most predictive." }, { "code": null, "e": 5738, "s": 5337, "text": "It is not easy to extract feature importances from this pipeline. However, there is a python library that makes this very simple called ELI5. This library, named after the slang term “explain like I’m 5”, is a package that provides a simple way to explain and interpret machine learning models. It is compatible with most popular machine learning frameworks including scikit-learn, xgboost and keras." }, { "code": null, "e": 5785, "s": 5738, "text": "The library can be installed via pip or conda." }, { "code": null, "e": 5835, "s": 5785, "text": "pip install eli5conda install -c conda-forge eli5" }, { "code": null, "e": 5900, "s": 5835, "text": "Let's use ELI5 to extract feature importances from the pipeline." }, { "code": null, "e": 6304, "s": 5900, "text": "ELI5 needs to know all feature names in order to construct feature importances. By applying one-hot encoding to the categorical variables in the pipeline we are introducing a number of new features. We therefore first need to extract these feature names and append them to the known list of numerical features. The code below uses the ‘named_steps’ function built into scikit-learn pipelines to do this." }, { "code": null, "e": 6555, "s": 6304, "text": "onehot_columns = list(pipe.named_steps['preprocessor'].named_transformers_['cat'].named_steps['one_hot'].get_feature_names(input_features=categorical_features))numeric_features_list = list(numeric_features)numeric_features_list.extend(onehot_columns)" }, { "code": null, "e": 6636, "s": 6555, "text": "To extract the feature importances we then simply need to run this line of code." }, { "code": null, "e": 6734, "s": 6636, "text": "eli5.explain_weights(pipe.named_steps['classifier'], top=50, feature_names=numeric_features_list)" }, { "code": null, "e": 6773, "s": 6734, "text": "Which gives a nicely formatted output." }, { "code": null, "e": 7088, "s": 6773, "text": "The ELI5 library also provides the ability to explain individual predictions but this is not yet supported for pipelines. In this article, I demonstrated a simple method to extract features importances from a scikit-learn pipeline which provides a good starting point to debug and improve a machine learning model." } ]
LSTM for time series prediction. Training a Long Short Term Memory... | by Roman Orac | Towards Data Science
The idea of using a Neural Network (NN) to predict the stock price movement on the market is as old as Neural nets. Intuitively, it seems difficult to predict the future price movement looking only at its past. There are many tutorials on how to predict the price trend or its power, which simplifies the problem. I’ve decided to try to predict Volume Weighted Average Price with LSTM because it seems challenging and fun. In this blog post, I am going to train a Long Short Term Memory Neural Network (LSTM) with PyTorch on Bitcoin trading data and use it to predict the price of unseen trading data. I had quite some difficulties with finding intermediate tutorials with a repeatable example of training an LSTM for time series prediction, so I’ve put together a Jupyter notebook to help you to get started. - 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 import the libraries that we are going to use for data manipulation, visualization, training the model, etc. We are going to train the LSTM using the PyTorch library. %matplotlib inlineimport globimport matplotlibimport numpy as npimport pandas as pdimport sklearnimport torch We are going to analyze XBTUSD trading data from BitMex. The daily files are publicly available to download. I didn’t bother to write the code to download the data automatically, I’ve simply clicked a couple of times to download the files. Let’s list all the files, read them to a pandas DataFrame and filter the trading data by XBTUSD symbol. It is important to sort the DataFrame by timestamp as there are multiple daily files so that they don’t get mixed up. files = sorted(glob.glob('data/*.csv.gz'))df = pd.concat(map(pd.read_csv, files))df = df[df.symbol == 'XBTUSD']df.timestamp = pd.to_datetime(df.timestamp.str.replace('D', 'T')) # covert to timestamp typedf = df.sort_values('timestamp')df.set_index('timestamp', inplace=True) # set index to timestampdf.head() Each row represents a trade: timestamp in microsecond accuracy, symbol of the contract traded, side of the trade, buy or sell, size represents the number of contracts (the number of USD traded), price of the contract, tickDirection describes an increase/decrease in the price since the previous transaction, trdMatchID is the unique trade ID, grossValue is the number of satoshis exchanged, homeNotional is the amount of XBT in the trade, foreignNotional is the amount of USD in the trade. We are going to use 3 columns: timestamp, price and foreignNotional. Let’s calculate Volume Weighted Average Price (VWAP) in 1 minute time intervals. The data representation where we group trades by the predefined time interval is called time bars. Is this the best way to represent the trade data for modeling? According to Lopez de Prado, trades on the market are not uniformly distributed over time. There are periods with high activity, eg. right before future contracts expire, and grouping of data in predefined time intervals would oversample the data in some time bars and undersample it at others. Financial Machine Learning Part 0: Bars is a nice summary of the 2nd Chapter of Lopez de Prado’s book Advances in Financial Machine Learning Book. Time bars may not be the best data representation, but we are going to use them regardless. df_vwap = df.groupby(pd.Grouper(freq="1Min")).apply( lambda row: pd.np.sum(row.price * row.foreignNotional) / pd.np.sum(row.foreignNotional)) The plot shows time bars with VWAP from the 1st of August till the 17th of September 2019. We are going to use the first part of the data for the training set, part in-between for validation set and the last part of the data for the test set (vertical lines are delimiters). We can observe volatility in the VWAP, where the price reaches its highs in the first part of August and lows at the end of August. The high and low are captured in the training set, which is important, as the model most probably wouldn’t work well on unseen VWAP intervals. To help the LSTM model to converge faster it is important to scale the data. It is possible that large values in the inputs slow down the learning. We are going to use StandardScaler from sklearn library to scale the data. The scaler is fit on the training set and it is used to transform the unseen trade data on validation and test set. If we would fit the scalar on all data, the model would overfit and it would achieve good results on this data, but performance would suffer on the real-world data. from sklearn.preprocessing import StandardScalerscaler = StandardScaler()train_arr = scaler.fit_transform(df_train)val_arr = scaler.transform(df_val)test_arr = scaler.transform(df_test) After scaling we need to transform the data into a format that is appropriate for modeling with LSTM. We transform the long sequence of data into many shorter sequences (100-time bars per sequence) that are shifted by a single time bar. from torch.autograd import Variabledef transform_data(arr, seq_len): x, y = [], [] for i in range(len(arr) - seq_len): x_i = arr[i : i + seq_len] y_i = arr[i + 1 : i + seq_len + 1] x.append(x_i) y.append(y_i) x_arr = np.array(x).reshape(-1, seq_len) y_arr = np.array(y).reshape(-1, seq_len) x_var = Variable(torch.from_numpy(x_arr).float()) y_var = Variable(torch.from_numpy(y_arr).float()) return x_var, y_varseq_len = 100x_train, y_train = transform_data(train_arr, seq_len)x_val, y_val = transform_data(val_arr, seq_len)x_test, y_test = transform_data(test_arr, seq_len) The plot below shows the first and the second sequence in the training set. The length of both sequences is 100-time bars. We can observe that the target of both sequences is almost the same as the feature, the differences are in the first and in the last time bar. How does the LSTM use the sequence in the training phase? Let’s focus on the 1st sequence. The model takes the feature of the time bar at index 0 and it tries to predict the target of the time bar at index 1. Then it takes the feature of the time bar at index 1 and it tries to predict the target of the time bar at index 2, etc. The feature of 2nd sequence is shifted by a 1-time bar from the feature of 1st sequence, the feature of the 3rd sequence is shifted by a 1-time bar from 2nd sequence, etc. With this procedure, we get many shorter sequences that are shifted by a single time bar. Note that in classification or regression tasks, we usually have a set of features and a target that we are trying to predict. In this example with LSTM, the feature and the target are from the same sequence, the only difference is that the target is shifted by a 1-time bar. The Long Short Term Memory neural network is a type of a Recurrent Neural Network (RNN). RNNs use previous time events to inform the later ones. For example, to classify what kind of event is happening in a movie, the model needs to use information about previous events. RNNs work well if the problem requires only recent information to perform the present task. If the problem requires long term dependencies, RNN would struggle to model it. The LSTM was designed to learn long term dependencies. It remembers the information for long periods. LSTM was introduced by S Hochreiter, J Schmidhuber in 1997. To learn more about LSTMs read a great colah blog post which offers a good explanation. The code below is an implementation of a stateful LSTM for time series prediction. It has an LSTMCell unit and a linear layer to model a sequence of a time series. The model can generate the future values of a time series and it can be trained using teacher forcing (a concept that I am going to describe later). import torch.nn as nnimport torch.optim as optimclass Model(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(Model, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size self.lstm = nn.LSTMCell(self.input_size, self.hidden_size) self.linear = nn.Linear(self.hidden_size, self.output_size) def forward(self, input, future=0, y=None): outputs = [] # reset the state of LSTM # the state is kept till the end of the sequence h_t = torch.zeros(input.size(0), self.hidden_size, dtype=torch.float32) c_t = torch.zeros(input.size(0), self.hidden_size, dtype=torch.float32) for i, input_t in enumerate(input.chunk(input.size(1), dim=1)): h_t, c_t = self.lstm(input_t, (h_t, c_t)) output = self.linear(h_t) outputs += [output] for i in range(future): if y is not None and random.random() > 0.5: output = y[:, [i]] # teacher forcing h_t, c_t = self.lstm(output, (h_t, c_t)) output = self.linear(h_t) outputs += [output] outputs = torch.stack(outputs, 1).squeeze(2) return outputs We train LSTM with 21 hidden units. A lower number of units is used so that it is less likely that LSTM would perfectly memorize the sequence. We use the Mean Square Error loss function and Adam optimizer. The learning rate is set to 0.001 and it decays every 5 epochs. We train the model with 100 sequences per batch for 15 epochs. From the plot below, we can observe that training and validation loss converge after the sixth epoch. Let’s evaluate the model on the test set. The future parameter is set to 5, which means that the model outputs the VWAP where it believes it will be in the next 5 time bars (5 minutes in our example). This should make the price change visible a few time bars before it occurs. On the plot below, we can observe that predicted values closely match the actual values of VWAP, which seems great at first sight. But the future parameter was set to 5, which means that the orange line should react before a spike occurs instead of covering it. When we zoom into the spikes (one on the start and the other on the end of the time series). We can observe that predicted values mimic the actual values. When the actual value changes direction, predicted value follows, which doesn’t help us much. The same happens when we increase the future parameter (like it doesn’t affect the predicted line). Let’s generate 1000 time bars for the first test sequence with the model and compare predicted, generated and actual VWAP. We can observe that while the model outputs predicted values, they are close to actual values. But when it starts to generate values, the output almost resembles the sine wave. After a certain period values converge to 9600. This behavior could occur because the model was trained only with true inputs and never with generated inputs. When the model gets fed the generated output on the input, it does a poor job of generating the next values. Teacher forcing is a concept that deals with this issue. The Teacher forcing is a method for training Recurrent Neural Networks that use the output from a previous time step as an input. When the RNN is trained, it can generate a sequence by using the previous output as current input. The same process can be used during training, but the model can become unstable or it does not converge. Teacher forcing is an approach to address those issues during training. It is commonly used in language models. We are going to use an extension of Teacher forcing, called Scheduled sampling. The model will use its generated output as an input with a certain probability during training. At first, the probability of a model seeing its generated output is small and then it gradually increases during training. Note that in this example, we use a random probability, which doesn’t increase during the training process. Let’s train a model with the same parameters as before but with the teacher forcing enabled. After 7 epochs, the training and validation loss converge. We can observe a similar predicted sequence as before. When we zoom into the spikes, similar behavior of the model can be observed, where predicted values mimic the actual values. It seems like teacher forcing didn’t solve the problem. Let’s generate 1000 time bars for the first test sequence with the model trained with teacher forcing. The generated sequence from the model trained with teacher forcing needs longer to converge. Another observation about the generated sequence is that when it is increasing, it will continue to increase to some point, then start to decrease and the pattern repeats until the sequence converges. The pattern looks like a sine wave with a decreasing amplitude. The result of this experiment is that the predictions of the model mimic the actual values of the sequence. The first and second models do not detect price changes before they occur. Adding another feature (like volume) might help the model to detect the price changes before they occur, but then the model would need to generate two features to use the output of those as input in the next step, which would complicate the model. Using a more complex model (multiple LSTMCells, increase the number of hidden units) might not help as the model has the capacity to predict the VWAP time series as seen in the plots above. More advanced methods of teacher forcing might help so that the model would improve sequence generation skills. Time Sequence Prediction Understanding LSTM Networks What is Teacher Forcing for Recurrent Neural Networks? Scheduled Sampling for Sequence Prediction with Recurrent Neural Networks Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.
[ { "code": null, "e": 595, "s": 172, "text": "The idea of using a Neural Network (NN) to predict the stock price movement on the market is as old as Neural nets. Intuitively, it seems difficult to predict the future price movement looking only at its past. There are many tutorials on how to predict the price trend or its power, which simplifies the problem. I’ve decided to try to predict Volume Weighted Average Price with LSTM because it seems challenging and fun." }, { "code": null, "e": 982, "s": 595, "text": "In this blog post, I am going to train a Long Short Term Memory Neural Network (LSTM) with PyTorch on Bitcoin trading data and use it to predict the price of unseen trading data. I had quite some difficulties with finding intermediate tutorials with a repeatable example of training an LSTM for time series prediction, so I’ve put together a Jupyter notebook to help you to get started." }, { "code": null, "e": 1160, "s": 982, "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": 1331, "s": 1160, "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": 1504, "s": 1331, "text": "Let’s import the libraries that we are going to use for data manipulation, visualization, training the model, etc. We are going to train the LSTM using the PyTorch library." }, { "code": null, "e": 1614, "s": 1504, "text": "%matplotlib inlineimport globimport matplotlibimport numpy as npimport pandas as pdimport sklearnimport torch" }, { "code": null, "e": 1854, "s": 1614, "text": "We are going to analyze XBTUSD trading data from BitMex. The daily files are publicly available to download. I didn’t bother to write the code to download the data automatically, I’ve simply clicked a couple of times to download the files." }, { "code": null, "e": 2076, "s": 1854, "text": "Let’s list all the files, read them to a pandas DataFrame and filter the trading data by XBTUSD symbol. It is important to sort the DataFrame by timestamp as there are multiple daily files so that they don’t get mixed up." }, { "code": null, "e": 2385, "s": 2076, "text": "files = sorted(glob.glob('data/*.csv.gz'))df = pd.concat(map(pd.read_csv, files))df = df[df.symbol == 'XBTUSD']df.timestamp = pd.to_datetime(df.timestamp.str.replace('D', 'T')) # covert to timestamp typedf = df.sort_values('timestamp')df.set_index('timestamp', inplace=True) # set index to timestampdf.head()" }, { "code": null, "e": 2414, "s": 2385, "text": "Each row represents a trade:" }, { "code": null, "e": 2449, "s": 2414, "text": "timestamp in microsecond accuracy," }, { "code": null, "e": 2480, "s": 2449, "text": "symbol of the contract traded," }, { "code": null, "e": 2512, "s": 2480, "text": "side of the trade, buy or sell," }, { "code": null, "e": 2580, "s": 2512, "text": "size represents the number of contracts (the number of USD traded)," }, { "code": null, "e": 2603, "s": 2580, "text": "price of the contract," }, { "code": null, "e": 2693, "s": 2603, "text": "tickDirection describes an increase/decrease in the price since the previous transaction," }, { "code": null, "e": 2728, "s": 2693, "text": "trdMatchID is the unique trade ID," }, { "code": null, "e": 2776, "s": 2728, "text": "grossValue is the number of satoshis exchanged," }, { "code": null, "e": 2824, "s": 2776, "text": "homeNotional is the amount of XBT in the trade," }, { "code": null, "e": 2875, "s": 2824, "text": "foreignNotional is the amount of USD in the trade." }, { "code": null, "e": 2944, "s": 2875, "text": "We are going to use 3 columns: timestamp, price and foreignNotional." }, { "code": null, "e": 3721, "s": 2944, "text": "Let’s calculate Volume Weighted Average Price (VWAP) in 1 minute time intervals. The data representation where we group trades by the predefined time interval is called time bars. Is this the best way to represent the trade data for modeling? According to Lopez de Prado, trades on the market are not uniformly distributed over time. There are periods with high activity, eg. right before future contracts expire, and grouping of data in predefined time intervals would oversample the data in some time bars and undersample it at others. Financial Machine Learning Part 0: Bars is a nice summary of the 2nd Chapter of Lopez de Prado’s book Advances in Financial Machine Learning Book. Time bars may not be the best data representation, but we are going to use them regardless." }, { "code": null, "e": 3866, "s": 3721, "text": "df_vwap = df.groupby(pd.Grouper(freq=\"1Min\")).apply( lambda row: pd.np.sum(row.price * row.foreignNotional) / pd.np.sum(row.foreignNotional))" }, { "code": null, "e": 4416, "s": 3866, "text": "The plot shows time bars with VWAP from the 1st of August till the 17th of September 2019. We are going to use the first part of the data for the training set, part in-between for validation set and the last part of the data for the test set (vertical lines are delimiters). We can observe volatility in the VWAP, where the price reaches its highs in the first part of August and lows at the end of August. The high and low are captured in the training set, which is important, as the model most probably wouldn’t work well on unseen VWAP intervals." }, { "code": null, "e": 4920, "s": 4416, "text": "To help the LSTM model to converge faster it is important to scale the data. It is possible that large values in the inputs slow down the learning. We are going to use StandardScaler from sklearn library to scale the data. The scaler is fit on the training set and it is used to transform the unseen trade data on validation and test set. If we would fit the scalar on all data, the model would overfit and it would achieve good results on this data, but performance would suffer on the real-world data." }, { "code": null, "e": 5106, "s": 4920, "text": "from sklearn.preprocessing import StandardScalerscaler = StandardScaler()train_arr = scaler.fit_transform(df_train)val_arr = scaler.transform(df_val)test_arr = scaler.transform(df_test)" }, { "code": null, "e": 5343, "s": 5106, "text": "After scaling we need to transform the data into a format that is appropriate for modeling with LSTM. We transform the long sequence of data into many shorter sequences (100-time bars per sequence) that are shifted by a single time bar." }, { "code": null, "e": 5966, "s": 5343, "text": "from torch.autograd import Variabledef transform_data(arr, seq_len): x, y = [], [] for i in range(len(arr) - seq_len): x_i = arr[i : i + seq_len] y_i = arr[i + 1 : i + seq_len + 1] x.append(x_i) y.append(y_i) x_arr = np.array(x).reshape(-1, seq_len) y_arr = np.array(y).reshape(-1, seq_len) x_var = Variable(torch.from_numpy(x_arr).float()) y_var = Variable(torch.from_numpy(y_arr).float()) return x_var, y_varseq_len = 100x_train, y_train = transform_data(train_arr, seq_len)x_val, y_val = transform_data(val_arr, seq_len)x_test, y_test = transform_data(test_arr, seq_len)" }, { "code": null, "e": 6232, "s": 5966, "text": "The plot below shows the first and the second sequence in the training set. The length of both sequences is 100-time bars. We can observe that the target of both sequences is almost the same as the feature, the differences are in the first and in the last time bar." }, { "code": null, "e": 6290, "s": 6232, "text": "How does the LSTM use the sequence in the training phase?" }, { "code": null, "e": 6824, "s": 6290, "text": "Let’s focus on the 1st sequence. The model takes the feature of the time bar at index 0 and it tries to predict the target of the time bar at index 1. Then it takes the feature of the time bar at index 1 and it tries to predict the target of the time bar at index 2, etc. The feature of 2nd sequence is shifted by a 1-time bar from the feature of 1st sequence, the feature of the 3rd sequence is shifted by a 1-time bar from 2nd sequence, etc. With this procedure, we get many shorter sequences that are shifted by a single time bar." }, { "code": null, "e": 7100, "s": 6824, "text": "Note that in classification or regression tasks, we usually have a set of features and a target that we are trying to predict. In this example with LSTM, the feature and the target are from the same sequence, the only difference is that the target is shifted by a 1-time bar." }, { "code": null, "e": 7794, "s": 7100, "text": "The Long Short Term Memory neural network is a type of a Recurrent Neural Network (RNN). RNNs use previous time events to inform the later ones. For example, to classify what kind of event is happening in a movie, the model needs to use information about previous events. RNNs work well if the problem requires only recent information to perform the present task. If the problem requires long term dependencies, RNN would struggle to model it. The LSTM was designed to learn long term dependencies. It remembers the information for long periods. LSTM was introduced by S Hochreiter, J Schmidhuber in 1997. To learn more about LSTMs read a great colah blog post which offers a good explanation." }, { "code": null, "e": 8107, "s": 7794, "text": "The code below is an implementation of a stateful LSTM for time series prediction. It has an LSTMCell unit and a linear layer to model a sequence of a time series. The model can generate the future values of a time series and it can be trained using teacher forcing (a concept that I am going to describe later)." }, { "code": null, "e": 9361, "s": 8107, "text": "import torch.nn as nnimport torch.optim as optimclass Model(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(Model, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size self.lstm = nn.LSTMCell(self.input_size, self.hidden_size) self.linear = nn.Linear(self.hidden_size, self.output_size) def forward(self, input, future=0, y=None): outputs = [] # reset the state of LSTM # the state is kept till the end of the sequence h_t = torch.zeros(input.size(0), self.hidden_size, dtype=torch.float32) c_t = torch.zeros(input.size(0), self.hidden_size, dtype=torch.float32) for i, input_t in enumerate(input.chunk(input.size(1), dim=1)): h_t, c_t = self.lstm(input_t, (h_t, c_t)) output = self.linear(h_t) outputs += [output] for i in range(future): if y is not None and random.random() > 0.5: output = y[:, [i]] # teacher forcing h_t, c_t = self.lstm(output, (h_t, c_t)) output = self.linear(h_t) outputs += [output] outputs = torch.stack(outputs, 1).squeeze(2) return outputs" }, { "code": null, "e": 9796, "s": 9361, "text": "We train LSTM with 21 hidden units. A lower number of units is used so that it is less likely that LSTM would perfectly memorize the sequence. We use the Mean Square Error loss function and Adam optimizer. The learning rate is set to 0.001 and it decays every 5 epochs. We train the model with 100 sequences per batch for 15 epochs. From the plot below, we can observe that training and validation loss converge after the sixth epoch." }, { "code": null, "e": 10073, "s": 9796, "text": "Let’s evaluate the model on the test set. The future parameter is set to 5, which means that the model outputs the VWAP where it believes it will be in the next 5 time bars (5 minutes in our example). This should make the price change visible a few time bars before it occurs." }, { "code": null, "e": 10335, "s": 10073, "text": "On the plot below, we can observe that predicted values closely match the actual values of VWAP, which seems great at first sight. But the future parameter was set to 5, which means that the orange line should react before a spike occurs instead of covering it." }, { "code": null, "e": 10684, "s": 10335, "text": "When we zoom into the spikes (one on the start and the other on the end of the time series). We can observe that predicted values mimic the actual values. When the actual value changes direction, predicted value follows, which doesn’t help us much. The same happens when we increase the future parameter (like it doesn’t affect the predicted line)." }, { "code": null, "e": 11032, "s": 10684, "text": "Let’s generate 1000 time bars for the first test sequence with the model and compare predicted, generated and actual VWAP. We can observe that while the model outputs predicted values, they are close to actual values. But when it starts to generate values, the output almost resembles the sine wave. After a certain period values converge to 9600." }, { "code": null, "e": 11309, "s": 11032, "text": "This behavior could occur because the model was trained only with true inputs and never with generated inputs. When the model gets fed the generated output on the input, it does a poor job of generating the next values. Teacher forcing is a concept that deals with this issue." }, { "code": null, "e": 11755, "s": 11309, "text": "The Teacher forcing is a method for training Recurrent Neural Networks that use the output from a previous time step as an input. When the RNN is trained, it can generate a sequence by using the previous output as current input. The same process can be used during training, but the model can become unstable or it does not converge. Teacher forcing is an approach to address those issues during training. It is commonly used in language models." }, { "code": null, "e": 12162, "s": 11755, "text": "We are going to use an extension of Teacher forcing, called Scheduled sampling. The model will use its generated output as an input with a certain probability during training. At first, the probability of a model seeing its generated output is small and then it gradually increases during training. Note that in this example, we use a random probability, which doesn’t increase during the training process." }, { "code": null, "e": 12314, "s": 12162, "text": "Let’s train a model with the same parameters as before but with the teacher forcing enabled. After 7 epochs, the training and validation loss converge." }, { "code": null, "e": 12550, "s": 12314, "text": "We can observe a similar predicted sequence as before. When we zoom into the spikes, similar behavior of the model can be observed, where predicted values mimic the actual values. It seems like teacher forcing didn’t solve the problem." }, { "code": null, "e": 12653, "s": 12550, "text": "Let’s generate 1000 time bars for the first test sequence with the model trained with teacher forcing." }, { "code": null, "e": 13011, "s": 12653, "text": "The generated sequence from the model trained with teacher forcing needs longer to converge. Another observation about the generated sequence is that when it is increasing, it will continue to increase to some point, then start to decrease and the pattern repeats until the sequence converges. The pattern looks like a sine wave with a decreasing amplitude." }, { "code": null, "e": 13744, "s": 13011, "text": "The result of this experiment is that the predictions of the model mimic the actual values of the sequence. The first and second models do not detect price changes before they occur. Adding another feature (like volume) might help the model to detect the price changes before they occur, but then the model would need to generate two features to use the output of those as input in the next step, which would complicate the model. Using a more complex model (multiple LSTMCells, increase the number of hidden units) might not help as the model has the capacity to predict the VWAP time series as seen in the plots above. More advanced methods of teacher forcing might help so that the model would improve sequence generation skills." }, { "code": null, "e": 13769, "s": 13744, "text": "Time Sequence Prediction" }, { "code": null, "e": 13797, "s": 13769, "text": "Understanding LSTM Networks" }, { "code": null, "e": 13852, "s": 13797, "text": "What is Teacher Forcing for Recurrent Neural Networks?" }, { "code": null, "e": 13926, "s": 13852, "text": "Scheduled Sampling for Sequence Prediction with Recurrent Neural Networks" } ]
yppasswd - Unix, Linux Command
Today, this versions are deprecated and should not be used any longer. Using the command line switches, you can choose whether to update your password -p, your login shell -l, or your GECOS field -f, or a combination of them. yppasswd implies the -p option, if no other option is given. If you use the -f or -l option, you also need to add the -p flag. ypchfn implies the -f option, and ypchsh -l. When invoked without the user argument, the account information for the invoking user will be updated, otherwise that of user will be updated. This option is only available to the super-user. If the yppasswdd daemon on the server supports it, you can give the root password of the server instead of the users [old] password. All tools will first prompt the user for the current NIS password needed for authentication with the yppasswdd(8) daemon. Subsequently, the program prompts for the updated information: Login shell [/bin/sh]: _ Name [Joe Doe]: Location [2nd floor, bldg 34]: Office Phone [12345]: Home Phone []: chfn (1) chfn (1) chsh (1) chsh (1) finger (1) finger (1) passwd (1) passwd (1) ypcat (1) ypcat (1) yppasswdd (8) yppasswdd (8) ypserv (8) ypserv (8) ypwhich (1) ypwhich (1) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10650, "s": 10577, "text": "\nToday, this versions are deprecated and should not be used any\nlonger.\n" }, { "code": null, "e": 10979, "s": 10650, "text": "\nUsing the command line switches, you can choose whether to update your\npassword\n-p, your login shell\n-l, or your GECOS field\n-f, or a combination of them.\nyppasswd implies the\n-p option, if no other option is given. If you use the\n-f or\n-l option, you also need to add the\n-p flag.\nypchfn implies the\n-f option, and\nypchsh -l. " }, { "code": null, "e": 11306, "s": 10979, "text": "\nWhen invoked without the\nuser argument, the account information for the invoking user will be updated,\notherwise that of\nuser will be updated. This option is only available to the super-user. If the\nyppasswdd daemon on the server supports it, you can give the root password\nof the server instead of the users [old] password.\n" }, { "code": null, "e": 11493, "s": 11306, "text": "\nAll tools will first prompt the user for the current NIS password needed\nfor authentication with the\nyppasswdd(8)\ndaemon. Subsequently, the\nprogram prompts for the updated information:\n" }, { "code": null, "e": 11519, "s": 11493, "text": "Login shell [/bin/sh]: _\n" }, { "code": null, "e": 11604, "s": 11519, "text": "Name [Joe Doe]:\nLocation [2nd floor, bldg 34]:\nOffice Phone [12345]:\nHome Phone []:\n" }, { "code": null, "e": 11613, "s": 11604, "text": "chfn (1)" }, { "code": null, "e": 11622, "s": 11613, "text": "chfn (1)" }, { "code": null, "e": 11631, "s": 11622, "text": "chsh (1)" }, { "code": null, "e": 11640, "s": 11631, "text": "chsh (1)" }, { "code": null, "e": 11651, "s": 11640, "text": "finger (1)" }, { "code": null, "e": 11662, "s": 11651, "text": "finger (1)" }, { "code": null, "e": 11673, "s": 11662, "text": "passwd (1)" }, { "code": null, "e": 11684, "s": 11673, "text": "passwd (1)" }, { "code": null, "e": 11694, "s": 11684, "text": "ypcat (1)" }, { "code": null, "e": 11704, "s": 11694, "text": "ypcat (1)" }, { "code": null, "e": 11718, "s": 11704, "text": "yppasswdd (8)" }, { "code": null, "e": 11732, "s": 11718, "text": "yppasswdd (8)" }, { "code": null, "e": 11743, "s": 11732, "text": "ypserv (8)" }, { "code": null, "e": 11754, "s": 11743, "text": "ypserv (8)" }, { "code": null, "e": 11766, "s": 11754, "text": "ypwhich (1)" }, { "code": null, "e": 11778, "s": 11766, "text": "ypwhich (1)" }, { "code": null, "e": 11795, "s": 11778, "text": "\nAdvertisements\n" }, { "code": null, "e": 11830, "s": 11795, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 11858, "s": 11830, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11892, "s": 11858, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11909, "s": 11892, "text": " Frahaan Hussain" }, { "code": null, "e": 11942, "s": 11909, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 11953, "s": 11942, "text": " Pradeep D" }, { "code": null, "e": 11988, "s": 11953, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12004, "s": 11988, "text": " Musab Zayadneh" }, { "code": null, "e": 12037, "s": 12004, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 12049, "s": 12037, "text": " GUHARAJANM" }, { "code": null, "e": 12081, "s": 12049, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 12089, "s": 12081, "text": " Uplatz" }, { "code": null, "e": 12096, "s": 12089, "text": " Print" }, { "code": null, "e": 12107, "s": 12096, "text": " Add Notes" } ]
Difference between NodeJS and ReactJS
ReactJS and NodeJS both are a widely used subsets of JavaScript nowadays with high performance. But both are different in someways. In the below article, we will discuss the difference between the two and which is better to use to build a web application and why ? It is a completely open-source and cross-platform runtime environment used for executing JavaScript code outside of a browser. The event driven model of NodeJs lets the user to create a fast and scalable network applications. First thing to remember about NodeJS is that its neither a framework and nor a programming language. NodeJS is a lightweight, efficient JavaScript runtime environment on the server side which is powered by the Chrome V8 JavaScript engine and uses a nonblocking I/O model to run applications. Following are the features of NodeJS which differs from other backend creating frameworks or languages − NodeJS is easy to understand and get started with. NodeJS is easy to understand and get started with. It can be used for prototyping and agile development. It can be used for prototyping and agile development. Provides high performance and scalable services Provides high performance and scalable services Large ecosystem and contributors for open source library Large ecosystem and contributors for open source library Asynchronous and single threaded Asynchronous and single threaded In this example, we will see how to include the HTTP module to build the server in NodeJS. Create a JS File as → filename.js (You can create a file with other name as well. Just keep in mind that when running the code using node, change the name there too, else it will throw a FileNotFound error.) var http = require('http'); // Creating a server object using http http.createServer(function (req, res) { // Write a response to the client res.write('Welcome to the Tutorials Point !!!'); // End the response res.end(); // The server object listens on port 8080 }).listen(8081); For compiling the JS file go to the terminal and run the following command − node filename.js It is also an open-source JavaScript library (instead of a conventional web framework) that can be used with a web browser. It is used for building single page user interfaces or web browser apps. React's virtual DOM algorithm is a time-consuming and imprecise writing ode. It can be used as a base in all the signle-page, complex and interactive web projects. We can use react in nesting components to allow complex application to be built out of simple building blocks. Following are some of the features of ReactJS that makes it different from other programming languages − It has reusable codes that makes it simple to learn and use. It has reusable codes that makes it simple to learn and use. The ReactJS library has JSX (JavaScript XML) The ReactJS library has JSX (JavaScript XML) It supports one-way binding which provides complete control over the application It supports one-way binding which provides complete control over the application It has virtual DOM which represent better UI and keeps in memory, also syncs itself with the real DOM. It has virtual DOM which represent better UI and keeps in memory, also syncs itself with the real DOM. Since, it has virtual component – it gives smoother and faster performance. Since, it has virtual component – it gives smoother and faster performance. Here is a React app project example. Create a ReactJS application project and edit the App.js file in the source folder − import React, { Component } from 'react'; class App extends Component { render() { return ( <div className="App"> <> <h1>Hello from Tutorials Point !!</h1> </> </div> ); } } export default App;
[ { "code": null, "e": 1327, "s": 1062, "text": "ReactJS and NodeJS both are a widely used subsets of JavaScript nowadays with high performance. But both are different in someways. In the below article, we will discuss the difference between the two and which is better to use to build a web application and why ?" }, { "code": null, "e": 1454, "s": 1327, "text": "It is a completely open-source and cross-platform runtime environment used for executing JavaScript code outside of a browser." }, { "code": null, "e": 1845, "s": 1454, "text": "The event driven model of NodeJs lets the user to create a fast and scalable network applications. First thing to remember about NodeJS is that its neither a framework and nor a programming language. NodeJS is a lightweight, efficient JavaScript runtime environment on the server side which is powered by the Chrome V8 JavaScript engine and uses a nonblocking I/O model to run applications." }, { "code": null, "e": 1950, "s": 1845, "text": "Following are the features of NodeJS which differs from other backend creating frameworks or languages −" }, { "code": null, "e": 2001, "s": 1950, "text": "NodeJS is easy to understand and get started with." }, { "code": null, "e": 2052, "s": 2001, "text": "NodeJS is easy to understand and get started with." }, { "code": null, "e": 2106, "s": 2052, "text": "It can be used for prototyping and agile development." }, { "code": null, "e": 2160, "s": 2106, "text": "It can be used for prototyping and agile development." }, { "code": null, "e": 2208, "s": 2160, "text": "Provides high performance and scalable services" }, { "code": null, "e": 2256, "s": 2208, "text": "Provides high performance and scalable services" }, { "code": null, "e": 2313, "s": 2256, "text": "Large ecosystem and contributors for open source library" }, { "code": null, "e": 2370, "s": 2313, "text": "Large ecosystem and contributors for open source library" }, { "code": null, "e": 2403, "s": 2370, "text": "Asynchronous and single threaded" }, { "code": null, "e": 2436, "s": 2403, "text": "Asynchronous and single threaded" }, { "code": null, "e": 2527, "s": 2436, "text": "In this example, we will see how to include the HTTP module to build the server in NodeJS." }, { "code": null, "e": 2561, "s": 2527, "text": "Create a JS File as → filename.js" }, { "code": null, "e": 2735, "s": 2561, "text": "(You can create a file with other name as well. Just keep in mind that when running the code using node, change the name there too, else it will throw a FileNotFound error.)" }, { "code": null, "e": 3034, "s": 2735, "text": "var http = require('http');\n\n// Creating a server object using http\nhttp.createServer(function (req, res) {\n\n // Write a response to the client\n res.write('Welcome to the Tutorials Point !!!');\n\n // End the response\n res.end();\n\n // The server object listens on port 8080\n}).listen(8081);" }, { "code": null, "e": 3111, "s": 3034, "text": "For compiling the JS file go to the terminal and run the following command −" }, { "code": null, "e": 3128, "s": 3111, "text": "node filename.js" }, { "code": null, "e": 3600, "s": 3128, "text": "It is also an open-source JavaScript library (instead of a conventional web framework) that can be used with a web browser. It is used for building single page user interfaces or web browser apps. React's virtual DOM algorithm is a time-consuming and imprecise writing ode. It can be used as a base in all the signle-page, complex and interactive web projects. We can use react in nesting components to allow complex application to be built out of simple building blocks." }, { "code": null, "e": 3705, "s": 3600, "text": "Following are some of the features of ReactJS that makes it different from other programming languages −" }, { "code": null, "e": 3766, "s": 3705, "text": "It has reusable codes that makes it simple to learn and use." }, { "code": null, "e": 3827, "s": 3766, "text": "It has reusable codes that makes it simple to learn and use." }, { "code": null, "e": 3872, "s": 3827, "text": "The ReactJS library has JSX (JavaScript XML)" }, { "code": null, "e": 3917, "s": 3872, "text": "The ReactJS library has JSX (JavaScript XML)" }, { "code": null, "e": 3998, "s": 3917, "text": "It supports one-way binding which provides complete control over the application" }, { "code": null, "e": 4079, "s": 3998, "text": "It supports one-way binding which provides complete control over the application" }, { "code": null, "e": 4182, "s": 4079, "text": "It has virtual DOM which represent better UI and keeps in memory, also syncs itself with the real DOM." }, { "code": null, "e": 4285, "s": 4182, "text": "It has virtual DOM which represent better UI and keeps in memory, also syncs itself with the real DOM." }, { "code": null, "e": 4361, "s": 4285, "text": "Since, it has virtual component – it gives smoother and faster performance." }, { "code": null, "e": 4437, "s": 4361, "text": "Since, it has virtual component – it gives smoother and faster performance." }, { "code": null, "e": 4559, "s": 4437, "text": "Here is a React app project example. Create a ReactJS application project and edit the App.js file in the source folder −" }, { "code": null, "e": 4821, "s": 4559, "text": "import React, { Component } from 'react';\n\nclass App extends Component {\n\n render() {\n return (\n <div className=\"App\">\n <>\n <h1>Hello from Tutorials Point !!</h1>\n </>\n </div>\n );\n }\n}\nexport default App;" } ]
Deduplication of customer data using fuzzy-scoring | by Shreepada Shivananda | Towards Data Science
Abstract: For any organization, data management is always a challenge, through its life cycle of planning, collection, processing, storage, management, analysis, visualization and finally interpretation. For successful management and protection of data requires a lot of planning and collaboration between teams to move data from one stage to the next. Few prominent steps of data processing are wrangling, compression, deduplication and encryption. When it comes to most of the customer centric organizations it will be a biggest challenge to get a unique list of customers not because of storage cost reduction, but rather due to the fact that understanding their customer is a biggest asset for them. Hence irrespective of size of the corporation, they spend a lot of time and effort on getting this data right, either through in-line deduplication or post-processing deduplication [1]. This paper talks through post processing deduplication using a fuzzy scoring method with python and relevant packages. Challenges: The data is collected in various methods with/without standard data collection forms and collected in various places but consolidated at one place. These lists are often compiled by third-parties without standard formatting and can often contain duplicate or otherwise ‘dirty’ data. Data goes back into a long history, contains inaccuracies and incompleteness. When attempting to compare lists compiled by different collection methods are quickly challenged with several data concerns: 1. Unclear addresses: Based on when, where and what was the primary purpose of the data collection, it can have non-structured and non-specific addresses, postal codes and even names. 2. Transliteration problems: Inconsistencies when translating addresses with non-Roman characters into English text introduces variation in addresses and names. 3. Contact information complication: Customers will generally have multiple email addresses and phone numbers, this problem explodes when the business type is B2B where a business will have multiple phone numbers and email addresses. 4. Most repeated values: Commonly repeated values are because of incorrect data collection especially occurs under name, email, and phone number, etc. and each scenario must be handled appropriately. Data normalization: An essential step before starting deduplication is making sure the data is structured, aligned and has a consistent format. Hence it’s sensible to follow below steps: 1. Lowercase: One of the efficient and simplest steps is to convert everything to lowercase to make name and address comparable. 2. Abbreviation: Maintain consistency by words with abbreviation with be building a repository obtained in the internet or custom made of the data which is getting processed. Example: Street is also represented as St. , St, Str. , Str, etc. 3. Missing values: Assess missing value per record and if there is a significant missing value then remove it from proceeding further and the quality of such records will be too low to help deduplication scoring. 4. Incorrect country names: A Python package ‘iso3166’ contains a list of all countries and helps identifying the country names which are incorrect in country name. 5. Incorrect postal codes: ‘pgeocode’ is a python library which contains legitimate postal codes for all countries and used for validating postal codes in the address. There are several paid APIs as well for the same purpose which helps in getting the postal code right. Validation of Phone numbers and email address: Apart from identification of repeated phone numbers, an additional verification that can be done is assessing the quality and standardizing format with prefix of ‘+’ or ‘0’ or (country code). Below script helps standardizing millions of phone numbers in few seconds. Further precise validation can be done through the paid API which helps validation during in-line of post processing deduplication. def check_phone(phone, cc): try: if int(phone) <1: return np.nan if phone== np.nan: return np.nan except:pass phone= str(phone) cc= str(cc)#print(phone, cc) if len(phone)>4 : if phone != np.nan or cc != np.nan: cc_len = len(cc) if(phone[:1] == '+'): if phone[1:1+cc_len] == cc: return phone else: return phone else: cc_len = len(cc) if phone[:1] == '0': if phone[1:1+cc_len]== cc: return phone.replace('0','+',1) else: return phone.replace('0','+'+cc,1) else: if phone[0:cc_len]== cc: return '+'+phone else:return '+'+cc+phone else: return np.nan# Function caller%time account[['calling_code','contact_Phone']].apply(lambda x : check_phone(x.contact_Phone, x.calling_code),axis = 1) Definition of Duplication: Defining what duplication in the data is an important aspect for the process. Depending on the problem that is getting solved, the definition of duplication will change. For a most common customer data generally this will be Name, Postal address, Phone number(s) and email address. These will form a set of fields to look for scoring and help identifying duplication. Few fields such as Phone Number or email will give a clear indication of duplication, on the other hand duplication in Name or address can actually represent people that are actually detached individuals. Hence such cases should go through a semi-automated/automated verification process. Finally the Scoring: Scoring starts with a self-join of the table joining with itself based on city/postal code and then using fuzzy logic to score the rest of the columns such as name, email, and phone numbers. The scoring with the right cutoff gives the probable list of duplicates in the data and rest to be discarded. As always there is no magical number for the definite cutoff and it take a few iterations to arrive at a number between 0–100 to define what the right cutoff for the data is. In addition, it’s better to have distinct cutoffs for each column like in the code below. # self-joining data based on the parameter# Preparation of data for fuzzydef joiner(cntry , file , mcol): df_string_all = account[(account.ShippingCountryCode == cntry)] df_string_all = df_string_all[address_match_columns] global dup dup = pd.DataFrame() parts = round(df_string_all.shape[0]/1000) start_time = time.time() if cntry == 'ie': mcol = mcol.replace('PostalCode','City')print(cntry.upper(), mcol) total_uni = len(df_string_all[mcol].unique()) unique_col_value = df_string_all[mcol].unique() rem = ['xxxxx','Nan','', 'NAN', 'nan', np.nan] unique_col_value = [uni for uni in unique_col_value if uni not in rem] for i in range(1,parts+1): my_list = unique_col_value[int(round(np.divide((1),parts)*total_uni*(i-1))):\ int(round(np.divide((1),parts)*total_uni*i))] df_string = df_string_all[(df_string_all[mcol].isin(my_list))] df_string = df_string.merge(df_string, on= mcol , how = 'left', suffixes= ('1', '2')) col_list = df_string.columns.sort_values().drop( ['Id1', 'Id2']).drop(mcol)df_string = df_string[(df_string.Id1 < df_string.Id2)] even = col_list[::2] odd = col_list[1::2] df_string = df_string[(df_string[['Name1' , 'Name2']].apply( lambda x:fuzz.token_sort_ratio(x['Name1'], x['Name2']), axis = 1) > name_match_cutoff)] if df_string.shape[0] >0: dup = dup.append(identifier(df_string, even, odd, mcol)) del df_string del df_string_all end_time = time.time() print('Time taken for : ' ,cntry.upper() , mcol , round((end_time - start_time)/60,2) , ' minutes') print('Duplicates for : ',cntry.upper() , mcol, dup.shape) return dup Below block identifies duplicates in the data based on the cutoff levels defined by the users: def identifier(df_string, col_even, col_odd, case): for i in col_even: for j in col_odd: if(i[:-1] == j[:-1]): new_col = i[:-1]+'_score' df_string[new_col] = df_string.apply(lambda x: fuzz.token_sort_ratio(x[i], x[j]) , axis = 1) df_string[new_col] = df_string.apply(lambda x: 0 if (pd.isnull(x[i]) | pd.isnull(x[j])) else x[new_col], axis=1)col_score = [k for k in df_string.columns if 'score' in k] street_score = [k for k in col_score if 'Street' in k] city_score = [k for k in col_score if 'City' in k] +[k for k in col_score if 'Post' in k] if case == 'Name': duplicate_con = df_string[((df_string[street_score]> street_match_cutoff).sum(axis= 1) > 0) &\ ((df_string[city_score]> city_match_cutoff).sum(axis=1)>0)] elif case == 'BillingStreet': duplicate_con = df_string[((df_string[city_score]> city_match_cutoff).sum(axis=1)>0) & \ (df_string['Name_score']> name_match_cutoff)] else: duplicate_con = df_string[(df_string['Name_score'] > name_match_cutoff) & \ ((df_string[street_score] > street_match_cutoff).sum(axis=1) > 0) & \ ((df_string[city_score]> city_match_cutoff).sum(axis=1)>0)] if duplicate_con.shape[0] >0: duplicate_con['2Final_Score'] = round((duplicate_con[col_score].mean(axis = 1))) duplicate_con['1Match_Case'] = case duplicate_con[case+'1'] = duplicate_con[case] duplicate_con[case+'2'] = duplicate_con[case] duplicate_con[case+'_score'] = 100 duplicate_con= duplicate_con.drop(columns= case) return duplicate_con Function caller country = list(account.ShippingCountryCode.unique())country = [e for e in country if e not in (['nan', np.nan])]duplicate = pd.DataFrame()duplicate_indi = pd.DataFrame()start = time.time()for cntr in country: file_name = 'account_'+ cntr for cols in ['MailingPostalCode', 'PostalCode']: duplicate = duplicate.append(joiner(cntr , file_name, cols)) end = time.time()print('Total Time taken:' , round((end - start)/60,2) , ' minutes')
[ { "code": null, "e": 182, "s": 172, "text": "Abstract:" }, { "code": null, "e": 876, "s": 182, "text": "For any organization, data management is always a challenge, through its life cycle of planning, collection, processing, storage, management, analysis, visualization and finally interpretation. For successful management and protection of data requires a lot of planning and collaboration between teams to move data from one stage to the next. Few prominent steps of data processing are wrangling, compression, deduplication and encryption. When it comes to most of the customer centric organizations it will be a biggest challenge to get a unique list of customers not because of storage cost reduction, but rather due to the fact that understanding their customer is a biggest asset for them." }, { "code": null, "e": 1181, "s": 876, "text": "Hence irrespective of size of the corporation, they spend a lot of time and effort on getting this data right, either through in-line deduplication or post-processing deduplication [1]. This paper talks through post processing deduplication using a fuzzy scoring method with python and relevant packages." }, { "code": null, "e": 1193, "s": 1181, "text": "Challenges:" }, { "code": null, "e": 1554, "s": 1193, "text": "The data is collected in various methods with/without standard data collection forms and collected in various places but consolidated at one place. These lists are often compiled by third-parties without standard formatting and can often contain duplicate or otherwise ‘dirty’ data. Data goes back into a long history, contains inaccuracies and incompleteness." }, { "code": null, "e": 1679, "s": 1554, "text": "When attempting to compare lists compiled by different collection methods are quickly challenged with several data concerns:" }, { "code": null, "e": 1863, "s": 1679, "text": "1. Unclear addresses: Based on when, where and what was the primary purpose of the data collection, it can have non-structured and non-specific addresses, postal codes and even names." }, { "code": null, "e": 2024, "s": 1863, "text": "2. Transliteration problems: Inconsistencies when translating addresses with non-Roman characters into English text introduces variation in addresses and names." }, { "code": null, "e": 2258, "s": 2024, "text": "3. Contact information complication: Customers will generally have multiple email addresses and phone numbers, this problem explodes when the business type is B2B where a business will have multiple phone numbers and email addresses." }, { "code": null, "e": 2458, "s": 2258, "text": "4. Most repeated values: Commonly repeated values are because of incorrect data collection especially occurs under name, email, and phone number, etc. and each scenario must be handled appropriately." }, { "code": null, "e": 2478, "s": 2458, "text": "Data normalization:" }, { "code": null, "e": 2645, "s": 2478, "text": "An essential step before starting deduplication is making sure the data is structured, aligned and has a consistent format. Hence it’s sensible to follow below steps:" }, { "code": null, "e": 2774, "s": 2645, "text": "1. Lowercase: One of the efficient and simplest steps is to convert everything to lowercase to make name and address comparable." }, { "code": null, "e": 3015, "s": 2774, "text": "2. Abbreviation: Maintain consistency by words with abbreviation with be building a repository obtained in the internet or custom made of the data which is getting processed. Example: Street is also represented as St. , St, Str. , Str, etc." }, { "code": null, "e": 3228, "s": 3015, "text": "3. Missing values: Assess missing value per record and if there is a significant missing value then remove it from proceeding further and the quality of such records will be too low to help deduplication scoring." }, { "code": null, "e": 3393, "s": 3228, "text": "4. Incorrect country names: A Python package ‘iso3166’ contains a list of all countries and helps identifying the country names which are incorrect in country name." }, { "code": null, "e": 3664, "s": 3393, "text": "5. Incorrect postal codes: ‘pgeocode’ is a python library which contains legitimate postal codes for all countries and used for validating postal codes in the address. There are several paid APIs as well for the same purpose which helps in getting the postal code right." }, { "code": null, "e": 3711, "s": 3664, "text": "Validation of Phone numbers and email address:" }, { "code": null, "e": 4110, "s": 3711, "text": "Apart from identification of repeated phone numbers, an additional verification that can be done is assessing the quality and standardizing format with prefix of ‘+’ or ‘0’ or (country code). Below script helps standardizing millions of phone numbers in few seconds. Further precise validation can be done through the paid API which helps validation during in-line of post processing deduplication." }, { "code": null, "e": 5111, "s": 4110, "text": "def check_phone(phone, cc): try: if int(phone) <1: return np.nan if phone== np.nan: return np.nan except:pass phone= str(phone) cc= str(cc)#print(phone, cc) if len(phone)>4 : if phone != np.nan or cc != np.nan: cc_len = len(cc) if(phone[:1] == '+'): if phone[1:1+cc_len] == cc: return phone else: return phone else: cc_len = len(cc) if phone[:1] == '0': if phone[1:1+cc_len]== cc: return phone.replace('0','+',1) else: return phone.replace('0','+'+cc,1) else: if phone[0:cc_len]== cc: return '+'+phone else:return '+'+cc+phone else: return np.nan# Function caller%time account[['calling_code','contact_Phone']].apply(lambda x : check_phone(x.contact_Phone, x.calling_code),axis = 1)" }, { "code": null, "e": 5138, "s": 5111, "text": "Definition of Duplication:" }, { "code": null, "e": 5795, "s": 5138, "text": "Defining what duplication in the data is an important aspect for the process. Depending on the problem that is getting solved, the definition of duplication will change. For a most common customer data generally this will be Name, Postal address, Phone number(s) and email address. These will form a set of fields to look for scoring and help identifying duplication. Few fields such as Phone Number or email will give a clear indication of duplication, on the other hand duplication in Name or address can actually represent people that are actually detached individuals. Hence such cases should go through a semi-automated/automated verification process." }, { "code": null, "e": 5816, "s": 5795, "text": "Finally the Scoring:" }, { "code": null, "e": 6382, "s": 5816, "text": "Scoring starts with a self-join of the table joining with itself based on city/postal code and then using fuzzy logic to score the rest of the columns such as name, email, and phone numbers. The scoring with the right cutoff gives the probable list of duplicates in the data and rest to be discarded. As always there is no magical number for the definite cutoff and it take a few iterations to arrive at a number between 0–100 to define what the right cutoff for the data is. In addition, it’s better to have distinct cutoffs for each column like in the code below." }, { "code": null, "e": 8075, "s": 6382, "text": "# self-joining data based on the parameter# Preparation of data for fuzzydef joiner(cntry , file , mcol): df_string_all = account[(account.ShippingCountryCode == cntry)] df_string_all = df_string_all[address_match_columns] global dup dup = pd.DataFrame() parts = round(df_string_all.shape[0]/1000) start_time = time.time() if cntry == 'ie': mcol = mcol.replace('PostalCode','City')print(cntry.upper(), mcol) total_uni = len(df_string_all[mcol].unique()) unique_col_value = df_string_all[mcol].unique() rem = ['xxxxx','Nan','', 'NAN', 'nan', np.nan] unique_col_value = [uni for uni in unique_col_value if uni not in rem] for i in range(1,parts+1): my_list = unique_col_value[int(round(np.divide((1),parts)*total_uni*(i-1))):\\ int(round(np.divide((1),parts)*total_uni*i))] df_string = df_string_all[(df_string_all[mcol].isin(my_list))] df_string = df_string.merge(df_string, on= mcol , how = 'left', suffixes= ('1', '2')) col_list = df_string.columns.sort_values().drop( ['Id1', 'Id2']).drop(mcol)df_string = df_string[(df_string.Id1 < df_string.Id2)] even = col_list[::2] odd = col_list[1::2] df_string = df_string[(df_string[['Name1' , 'Name2']].apply( lambda x:fuzz.token_sort_ratio(x['Name1'], x['Name2']), axis = 1) > name_match_cutoff)] if df_string.shape[0] >0: dup = dup.append(identifier(df_string, even, odd, mcol)) del df_string del df_string_all end_time = time.time() print('Time taken for : ' ,cntry.upper() , mcol , round((end_time - start_time)/60,2) , ' minutes') print('Duplicates for : ',cntry.upper() , mcol, dup.shape) return dup" }, { "code": null, "e": 8170, "s": 8075, "text": "Below block identifies duplicates in the data based on the cutoff levels defined by the users:" }, { "code": null, "e": 9957, "s": 8170, "text": "def identifier(df_string, col_even, col_odd, case): for i in col_even: for j in col_odd: if(i[:-1] == j[:-1]): new_col = i[:-1]+'_score' df_string[new_col] = df_string.apply(lambda x: fuzz.token_sort_ratio(x[i], x[j]) , axis = 1) df_string[new_col] = df_string.apply(lambda x: 0 if (pd.isnull(x[i]) | pd.isnull(x[j])) else x[new_col], axis=1)col_score = [k for k in df_string.columns if 'score' in k] street_score = [k for k in col_score if 'Street' in k] city_score = [k for k in col_score if 'City' in k] +[k for k in col_score if 'Post' in k] if case == 'Name': duplicate_con = df_string[((df_string[street_score]> street_match_cutoff).sum(axis= 1) > 0) &\\ ((df_string[city_score]> city_match_cutoff).sum(axis=1)>0)] elif case == 'BillingStreet': duplicate_con = df_string[((df_string[city_score]> city_match_cutoff).sum(axis=1)>0) & \\ (df_string['Name_score']> name_match_cutoff)] else: duplicate_con = df_string[(df_string['Name_score'] > name_match_cutoff) & \\ ((df_string[street_score] > street_match_cutoff).sum(axis=1) > 0) & \\ ((df_string[city_score]> city_match_cutoff).sum(axis=1)>0)] if duplicate_con.shape[0] >0: duplicate_con['2Final_Score'] = round((duplicate_con[col_score].mean(axis = 1))) duplicate_con['1Match_Case'] = case duplicate_con[case+'1'] = duplicate_con[case] duplicate_con[case+'2'] = duplicate_con[case] duplicate_con[case+'_score'] = 100 duplicate_con= duplicate_con.drop(columns= case) return duplicate_con" }, { "code": null, "e": 9973, "s": 9957, "text": "Function caller" } ]
How to Delete or Remove a File in Golang? - GeeksforGeeks
02 Apr, 2020 In the Go language, you are allowed to remove the existing file with the help of the Remove() method. This method removes the specified file from the director or it also removes empty directories. If the given path is incorrect, then it will throw an error of type *PathError. It is defined under the os package so, you have to import os package in your program for accessing Remove() function. Syntax: func Remove(file_name string) error Example 1: // Golang program to illustrate how to // remove files from the default directorypackage main import ( "log" "os") func main() { // Removing file from the directory // Using Remove() function e := os.Remove("GeeksforGeeks.txt") if e != nil { log.Fatal(e) }} Output: Before: After: Example 2: // Golang program to illustrate how to remove// files from the specified directorypackage main import ( "log" "os") func main() { // Removing file // Using Remove() function e := os.Remove("/Users/anki/Documents/new_folder/GeeksforGeeks.txt") if e != nil { log.Fatal(e) } } Output: Before: After: Golang-File-Handling Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples Time Formatting in Golang fmt.Sprintf() Function in Golang With Examples How to Split a String in Golang? Arrays in Go Slices in Golang Golang Maps Interfaces in Golang Inheritance in GoLang Different Ways to Find the Type of Variable in Golang
[ { "code": null, "e": 24331, "s": 24303, "text": "\n02 Apr, 2020" }, { "code": null, "e": 24726, "s": 24331, "text": "In the Go language, you are allowed to remove the existing file with the help of the Remove() method. This method removes the specified file from the director or it also removes empty directories. If the given path is incorrect, then it will throw an error of type *PathError. It is defined under the os package so, you have to import os package in your program for accessing Remove() function." }, { "code": null, "e": 24734, "s": 24726, "text": "Syntax:" }, { "code": null, "e": 24770, "s": 24734, "text": "func Remove(file_name string) error" }, { "code": null, "e": 24781, "s": 24770, "text": "Example 1:" }, { "code": "// Golang program to illustrate how to // remove files from the default directorypackage main import ( \"log\" \"os\") func main() { // Removing file from the directory // Using Remove() function e := os.Remove(\"GeeksforGeeks.txt\") if e != nil { log.Fatal(e) }}", "e": 25074, "s": 24781, "text": null }, { "code": null, "e": 25082, "s": 25074, "text": "Output:" }, { "code": null, "e": 25090, "s": 25082, "text": "Before:" }, { "code": null, "e": 25097, "s": 25090, "text": "After:" }, { "code": null, "e": 25108, "s": 25097, "text": "Example 2:" }, { "code": "// Golang program to illustrate how to remove// files from the specified directorypackage main import ( \"log\" \"os\") func main() { // Removing file // Using Remove() function e := os.Remove(\"/Users/anki/Documents/new_folder/GeeksforGeeks.txt\") if e != nil { log.Fatal(e) } }", "e": 25420, "s": 25108, "text": null }, { "code": null, "e": 25428, "s": 25420, "text": "Output:" }, { "code": null, "e": 25436, "s": 25428, "text": "Before:" }, { "code": null, "e": 25443, "s": 25436, "text": "After:" }, { "code": null, "e": 25464, "s": 25443, "text": "Golang-File-Handling" }, { "code": null, "e": 25476, "s": 25464, "text": "Go Language" }, { "code": null, "e": 25574, "s": 25476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25625, "s": 25574, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 25651, "s": 25625, "text": "Time Formatting in Golang" }, { "code": null, "e": 25698, "s": 25651, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 25731, "s": 25698, "text": "How to Split a String in Golang?" }, { "code": null, "e": 25744, "s": 25731, "text": "Arrays in Go" }, { "code": null, "e": 25761, "s": 25744, "text": "Slices in Golang" }, { "code": null, "e": 25773, "s": 25761, "text": "Golang Maps" }, { "code": null, "e": 25794, "s": 25773, "text": "Interfaces in Golang" }, { "code": null, "e": 25816, "s": 25794, "text": "Inheritance in GoLang" } ]
Exception Handling in Dart - GeeksforGeeks
20 Jul, 2020 An exception is an error that takes place inside the program. When an exception occurs inside a program the normal flow of the program is disrupted and it terminates abnormally, displaying the error and exception stack as output. So, an exception must be taken care to prevent the application from termination. Built-in Exceptions in Dart: Every built-in exception in Drat comes under a pre-defined class named Exception. To prevent the program from exception we make use of try/on/catch blocks in Dart. try { // program that might throw an exception } on Exception1 { // code for handling exception 1 } catch Exception2 { // code for handling exception 2 } Example 1: Using a try-on block in the dart. Dart void main() { String geek = "GeeksForGeeks"; try{ var geek2 = geek ~/ 0; print(geek2); } on FormatException{ print("Error!! \nCan't act as input is not an integer."); }} Output: Error!! Can't act as input is not an integer. Example 2: Using a try-catch block in the dart. Dart void main() { String geek = "GeeksForGeeks"; try{ var geek2 = geek ~/ 0; print(geek2); } catch(e){ print(e); }} Output: Class 'String' has no instance method '~/'. NoSuchMethodError: method not found: '~/' Receiver: "GeeksForGeeks" Arguments: [0] Final block: The final block in dart is used to include specific code that must be executed irrespective of error in the code. Although it is optional to include finally block if you include it then it should be after try and catch block are over. finally { ... } Example: Dart void main() { int geek = 10; try{ var geek2 = geek ~/ 0; print(geek2); } catch(e){ print(e); } finally { print("Code is at end, Geek"); }} Output: Unsupported operation: Result of truncating division is Infinity: 10 ~/ 0 Code is at end, Geek Unlike other languages, in Dart to one can create a custom exception. To do, so we make use of throw new keyword in the dart. Example: Creating custom exceptions in the dart. Dart // extending Class Age// with Exception classclass Age implements Exception { String error() => 'Geek, your age is less than 18 :(';} void main() { int geek_age1 = 20; int geek_age2 = 10; try{ // Checking Age and // calling if the // exception occur check(geek_age1); check(geek_age2); } catch(e){ // Printing error print(e.error()); }} // Checking Agevoid check(int age){ if(age < 18){ throw new Age(); } else { print("You are eligible to visit GeeksForGeeks :)"); }} Output: You are eligible to visit GeeksForGeeks :) Geek, your age is less than 18 :( Dart-Exception-Handling Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - BoxShadow Widget Dart Tutorial Flutter - Checkbox Widget How to Append or Concatenate Strings in Dart? Operators in Dart Flutter - BorderRadius Widget Flutter - Flexible Widget
[ { "code": null, "e": 23958, "s": 23930, "text": "\n20 Jul, 2020" }, { "code": null, "e": 24270, "s": 23958, "text": "An exception is an error that takes place inside the program. When an exception occurs inside a program the normal flow of the program is disrupted and it terminates abnormally, displaying the error and exception stack as output. So, an exception must be taken care to prevent the application from termination. " }, { "code": null, "e": 24301, "s": 24270, "text": "Built-in Exceptions in Dart: " }, { "code": null, "e": 24465, "s": 24301, "text": "Every built-in exception in Drat comes under a pre-defined class named Exception. To prevent the program from exception we make use of try/on/catch blocks in Dart." }, { "code": null, "e": 24637, "s": 24465, "text": "try { \n // program that might throw an exception \n} \non Exception1 { \n // code for handling exception 1\n} \ncatch Exception2 { \n // code for handling exception 2\n}\n" }, { "code": null, "e": 24683, "s": 24637, "text": "Example 1: Using a try-on block in the dart. " }, { "code": null, "e": 24688, "s": 24683, "text": "Dart" }, { "code": "void main() { String geek = \"GeeksForGeeks\"; try{ var geek2 = geek ~/ 0; print(geek2); } on FormatException{ print(\"Error!! \\nCan't act as input is not an integer.\"); }}", "e": 24872, "s": 24688, "text": null }, { "code": null, "e": 24884, "s": 24874, "text": "Output: " }, { "code": null, "e": 24932, "s": 24884, "text": "Error!! \nCan't act as input is not an integer.\n" }, { "code": null, "e": 24981, "s": 24932, "text": "Example 2: Using a try-catch block in the dart. " }, { "code": null, "e": 24986, "s": 24981, "text": "Dart" }, { "code": "void main() { String geek = \"GeeksForGeeks\"; try{ var geek2 = geek ~/ 0; print(geek2); } catch(e){ print(e); }}", "e": 25112, "s": 24986, "text": null }, { "code": null, "e": 25124, "s": 25114, "text": "Output: " }, { "code": null, "e": 25253, "s": 25124, "text": "Class 'String' has no instance method '~/'.\n\nNoSuchMethodError: method not found: '~/'\nReceiver: \"GeeksForGeeks\"\nArguments: [0]\n" }, { "code": null, "e": 25501, "s": 25253, "text": "Final block: The final block in dart is used to include specific code that must be executed irrespective of error in the code. Although it is optional to include finally block if you include it then it should be after try and catch block are over." }, { "code": null, "e": 25521, "s": 25501, "text": "finally {\n ...\n}\n" }, { "code": null, "e": 25532, "s": 25521, "text": "Example: " }, { "code": null, "e": 25537, "s": 25532, "text": "Dart" }, { "code": "void main() { int geek = 10; try{ var geek2 = geek ~/ 0; print(geek2); } catch(e){ print(e); } finally { print(\"Code is at end, Geek\"); }}", "e": 25695, "s": 25537, "text": null }, { "code": null, "e": 25707, "s": 25697, "text": "Output: " }, { "code": null, "e": 25803, "s": 25707, "text": "Unsupported operation: Result of truncating division is Infinity: 10 ~/ 0\nCode is at end, Geek\n" }, { "code": null, "e": 25930, "s": 25803, "text": "Unlike other languages, in Dart to one can create a custom exception. To do, so we make use of throw new keyword in the dart. " }, { "code": null, "e": 25980, "s": 25930, "text": "Example: Creating custom exceptions in the dart. " }, { "code": null, "e": 25985, "s": 25980, "text": "Dart" }, { "code": "// extending Class Age// with Exception classclass Age implements Exception { String error() => 'Geek, your age is less than 18 :(';} void main() { int geek_age1 = 20; int geek_age2 = 10; try{ // Checking Age and // calling if the // exception occur check(geek_age1); check(geek_age2); } catch(e){ // Printing error print(e.error()); }} // Checking Agevoid check(int age){ if(age < 18){ throw new Age(); } else { print(\"You are eligible to visit GeeksForGeeks :)\"); }}", "e": 26499, "s": 25985, "text": null }, { "code": null, "e": 26510, "s": 26501, "text": "Output: " }, { "code": null, "e": 26588, "s": 26510, "text": "You are eligible to visit GeeksForGeeks :)\nGeek, your age is less than 18 :(\n" }, { "code": null, "e": 26612, "s": 26588, "text": "Dart-Exception-Handling" }, { "code": null, "e": 26617, "s": 26612, "text": "Dart" }, { "code": null, "e": 26715, "s": 26617, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26724, "s": 26715, "text": "Comments" }, { "code": null, "e": 26737, "s": 26724, "text": "Old Comments" }, { "code": null, "e": 26769, "s": 26737, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 26808, "s": 26769, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 26834, "s": 26808, "text": "ListView Class in Flutter" }, { "code": null, "e": 26861, "s": 26834, "text": "Flutter - BoxShadow Widget" }, { "code": null, "e": 26875, "s": 26861, "text": "Dart Tutorial" }, { "code": null, "e": 26901, "s": 26875, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 26947, "s": 26901, "text": "How to Append or Concatenate Strings in Dart?" }, { "code": null, "e": 26965, "s": 26947, "text": "Operators in Dart" }, { "code": null, "e": 26995, "s": 26965, "text": "Flutter - BorderRadius Widget" } ]
Split the number into N parts such that difference between the smallest and the largest part is minimum - GeeksforGeeks
10 Mar, 2022 Given two integers ‘X’ and ‘N’, the task is to split the integer ‘X’ into exactly ‘N’ parts such that: X1 + X2 + X3 + ... + Xn = X and the difference between the maximum and the minimum number from the sequence is minimized. Print the sequence in the end, if the number cannot be divided into exactly ‘N’ parts then print ‘-1’ instead. Examples: Input: X = 5, N = 3 Output: 1 2 2 Divide 5 into 3 parts such that the difference between the largest and smallest integer among them is as minimal as possible. So we divide 5 as 1 + 2 + 2. Input: X = 25, N = 5 Output: 5 5 5 5 5 Approach: There is always a way of splitting the number if X >= N. If the number is being split into exactly ‘N’ parts then every part will have the value X/N and the remaining X%N part can be distributed among any X%N numbers. Thus, if X % N == 0 then the minimum difference will always be ‘0’ and the sequence will contain all equal numbers i.e. x/n. Else, the difference will be ‘1’ and the sequence will be X/N, X/N, ..., (X/N)+1, (X/N)+1.. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP implementation of the approach#include<bits/stdc++.h>using namespace std;; // Function that prints// the required sequencevoid split(int x, int n){ // If we cannot split the// number into exactly 'N' partsif(x < n)cout<<"-1"<<" "; // If x % n == 0 then the minimum // difference is 0 and all // numbers are x / n else if (x % n == 0) { for(int i=0;i<n;i++) cout<<(x/n)<<" "; } else { // upto n-(x % n) the values // will be x / n // after that the values // will be x / n + 1 int zp = n - (x % n); int pp = x/n; for(int i=0;i<n;i++) { if(i>= zp) cout<<(pp + 1)<<" "; else cout<<pp<<" "; } }} // Driver codeint main(){ int x = 5;int n = 3;split(x, n); }//THis code is contributed// Surendra_Gangwar // Java implementation of the approach class GFG{// Function that prints// the required sequencestatic void split(int x, int n){ // If we cannot split the// number into exactly 'N' partsif(x < n)System.out.print("-1 "); // If x % n == 0 then the minimum // difference is 0 and all // numbers are x / n else if (x % n == 0) { for(int i=0;i<n;i++) System.out.print((x/n)+" "); } else { // upto n-(x % n) the values // will be x / n // after that the values // will be x / n + 1 int zp = n - (x % n); int pp = x/n; for(int i=0;i<n;i++) { if(i>= zp) System.out.print((pp + 1)+" "); else System.out.print(pp+" "); } }} // Driver codepublic static void main(String[] args){ int x = 5;int n = 3;split(x, n); }}//This code is contributed by mits # Python3 implementation of the approach # Function that prints# the required sequencedef split(x, n): # If we cannot split the # number into exactly 'N' parts if(x < n): print(-1) # If x % n == 0 then the minimum # difference is 0 and all # numbers are x / n elif (x % n == 0): for i in range(n): print(x//n, end =" ") else: # upto n-(x % n) the values # will be x / n # after that the values # will be x / n + 1 zp = n - (x % n) pp = x//n for i in range(n): if(i>= zp): print(pp + 1, end =" ") else: print(pp, end =" ") # Driver code x = 5n = 3split(x, n) // C# implementation of the approachusing System; public class GFG{ // Function that prints// the required sequencestatic void split(int x, int n){ // If we cannot split the// number into exactly 'N' partsif(x < n)Console.WriteLine("-1 "); // If x % n == 0 then the minimum // difference is 0 and all // numbers are x / n else if (x % n == 0) { for(int i=0;i<n;i++) Console.Write((x/n)+" "); } else { // upto n-(x % n) the values // will be x / n // after that the values // will be x / n + 1 int zp = n - (x % n); int pp = x/n; for(int i=0;i<n;i++) { if(i>= zp) Console.Write((pp + 1)+" "); else Console.Write(pp+" "); } }} // Driver codestatic public void Main (){ int x = 5;int n = 3;split(x, n); }}//This code is contributed by Sachin. <?php// PHP implementation of the approach // Function that prints// the required sequencefunction split($x, $n){ // If we cannot split the // number into exactly 'N' parts if($x < $n) echo (-1); // If x % n == 0 then the minimum // difference is 0 and all // numbers are x / n else if ($x % $n == 0) { for($i = 0; $i < $n; $i++) { echo ($x / $n); echo (" "); } } else { // upto n-(x % n) the values // will be x / n // after that the values // will be x / n + 1 $zp = $n - ($x % $n); $pp = $x / $n; for ($i = 0; $i < $n; $i++) { if($i >= $zp) { echo (int)$pp + 1; echo (" "); } else { echo (int)$pp; echo (" "); } } }} // Driver code $x = 5;$n = 3;split( $x, $n); // This code is contributed// by Shivi_Aggarwal?> <script> // JavaScript implementation of the above approach // Function that prints// the required sequencefunction split(x, n){ // If we cannot split the// number into exactly 'N' partsif(x < n)document.write("-1 "); // If x % n == 0 then the minimum // difference is 0 and all // numbers are x / n else if (x % n == 0) { for(let i=0;i<n;i++) document.write((x/n)+" "); } else { // upto n-(x % n) the values // will be x / n // after that the values // will be x / n + 1 let zp = n - (x % n); let pp = Math.floor(x/n); for(let i=0;i<n;i++) { if(i>= zp) document.write((pp + 1)+" "); else document.write(pp+" "); } }} // driver code let x = 5; let n = 3; split(x, n); </script> 1 2 2 Time Complexity: O(n)Auxiliary Space: O(1) Shivi_Aggarwal SURENDRA_GANGWAR Mithun Kumar Sach_Code target_2 khushboogoyal499 simranarora5sos singhh3010 Modular Arithmetic Greedy Mathematical Greedy Mathematical Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Huffman Coding | Greedy Algo-3 Coin Change | DP-7 Fractional Knapsack Problem Activity Selection Problem | Greedy Algo-1 Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 26897, "s": 26869, "text": "\n10 Mar, 2022" }, { "code": null, "e": 27233, "s": 26897, "text": "Given two integers ‘X’ and ‘N’, the task is to split the integer ‘X’ into exactly ‘N’ parts such that: X1 + X2 + X3 + ... + Xn = X and the difference between the maximum and the minimum number from the sequence is minimized. Print the sequence in the end, if the number cannot be divided into exactly ‘N’ parts then print ‘-1’ instead." }, { "code": null, "e": 27245, "s": 27233, "text": "Examples: " }, { "code": null, "e": 27434, "s": 27245, "text": "Input: X = 5, N = 3 Output: 1 2 2 Divide 5 into 3 parts such that the difference between the largest and smallest integer among them is as minimal as possible. So we divide 5 as 1 + 2 + 2." }, { "code": null, "e": 27473, "s": 27434, "text": "Input: X = 25, N = 5 Output: 5 5 5 5 5" }, { "code": null, "e": 27542, "s": 27473, "text": "Approach: There is always a way of splitting the number if X >= N. " }, { "code": null, "e": 27703, "s": 27542, "text": "If the number is being split into exactly ‘N’ parts then every part will have the value X/N and the remaining X%N part can be distributed among any X%N numbers." }, { "code": null, "e": 27828, "s": 27703, "text": "Thus, if X % N == 0 then the minimum difference will always be ‘0’ and the sequence will contain all equal numbers i.e. x/n." }, { "code": null, "e": 27920, "s": 27828, "text": "Else, the difference will be ‘1’ and the sequence will be X/N, X/N, ..., (X/N)+1, (X/N)+1.." }, { "code": null, "e": 27973, "s": 27920, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27977, "s": 27973, "text": "C++" }, { "code": null, "e": 27982, "s": 27977, "text": "Java" }, { "code": null, "e": 27990, "s": 27982, "text": "Python3" }, { "code": null, "e": 27993, "s": 27990, "text": "C#" }, { "code": null, "e": 27997, "s": 27993, "text": "PHP" }, { "code": null, "e": 28008, "s": 27997, "text": "Javascript" }, { "code": "// CPP implementation of the approach#include<bits/stdc++.h>using namespace std;; // Function that prints// the required sequencevoid split(int x, int n){ // If we cannot split the// number into exactly 'N' partsif(x < n)cout<<\"-1\"<<\" \"; // If x % n == 0 then the minimum // difference is 0 and all // numbers are x / n else if (x % n == 0) { for(int i=0;i<n;i++) cout<<(x/n)<<\" \"; } else { // upto n-(x % n) the values // will be x / n // after that the values // will be x / n + 1 int zp = n - (x % n); int pp = x/n; for(int i=0;i<n;i++) { if(i>= zp) cout<<(pp + 1)<<\" \"; else cout<<pp<<\" \"; } }} // Driver codeint main(){ int x = 5;int n = 3;split(x, n); }//THis code is contributed// Surendra_Gangwar", "e": 28886, "s": 28008, "text": null }, { "code": "// Java implementation of the approach class GFG{// Function that prints// the required sequencestatic void split(int x, int n){ // If we cannot split the// number into exactly 'N' partsif(x < n)System.out.print(\"-1 \"); // If x % n == 0 then the minimum // difference is 0 and all // numbers are x / n else if (x % n == 0) { for(int i=0;i<n;i++) System.out.print((x/n)+\" \"); } else { // upto n-(x % n) the values // will be x / n // after that the values // will be x / n + 1 int zp = n - (x % n); int pp = x/n; for(int i=0;i<n;i++) { if(i>= zp) System.out.print((pp + 1)+\" \"); else System.out.print(pp+\" \"); } }} // Driver codepublic static void main(String[] args){ int x = 5;int n = 3;split(x, n); }}//This code is contributed by mits", "e": 29807, "s": 28886, "text": null }, { "code": "# Python3 implementation of the approach # Function that prints# the required sequencedef split(x, n): # If we cannot split the # number into exactly 'N' parts if(x < n): print(-1) # If x % n == 0 then the minimum # difference is 0 and all # numbers are x / n elif (x % n == 0): for i in range(n): print(x//n, end =\" \") else: # upto n-(x % n) the values # will be x / n # after that the values # will be x / n + 1 zp = n - (x % n) pp = x//n for i in range(n): if(i>= zp): print(pp + 1, end =\" \") else: print(pp, end =\" \") # Driver code x = 5n = 3split(x, n)", "e": 30531, "s": 29807, "text": null }, { "code": "// C# implementation of the approachusing System; public class GFG{ // Function that prints// the required sequencestatic void split(int x, int n){ // If we cannot split the// number into exactly 'N' partsif(x < n)Console.WriteLine(\"-1 \"); // If x % n == 0 then the minimum // difference is 0 and all // numbers are x / n else if (x % n == 0) { for(int i=0;i<n;i++) Console.Write((x/n)+\" \"); } else { // upto n-(x % n) the values // will be x / n // after that the values // will be x / n + 1 int zp = n - (x % n); int pp = x/n; for(int i=0;i<n;i++) { if(i>= zp) Console.Write((pp + 1)+\" \"); else Console.Write(pp+\" \"); } }} // Driver codestatic public void Main (){ int x = 5;int n = 3;split(x, n); }}//This code is contributed by Sachin.", "e": 31435, "s": 30531, "text": null }, { "code": "<?php// PHP implementation of the approach // Function that prints// the required sequencefunction split($x, $n){ // If we cannot split the // number into exactly 'N' parts if($x < $n) echo (-1); // If x % n == 0 then the minimum // difference is 0 and all // numbers are x / n else if ($x % $n == 0) { for($i = 0; $i < $n; $i++) { echo ($x / $n); echo (\" \"); } } else { // upto n-(x % n) the values // will be x / n // after that the values // will be x / n + 1 $zp = $n - ($x % $n); $pp = $x / $n; for ($i = 0; $i < $n; $i++) { if($i >= $zp) { echo (int)$pp + 1; echo (\" \"); } else { echo (int)$pp; echo (\" \"); } } }} // Driver code $x = 5;$n = 3;split( $x, $n); // This code is contributed// by Shivi_Aggarwal?>", "e": 32434, "s": 31435, "text": null }, { "code": "<script> // JavaScript implementation of the above approach // Function that prints// the required sequencefunction split(x, n){ // If we cannot split the// number into exactly 'N' partsif(x < n)document.write(\"-1 \"); // If x % n == 0 then the minimum // difference is 0 and all // numbers are x / n else if (x % n == 0) { for(let i=0;i<n;i++) document.write((x/n)+\" \"); } else { // upto n-(x % n) the values // will be x / n // after that the values // will be x / n + 1 let zp = n - (x % n); let pp = Math.floor(x/n); for(let i=0;i<n;i++) { if(i>= zp) document.write((pp + 1)+\" \"); else document.write(pp+\" \"); } }} // driver code let x = 5; let n = 3; split(x, n); </script>", "e": 33315, "s": 32434, "text": null }, { "code": null, "e": 33321, "s": 33315, "text": "1 2 2" }, { "code": null, "e": 33366, "s": 33323, "text": "Time Complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 33381, "s": 33366, "text": "Shivi_Aggarwal" }, { "code": null, "e": 33398, "s": 33381, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 33411, "s": 33398, "text": "Mithun Kumar" }, { "code": null, "e": 33421, "s": 33411, "text": "Sach_Code" }, { "code": null, "e": 33430, "s": 33421, "text": "target_2" }, { "code": null, "e": 33447, "s": 33430, "text": "khushboogoyal499" }, { "code": null, "e": 33463, "s": 33447, "text": "simranarora5sos" }, { "code": null, "e": 33474, "s": 33463, "text": "singhh3010" }, { "code": null, "e": 33493, "s": 33474, "text": "Modular Arithmetic" }, { "code": null, "e": 33500, "s": 33493, "text": "Greedy" }, { "code": null, "e": 33513, "s": 33500, "text": "Mathematical" }, { "code": null, "e": 33520, "s": 33513, "text": "Greedy" }, { "code": null, "e": 33533, "s": 33520, "text": "Mathematical" }, { "code": null, "e": 33552, "s": 33533, "text": "Modular Arithmetic" }, { "code": null, "e": 33650, "s": 33552, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33681, "s": 33650, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 33700, "s": 33681, "text": "Coin Change | DP-7" }, { "code": null, "e": 33728, "s": 33700, "text": "Fractional Knapsack Problem" }, { "code": null, "e": 33771, "s": 33728, "text": "Activity Selection Problem | Greedy Algo-1" }, { "code": null, "e": 33852, "s": 33771, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 33882, "s": 33852, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33897, "s": 33882, "text": "C++ Data Types" }, { "code": null, "e": 33940, "s": 33897, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 33959, "s": 33940, "text": "Coin Change | DP-7" } ]
Fill bars in a base R barplot with colors based on frequency.
Suppose we have a vector that contains only frequencies and we want to create a bar chart in base R using these frequencies with color of bars based on frequencies, therefore, we can use barplot function and providing the color of the bars with as shown in the below Examples The function is as follows − heat.colors function To fill the bars in a base R barplot with colours based on frequency, use the command given below − Frequency_1<-c(2,4,8,3,10,1) barplot(Frequency_1,col=heat.colors(max(Frequency_1))[Frequency_1]) If you execute the above given snippet, it generates the following Output − To fill the bars in a base R barplot with colours based on frequency, use the command given below − Frequency_2<-c(25,31,28,21,15,45) barplot(Frequency_2,col=heat.colors(max(Frequency_2))[Frequency_2]) If you execute the above given snippet, it generates the following Output −
[ { "code": null, "e": 1338, "s": 1062, "text": "Suppose we have a vector that contains only frequencies and we want to create a bar\nchart in base R using these frequencies with color of bars based on frequencies,\ntherefore, we can use barplot function and providing the color of the bars with as shown\nin the below Examples" }, { "code": null, "e": 1367, "s": 1338, "text": "The function is as follows −" }, { "code": null, "e": 1388, "s": 1367, "text": "heat.colors function" }, { "code": null, "e": 1488, "s": 1388, "text": "To fill the bars in a base R barplot with colours based on frequency, use the command given below −" }, { "code": null, "e": 1585, "s": 1488, "text": "Frequency_1<-c(2,4,8,3,10,1)\nbarplot(Frequency_1,col=heat.colors(max(Frequency_1))[Frequency_1])" }, { "code": null, "e": 1661, "s": 1585, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 1761, "s": 1661, "text": "To fill the bars in a base R barplot with colours based on frequency, use the command given below −" }, { "code": null, "e": 1863, "s": 1761, "text": "Frequency_2<-c(25,31,28,21,15,45)\nbarplot(Frequency_2,col=heat.colors(max(Frequency_2))[Frequency_2])" }, { "code": null, "e": 1939, "s": 1863, "text": "If you execute the above given snippet, it generates the following Output −" } ]
How to use Fab Component in ReactJS? - GeeksforGeeks
20 Jan, 2021 Fab stands for Floating Action Button is which appears in front of all screen content, typically as a circular shape with an icon in its center. Material UI for React has this component available for us and it is very easy to integrate. It can be used to turn an option on or off. We can use the Fab Component in ReactJS using the following approach: Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command: npm install @material-ui/core npm install @material-ui/icons Project Structure: It will look like the following. Project Structure App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react';import Fab from '@material-ui/core/Fab';import EditIcon from '@material-ui/icons/Edit'; const App = () => { return ( <div style={{ margin: 'auto', display: 'block', width: 'fit-content' }}> <h3>How to use Fab Component in ReactJS?</h3> <Fab color="secondary" aria-label="edit"> <EditIcon /> </Fab> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 25410, "s": 25382, "text": "\n20 Jan, 2021" }, { "code": null, "e": 25761, "s": 25410, "text": "Fab stands for Floating Action Button is which appears in front of all screen content, typically as a circular shape with an icon in its center. Material UI for React has this component available for us and it is very easy to integrate. It can be used to turn an option on or off. We can use the Fab Component in ReactJS using the following approach:" }, { "code": null, "e": 25811, "s": 25761, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25875, "s": 25811, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25907, "s": 25875, "text": "npx create-react-app foldername" }, { "code": null, "e": 26007, "s": 25907, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 26021, "s": 26007, "text": "cd foldername" }, { "code": null, "e": 26130, "s": 26021, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:" }, { "code": null, "e": 26191, "s": 26130, "text": "npm install @material-ui/core\nnpm install @material-ui/icons" }, { "code": null, "e": 26243, "s": 26191, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26261, "s": 26243, "text": "Project Structure" }, { "code": null, "e": 26390, "s": 26261, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 26401, "s": 26390, "text": "Javascript" }, { "code": "import React from 'react';import Fab from '@material-ui/core/Fab';import EditIcon from '@material-ui/icons/Edit'; const App = () => { return ( <div style={{ margin: 'auto', display: 'block', width: 'fit-content' }}> <h3>How to use Fab Component in ReactJS?</h3> <Fab color=\"secondary\" aria-label=\"edit\"> <EditIcon /> </Fab> </div> );} export default App;", "e": 26808, "s": 26401, "text": null }, { "code": null, "e": 26921, "s": 26808, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 26931, "s": 26921, "text": "npm start" }, { "code": null, "e": 27030, "s": 26931, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27041, "s": 27030, "text": "JavaScript" }, { "code": null, "e": 27049, "s": 27041, "text": "ReactJS" }, { "code": null, "e": 27066, "s": 27049, "text": "Web Technologies" }, { "code": null, "e": 27164, "s": 27066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27204, "s": 27164, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27265, "s": 27204, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27306, "s": 27265, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27328, "s": 27306, "text": "JavaScript | Promises" }, { "code": null, "e": 27382, "s": 27328, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27425, "s": 27382, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27470, "s": 27425, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27535, "s": 27470, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 27603, "s": 27535, "text": "How to pass data from one component to other component in ReactJS ?" } ]
Pytest - Environment Setup
In this chapter, we will learn how to install pytest. To start the installation, execute the following command − pip install pytest == 2.9.1 We can install any version of pytest. Here, 2.9.1 is the version we are installing. To install the latest version of pytest, execute the following command − pip install pytest Confirm the installation using the following command to display the help section of pytest. pytest -h 21 Lectures 4 hours Lucian Musat 22 Lectures 1.5 hours Fanuel Mapuwei 44 Lectures 3.5 hours Rohit Dharaviya Print Add Notes Bookmark this page
[ { "code": null, "e": 2096, "s": 2042, "text": "In this chapter, we will learn how to install pytest." }, { "code": null, "e": 2155, "s": 2096, "text": "To start the installation, execute the following command −" }, { "code": null, "e": 2184, "s": 2155, "text": "pip install pytest == 2.9.1\n" }, { "code": null, "e": 2268, "s": 2184, "text": "We can install any version of pytest. Here, 2.9.1 is the version we are installing." }, { "code": null, "e": 2341, "s": 2268, "text": "To install the latest version of pytest, execute the following command −" }, { "code": null, "e": 2361, "s": 2341, "text": "pip install pytest\n" }, { "code": null, "e": 2453, "s": 2361, "text": "Confirm the installation using the following command to display the help section of pytest." }, { "code": null, "e": 2464, "s": 2453, "text": "pytest -h\n" }, { "code": null, "e": 2497, "s": 2464, "text": "\n 21 Lectures \n 4 hours \n" }, { "code": null, "e": 2511, "s": 2497, "text": " Lucian Musat" }, { "code": null, "e": 2546, "s": 2511, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2562, "s": 2546, "text": " Fanuel Mapuwei" }, { "code": null, "e": 2597, "s": 2562, "text": "\n 44 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2614, "s": 2597, "text": " Rohit Dharaviya" }, { "code": null, "e": 2621, "s": 2614, "text": " Print" }, { "code": null, "e": 2632, "s": 2621, "text": " Add Notes" } ]
Productivity Tracking with the Notion API and Python | by Lucas Soares | Towards Data Science
1 2 3 4 5 6 7 8 9 10 Powered by Play.ht Create audio with Play.ht Powered by Play.ht With the recent release of the very much anticipated beta version of the Notion API, a lot of integrations between apps are now possible, and an entire universe of possibilities is now open for data science projects. In this post, I will show you how to build a simple project tracking dashboard with Streamlit and the Notion API. If you prefer, you can check out my youtube video on this topic: Let’s start with creating a page on Notion. Now, you need to create an integration token on your Notion page and then share your database with that integration. A detailed tutorial on how to do that can be found here. Now, you can set up a simple python API to communicate with your database in the Notion app so you can fetch the data. In my case I created a simple database with each property (column on the table) referencing a project, each line relating to a day of the month, and each entry containing a checkbox indicating whether or not that project was worked on that given day. On my Notion page, it looks like this: To fetch the data from the Notion database we can write a class with three methods: query_databases() to fetch the data from the Notion app;get_projects_titles to get the names of the projects you are tracking (they will be the titles of the columns in your Notion database);get_projects_data to get the projects tracking data from the resulting dictionary object obtained from the Notion API. query_databases() to fetch the data from the Notion app; get_projects_titles to get the names of the projects you are tracking (they will be the titles of the columns in your Notion database); get_projects_data to get the projects tracking data from the resulting dictionary object obtained from the Notion API. The full code for the python API: Let’s do a quick breakdown of each component: Querying the database Here, we are sending a post request to our database using the integration token from the Notion API, and we return the response as a json object to facilitate formatting the data in the shape we need to visualize it later. Getting the names of the projects Here, we are simply retrieving all the properties in our database. More details on how to work with databases using the Notion API can be found here. Getting the projects data Finally, we fetch the data from each project as well as the dates column. Now that we have the data loaded up, let’s use the plotly package to plot the projects’ information. Let’s do something simple and plot a bar chart with the number of days spent on each project over the tracked period (in this case the last 45 days) and a project events scatter plot that shows my daily activity (whether or not I worked on each project). Let’s start by importing our dependencies. import plotly.graph_objs as goimport pandas as pdimport plotly.express as pxfrom notion_api import * Now we use our python API to fetch the data from the Notion database. nsync = NotionSync()data = nsync.query_databases()projects = nsync.get_projects_titles(data)projects_data,dates = nsync.get_projects_data(data,projects) We set up a dataframe with the data we want to explore and plot the events tracker and the bar chart. It works perfectly! The really cool aspect of this tool is that, as we update our Notion page, this plot will update automatically without any extra effort needed. Now, let’s plot an events plot that tells us what we are working on each day over a given time period. We will need to turn the boolean values from the checkbox property in the database into continuous values that we can plot in such a way that each line in the y-axis represents a different project and each dot over that line region will represent having worked on that project on that given day. There we have it. To finish things off, let’s wrap this code on a Streamlit app so that we can look at our data anytime we want by just running a command on the terminal. To do that, we just need a few lines of code: The load_data function takes care of fetching the data directly from our Notion database, and the following code is just setting up a title and a subheader for the plots to be shown in Streamlit using the plotly package. The minimalistic style of Streamlit makes this really simple. On the terminal, run the Streamlit app with: streamlit run app.py The entire source code for this project can be found here. This new beta version of the Notion API is really powerful. Realizing that the app had only provided an SDK in javascript, I wrote this code to make it nicely integrated with python. The integrations that Notion now offers with this official API can really take productivity projects like this one to a whole other level and I feel like we will see more and more really interesting features appearing in the upcoming future. If you liked this post connect with me on Twitter, LinkedIn and follow me on Medium. Thanks and see you next time! :) Getting Started with the Notion API working with databases in Notion retrieve database in Notion Python API integration tutorial
[ { "code": null, "e": 174, "s": 172, "text": "1" }, { "code": null, "e": 176, "s": 174, "text": "2" }, { "code": null, "e": 178, "s": 176, "text": "3" }, { "code": null, "e": 180, "s": 178, "text": "4" }, { "code": null, "e": 182, "s": 180, "text": "5" }, { "code": null, "e": 184, "s": 182, "text": "6" }, { "code": null, "e": 186, "s": 184, "text": "7" }, { "code": null, "e": 188, "s": 186, "text": "8" }, { "code": null, "e": 190, "s": 188, "text": "9" }, { "code": null, "e": 193, "s": 190, "text": "10" }, { "code": null, "e": 212, "s": 193, "text": "Powered by Play.ht" }, { "code": null, "e": 238, "s": 212, "text": "Create audio with Play.ht" }, { "code": null, "e": 257, "s": 238, "text": "Powered by Play.ht" }, { "code": null, "e": 474, "s": 257, "text": "With the recent release of the very much anticipated beta version of the Notion API, a lot of integrations between apps are now possible, and an entire universe of possibilities is now open for data science projects." }, { "code": null, "e": 588, "s": 474, "text": "In this post, I will show you how to build a simple project tracking dashboard with Streamlit and the Notion API." }, { "code": null, "e": 653, "s": 588, "text": "If you prefer, you can check out my youtube video on this topic:" }, { "code": null, "e": 871, "s": 653, "text": "Let’s start with creating a page on Notion. Now, you need to create an integration token on your Notion page and then share your database with that integration. A detailed tutorial on how to do that can be found here." }, { "code": null, "e": 990, "s": 871, "text": "Now, you can set up a simple python API to communicate with your database in the Notion app so you can fetch the data." }, { "code": null, "e": 1280, "s": 990, "text": "In my case I created a simple database with each property (column on the table) referencing a project, each line relating to a day of the month, and each entry containing a checkbox indicating whether or not that project was worked on that given day. On my Notion page, it looks like this:" }, { "code": null, "e": 1364, "s": 1280, "text": "To fetch the data from the Notion database we can write a class with three methods:" }, { "code": null, "e": 1674, "s": 1364, "text": "query_databases() to fetch the data from the Notion app;get_projects_titles to get the names of the projects you are tracking (they will be the titles of the columns in your Notion database);get_projects_data to get the projects tracking data from the resulting dictionary object obtained from the Notion API." }, { "code": null, "e": 1731, "s": 1674, "text": "query_databases() to fetch the data from the Notion app;" }, { "code": null, "e": 1867, "s": 1731, "text": "get_projects_titles to get the names of the projects you are tracking (they will be the titles of the columns in your Notion database);" }, { "code": null, "e": 1986, "s": 1867, "text": "get_projects_data to get the projects tracking data from the resulting dictionary object obtained from the Notion API." }, { "code": null, "e": 2020, "s": 1986, "text": "The full code for the python API:" }, { "code": null, "e": 2066, "s": 2020, "text": "Let’s do a quick breakdown of each component:" }, { "code": null, "e": 2088, "s": 2066, "text": "Querying the database" }, { "code": null, "e": 2311, "s": 2088, "text": "Here, we are sending a post request to our database using the integration token from the Notion API, and we return the response as a json object to facilitate formatting the data in the shape we need to visualize it later." }, { "code": null, "e": 2345, "s": 2311, "text": "Getting the names of the projects" }, { "code": null, "e": 2495, "s": 2345, "text": "Here, we are simply retrieving all the properties in our database. More details on how to work with databases using the Notion API can be found here." }, { "code": null, "e": 2521, "s": 2495, "text": "Getting the projects data" }, { "code": null, "e": 2595, "s": 2521, "text": "Finally, we fetch the data from each project as well as the dates column." }, { "code": null, "e": 2696, "s": 2595, "text": "Now that we have the data loaded up, let’s use the plotly package to plot the projects’ information." }, { "code": null, "e": 2951, "s": 2696, "text": "Let’s do something simple and plot a bar chart with the number of days spent on each project over the tracked period (in this case the last 45 days) and a project events scatter plot that shows my daily activity (whether or not I worked on each project)." }, { "code": null, "e": 2994, "s": 2951, "text": "Let’s start by importing our dependencies." }, { "code": null, "e": 3095, "s": 2994, "text": "import plotly.graph_objs as goimport pandas as pdimport plotly.express as pxfrom notion_api import *" }, { "code": null, "e": 3165, "s": 3095, "text": "Now we use our python API to fetch the data from the Notion database." }, { "code": null, "e": 3318, "s": 3165, "text": "nsync = NotionSync()data = nsync.query_databases()projects = nsync.get_projects_titles(data)projects_data,dates = nsync.get_projects_data(data,projects)" }, { "code": null, "e": 3420, "s": 3318, "text": "We set up a dataframe with the data we want to explore and plot the events tracker and the bar chart." }, { "code": null, "e": 3584, "s": 3420, "text": "It works perfectly! The really cool aspect of this tool is that, as we update our Notion page, this plot will update automatically without any extra effort needed." }, { "code": null, "e": 3687, "s": 3584, "text": "Now, let’s plot an events plot that tells us what we are working on each day over a given time period." }, { "code": null, "e": 3983, "s": 3687, "text": "We will need to turn the boolean values from the checkbox property in the database into continuous values that we can plot in such a way that each line in the y-axis represents a different project and each dot over that line region will represent having worked on that project on that given day." }, { "code": null, "e": 4154, "s": 3983, "text": "There we have it. To finish things off, let’s wrap this code on a Streamlit app so that we can look at our data anytime we want by just running a command on the terminal." }, { "code": null, "e": 4200, "s": 4154, "text": "To do that, we just need a few lines of code:" }, { "code": null, "e": 4483, "s": 4200, "text": "The load_data function takes care of fetching the data directly from our Notion database, and the following code is just setting up a title and a subheader for the plots to be shown in Streamlit using the plotly package. The minimalistic style of Streamlit makes this really simple." }, { "code": null, "e": 4549, "s": 4483, "text": "On the terminal, run the Streamlit app with: streamlit run app.py" }, { "code": null, "e": 4608, "s": 4549, "text": "The entire source code for this project can be found here." }, { "code": null, "e": 4791, "s": 4608, "text": "This new beta version of the Notion API is really powerful. Realizing that the app had only provided an SDK in javascript, I wrote this code to make it nicely integrated with python." }, { "code": null, "e": 5033, "s": 4791, "text": "The integrations that Notion now offers with this official API can really take productivity projects like this one to a whole other level and I feel like we will see more and more really interesting features appearing in the upcoming future." }, { "code": null, "e": 5151, "s": 5033, "text": "If you liked this post connect with me on Twitter, LinkedIn and follow me on Medium. Thanks and see you next time! :)" }, { "code": null, "e": 5187, "s": 5151, "text": "Getting Started with the Notion API" }, { "code": null, "e": 5220, "s": 5187, "text": "working with databases in Notion" }, { "code": null, "e": 5248, "s": 5220, "text": "retrieve database in Notion" } ]
How to redirect URL to the different website after few seconds?
Page redirection is a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection. To redirect URL to a different website after few seconds, use the META tag, with the content attribute. The attributes set the seconds. The following is an example of redirecting current page to another website in 10 seconds. The content attribute sets the seconds. Live Demo <!DOCTYPE html> <html> <head> <title>HTML Meta Tag</title> <meta http-equiv = "refresh" content = "10; url = https://www.tutorialspoint.com" /> </head> <body> <p>Hello HTML5!</p> </body> </html>
[ { "code": null, "e": 1224, "s": 1062, "text": "Page redirection is a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection." }, { "code": null, "e": 1360, "s": 1224, "text": "To redirect URL to a different website after few seconds, use the META tag, with the content attribute. The attributes set the seconds." }, { "code": null, "e": 1490, "s": 1360, "text": "The following is an example of redirecting current page to another website in 10 seconds. The content attribute sets the seconds." }, { "code": null, "e": 1500, "s": 1490, "text": "Live Demo" }, { "code": null, "e": 1729, "s": 1500, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Meta Tag</title>\n <meta http-equiv = \"refresh\" content = \"10; url = https://www.tutorialspoint.com\" />\n </head>\n \n <body>\n <p>Hello HTML5!</p>\n </body>\n</html>" } ]
XAML - Templates
A template describes the overall look and visual appearance of a control. For each control, there is a default template associated with it which gives the appearance to that control. In XAML, you can easily create your own templates when you want to customize the visual behavior and visual appearance of a control. Connectivity between the logic and template can be achieved by data binding. The main difference between styles and templates are − Styles can only change the appearance of your control with default properties of that control. Styles can only change the appearance of your control with default properties of that control. With templates, you can access more parts of a control than in styles. You can also specify both existing and new behavior of a control. With templates, you can access more parts of a control than in styles. You can also specify both existing and new behavior of a control. There are two types of templates which are most commonly used. Control Template Data Template The Control Template defines or specifies the visual appearance and structure of a control. All of the UI elements have some kind of appearance as well as behavior, e.g., Button has an appearance and behavior. Click event or mouse hover events are the behaviors which are fired in response to a click and hover, and there is also a default appearance of button which can be changed by the Control template. Let’s have a look at a simple example again in which two buttons are created with some properties. One is with template and the other one is with the default button. <Window x:Class = "TemplateDemo.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Window.Resources> <ControlTemplate x:Key = "ButtonTemplate" TargetType = "Button"> <Grid> <Ellipse x:Name = "ButtonEllipse" Height = "100" Width = "150" > <Ellipse.Fill> <LinearGradientBrush StartPoint = "0,0.2" EndPoint = "0.2,1.4"> <GradientStop Offset = "0" Color = "Red"/> <GradientStop Offset = "1" Color = "Orange"/> </LinearGradientBrush> </Ellipse.Fill> </Ellipse> <ContentPresenter Content = "{TemplateBinding Content}" HorizontalAlignment = "Center" VerticalAlignment = "Center" /> </Grid> <ControlTemplate.Triggers> <Trigger Property = "IsMouseOver" Value = "True"> <Setter TargetName = "ButtonEllipse" Property = "Fill" > <Setter.Value> <LinearGradientBrush StartPoint = "0,0.2" EndPoint="0.2,1.4"> <GradientStop Offset = "0" Color = "YellowGreen"/> <GradientStop Offset = "1" Color = "Gold"/> </LinearGradientBrush> </Setter.Value> </Setter> </Trigger> <Trigger Property = "IsPressed" Value = "True"> <Setter Property = "RenderTransform"> <Setter.Value> <ScaleTransform ScaleX = "0.8" ScaleY = "0.8" CenterX = "0" CenterY = "0" /> </Setter.Value> </Setter> <Setter Property = "RenderTransformOrigin" Value = "0.5,0.5" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Window.Resources> <StackPanel> <Button Content = "Round Button!" Template = "{StaticResource ButtonTemplate}" Width = "150" Margin = "50" /> <Button Content = "Default Button!" Height = "40" Width = "150" Margin = "5" /> </StackPanel> </Window> When the above code is compiled and executed, it will produce the following MainWindow − When you hover the mouse over the button with custom template, then it also changes the color as shown below − A Data Template defines and specifies the appearance and structure of the collection of data. It provides the flexibility to format and define the presentation of the data on any UI element. It is mostly used on data related Item controls such as ComboBox, ListBox, etc. Let’s have a look at a simple example of data template. The following XAML code creates a combobox with Data Template and text blocks. <Window x:Class = "XAMLDataTemplate.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid VerticalAlignment = "Top"> <ComboBox Name = "Presidents" ItemsSource = "{Binding}" Height = "30" Width = "400"> <ComboBox.ItemTemplate> <DataTemplate> <StackPanel Orientation = "Horizontal" Margin = "2"> <TextBlock Text = "Name: " Width = "95" Background = "Aqua" Margin = "2" /> <TextBlock Text = "{Binding Name}" Width = "95" Background = "AliceBlue" Margin = "2" /> <TextBlock Text = "Title: " Width = "95" Background = "Aqua" Margin = "10,2,0,2" /> <TextBlock Text = "{Binding Title}" Width = "95" Background = "AliceBlue" Margin = "2" /> </StackPanel> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> </Grid> </Window> Here is the implementation in C# in which the employee object is assigned to DataContext − using System; using System.Windows; using System.Windows.Controls; namespace XAMLDataTemplate { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = Employee.GetEmployees(); } } } Here is the implementation in C# for Employee class − using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace XAMLDataTemplate { public class Employee : INotifyPropertyChanged { private string name; public string Name { get { return name; } set { name = value; RaiseProperChanged(); } } private string title; public string Title { get { return title; } set { title = value; RaiseProperChanged(); } } public static Employee GetEmployee() { var emp = new Employee() { Name = "Waqas", Title = "Software Engineer" }; return emp; } public event PropertyChangedEventHandler PropertyChanged; private void RaiseProperChanged( [CallerMemberName] string caller = ""){ if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(caller)); } } public static ObservableCollection<Employee> GetEmployees() { var employees = new ObservableCollection<Employee>(); employees.Add(new Employee() { Name = "Ali", Title = "Developer" }); employees.Add(new Employee() { Name = "Ahmed", Title = "Programmer" }); employees.Add(new Employee() { Name = "Amjad", Title = "Desiner" }); employees.Add(new Employee() { Name = "Waqas", Title = "Programmer" }); employees.Add(new Employee() { Name = "Bilal", Title = "Engineer" }); employees.Add(new Employee() { Name = "Waqar", Title = "Manager" }); return employees; } } } When the above code is compiled and executed, it will produce the following output. It contains a combobox and when you click on the combobox, you see that the collection of data which are created in the Employee class is listed as the combobox items. We recommend you to execute the above code and experiment with it. Print Add Notes Bookmark this page
[ { "code": null, "e": 2106, "s": 1923, "text": "A template describes the overall look and visual appearance of a control. For each control, there is a default template associated with it which gives the appearance to that control." }, { "code": null, "e": 2316, "s": 2106, "text": "In XAML, you can easily create your own templates when you want to customize the visual behavior and visual appearance of a control. Connectivity between the logic and template can be achieved by data binding." }, { "code": null, "e": 2371, "s": 2316, "text": "The main difference between styles and templates are −" }, { "code": null, "e": 2466, "s": 2371, "text": "Styles can only change the appearance of your control with default properties of that control." }, { "code": null, "e": 2561, "s": 2466, "text": "Styles can only change the appearance of your control with default properties of that control." }, { "code": null, "e": 2698, "s": 2561, "text": "With templates, you can access more parts of a control than in styles. You can also specify both existing and new behavior of a control." }, { "code": null, "e": 2835, "s": 2698, "text": "With templates, you can access more parts of a control than in styles. You can also specify both existing and new behavior of a control." }, { "code": null, "e": 2898, "s": 2835, "text": "There are two types of templates which are most commonly used." }, { "code": null, "e": 2915, "s": 2898, "text": "Control Template" }, { "code": null, "e": 2929, "s": 2915, "text": "Data Template" }, { "code": null, "e": 3336, "s": 2929, "text": "The Control Template defines or specifies the visual appearance and structure of a control. All of the UI elements have some kind of appearance as well as behavior, e.g., Button has an appearance and behavior. Click event or mouse hover events are the behaviors which are fired in response to a click and hover, and there is also a default appearance of button which can be changed by the Control template." }, { "code": null, "e": 3502, "s": 3336, "text": "Let’s have a look at a simple example again in which two buttons are created with some properties. One is with template and the other one is with the default button." }, { "code": null, "e": 5758, "s": 3502, "text": "<Window x:Class = \"TemplateDemo.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Window.Resources>\n <ControlTemplate x:Key = \"ButtonTemplate\" TargetType = \"Button\">\n <Grid>\n <Ellipse x:Name = \"ButtonEllipse\" Height = \"100\" Width = \"150\" >\n <Ellipse.Fill> \n <LinearGradientBrush StartPoint = \"0,0.2\" EndPoint = \"0.2,1.4\"> \n <GradientStop Offset = \"0\" Color = \"Red\"/>\n <GradientStop Offset = \"1\" Color = \"Orange\"/>\n </LinearGradientBrush> \n </Ellipse.Fill>\n </Ellipse>\n <ContentPresenter Content = \"{TemplateBinding Content}\"\n HorizontalAlignment = \"Center\" VerticalAlignment = \"Center\" />\n </Grid>\n <ControlTemplate.Triggers> \n <Trigger Property = \"IsMouseOver\" Value = \"True\">\n <Setter TargetName = \"ButtonEllipse\" Property = \"Fill\" >\n <Setter.Value> \n <LinearGradientBrush StartPoint = \"0,0.2\" EndPoint=\"0.2,1.4\"> \n <GradientStop Offset = \"0\" Color = \"YellowGreen\"/>\n <GradientStop Offset = \"1\" Color = \"Gold\"/>\n </LinearGradientBrush> \n </Setter.Value> \n </Setter>\n </Trigger> \n\t\t\t\t\n <Trigger Property = \"IsPressed\" Value = \"True\"> \n <Setter Property = \"RenderTransform\"> \n <Setter.Value> \n <ScaleTransform ScaleX = \"0.8\" ScaleY = \"0.8\" CenterX = \"0\" CenterY = \"0\" /> \n </Setter.Value> \n </Setter> \n\t\t\t\t\t\n <Setter Property = \"RenderTransformOrigin\" Value = \"0.5,0.5\" /> \n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate> \n </Window.Resources>\n\t\n <StackPanel> \n <Button Content = \"Round Button!\" Template = \"{StaticResource ButtonTemplate}\" \n Width = \"150\" Margin = \"50\" />\n <Button Content = \"Default Button!\" Height = \"40\" Width = \"150\" Margin = \"5\" /> \n </StackPanel> \n\t\n</Window>" }, { "code": null, "e": 5847, "s": 5758, "text": "When the above code is compiled and executed, it will produce the following MainWindow −" }, { "code": null, "e": 5958, "s": 5847, "text": "When you hover the mouse over the button with custom template, then it also changes the color as shown below −" }, { "code": null, "e": 6229, "s": 5958, "text": "A Data Template defines and specifies the appearance and structure of the collection of data. It provides the flexibility to format and define the presentation of the data on any UI element. It is mostly used on data related Item controls such as ComboBox, ListBox, etc." }, { "code": null, "e": 6364, "s": 6229, "text": "Let’s have a look at a simple example of data template. The following XAML code creates a combobox with Data Template and text blocks." }, { "code": null, "e": 7409, "s": 6364, "text": "<Window x:Class = \"XAMLDataTemplate.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid VerticalAlignment = \"Top\">\n <ComboBox Name = \"Presidents\" ItemsSource = \"{Binding}\" Height = \"30\" Width = \"400\"> \n <ComboBox.ItemTemplate> \n <DataTemplate>\n <StackPanel Orientation = \"Horizontal\" Margin = \"2\">\n <TextBlock Text = \"Name: \" Width = \"95\" Background = \"Aqua\" Margin = \"2\" /> \n <TextBlock Text = \"{Binding Name}\" Width = \"95\" Background = \"AliceBlue\" Margin = \"2\" /> \n <TextBlock Text = \"Title: \" Width = \"95\" Background = \"Aqua\" Margin = \"10,2,0,2\" />\n <TextBlock Text = \"{Binding Title}\" Width = \"95\" Background = \"AliceBlue\" Margin = \"2\" /> \n </StackPanel>\n </DataTemplate>\n </ComboBox.ItemTemplate> \n </ComboBox> \n </Grid>\n \n</Window>" }, { "code": null, "e": 7500, "s": 7409, "text": "Here is the implementation in C# in which the employee object is assigned to DataContext −" }, { "code": null, "e": 7859, "s": 7500, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls;\n\nnamespace XAMLDataTemplate { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window {\n public MainWindow() {\n InitializeComponent(); \n DataContext = Employee.GetEmployees(); \n }\n }\n}" }, { "code": null, "e": 7913, "s": 7859, "text": "Here is the implementation in C# for Employee class −" }, { "code": null, "e": 9613, "s": 7913, "text": "using System; \nusing System.Collections.Generic; \nusing System.Collections.ObjectModel; \nusing System.ComponentModel; \nusing System.Linq; \nusing System.Runtime.CompilerServices; \nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace XAMLDataTemplate { \n public class Employee : INotifyPropertyChanged {\n private string name; public string Name {\n get { return name; } \n set { name = value; RaiseProperChanged(); } \n }\n private string title; public string Title { \n get { return title; } \n set { title = value; RaiseProperChanged(); } \n }\n public static Employee GetEmployee() {\n var emp = new Employee() { \n Name = \"Waqas\", Title = \"Software Engineer\" };\n return emp; \n }\n public event PropertyChangedEventHandler PropertyChanged;\n private void RaiseProperChanged( [CallerMemberName] string caller = \"\"){\n if (PropertyChanged != null) { \n PropertyChanged(this, new PropertyChangedEventArgs(caller)); \n } \n }\n public static ObservableCollection<Employee> GetEmployees() {\n var employees = new ObservableCollection<Employee>();\n employees.Add(new Employee() { Name = \"Ali\", Title = \"Developer\" }); \n employees.Add(new Employee() { Name = \"Ahmed\", Title = \"Programmer\" });\n employees.Add(new Employee() { Name = \"Amjad\", Title = \"Desiner\" });\n employees.Add(new Employee() { Name = \"Waqas\", Title = \"Programmer\" }); \n employees.Add(new Employee() { Name = \"Bilal\", Title = \"Engineer\" });\n employees.Add(new Employee() { Name = \"Waqar\", Title = \"Manager\" }); \n return employees; \n }\n }\n}" }, { "code": null, "e": 9865, "s": 9613, "text": "When the above code is compiled and executed, it will produce the following output. It contains a combobox and when you click on the combobox, you see that the collection of data which are created in the Employee class is listed as the combobox items." }, { "code": null, "e": 9932, "s": 9865, "text": "We recommend you to execute the above code and experiment with it." }, { "code": null, "e": 9939, "s": 9932, "text": " Print" }, { "code": null, "e": 9950, "s": 9939, "text": " Add Notes" } ]
C# program to multiply all numbers in the list
Firstly, set the list − List<int> myList = new List<int> () { 5, 10, 7 }; Now, set the value of a variable to 1 that would help us in multiplying − int prod = 1; Loop through and get the product − foreach(int i in myList) { prod = prod*i; } The following is the code − Live Demo using System; using System.Collections.Generic; public class Program { public static void Main() { List<int> myList = new List<int>() { 5, 10, 7 }; Console.WriteLine("List: "); foreach(int i in myList) { Console.WriteLine(i); } int prod = 1; foreach(int i in myList) { prod = prod*i; } Console.WriteLine("Product: {0}",prod); } } List: 5 10 7 Product: 350
[ { "code": null, "e": 1086, "s": 1062, "text": "Firstly, set the list −" }, { "code": null, "e": 1145, "s": 1086, "text": "List<int> myList = new List<int> () {\n 5,\n 10,\n 7\n};" }, { "code": null, "e": 1219, "s": 1145, "text": "Now, set the value of a variable to 1 that would help us in multiplying −" }, { "code": null, "e": 1233, "s": 1219, "text": "int prod = 1;" }, { "code": null, "e": 1268, "s": 1233, "text": "Loop through and get the product −" }, { "code": null, "e": 1315, "s": 1268, "text": "foreach(int i in myList) {\n prod = prod*i;\n}" }, { "code": null, "e": 1343, "s": 1315, "text": "The following is the code −" }, { "code": null, "e": 1354, "s": 1343, "text": " Live Demo" }, { "code": null, "e": 1790, "s": 1354, "text": "using System;\nusing System.Collections.Generic;\n\npublic class Program {\n public static void Main() {\n List<int> myList = new List<int>() {\n 5,\n 10,\n 7\n };\n Console.WriteLine(\"List: \");\n foreach(int i in myList) {\n Console.WriteLine(i);\n }\n int prod = 1;\n foreach(int i in myList) {\n prod = prod*i;\n }\n Console.WriteLine(\"Product: {0}\",prod);\n }\n}" }, { "code": null, "e": 1816, "s": 1790, "text": "List:\n5\n10\n7\nProduct: 350" } ]
SVN - Fix Mistakes
Suppose Jerry accidently modifies array.c file and he is getting compilation errors. Now he wants to throw away the changes. In this situation, 'revert' operation will help. Revert operation will undo any local changes to a file or directory and resolve any conflicted states. [jerry@CentOS trunk]$ svn status Above command will produce the following result. M array.c Let's try to make array as follows: [jerry@CentOS trunk]$ make array Above command will produce the following result. cc array.c -o array array.c: In function ‘main’: array.c:26: error: ‘n’ undeclared (first use in this function) array.c:26: error: (Each undeclared identifier is reported only once array.c:26: error: for each function it appears in.) array.c:34: error: ‘arr’ undeclared (first use in this function) make: *** [array] Error 1 Jerry performs 'revert' operation on array.c file. [jerry@CentOS trunk]$ svn revert array.c Reverted 'array.c' [jerry@CentOS trunk]$ svn status [jerry@CentOS trunk]$ Now compile the code. [jerry@CentOS trunk]$ make array cc array.c -o array After the revert operation, his working copy is back to its original state. Revert operation can revert a single file as well as a complete directory. To revert a directory, use -R option as shown below. [jerry@CentOS project_repo]$ pwd /home/jerry/project_repo [jerry@CentOS project_repo]$ svn revert -R trunk Till now, we have seen how to revert changes, which has been made to the working copy. But what if you want to revert a committed revision! Version Control System tool doesn't allow to delete history from the repository. We can only append history. It will happen even if you delete files from the repository. To undo an old revision, we have to reverse whatever changes were made in the old revision and then commit a new revision. This is called a reverse merge. Let us suppose Jerry adds a code for linear search operation. After verification he commits his changes. [jerry@CentOS trunk]$ svn diff Index: array.c =================================================================== --- array.c (revision 21) +++ array.c (working copy) @@ -2,6 +2,16 @@ #define MAX 16 +int linear_search(int *arr, int n, int key) +{ + int i; + + for (i = 0; i < n; ++i) + if (arr[i] == key) + return i; + return -1; +} + void bubble_sort(int *arr, int n) { int i, j, temp, flag = 1; [jerry@CentOS trunk]$ svn status ? array M array.c [jerry@CentOS trunk]$ svn commit -m "Added code for linear search" Sending trunk/array.c Transmitting file data . Committed revision 22. Jerry is curious about what Tom is doing. So he checks the Subversion log messages. [jerry@CentOS trunk]$ svn log The above command will produce the following result. ------------------------------------------------------------------------ r5 | tom | 2013-08-24 17:15:28 +0530 (Sat, 24 Aug 2013) | 1 line Add binary search operation ------------------------------------------------------------------------ r4 | jerry | 2013-08-18 20:43:25 +0530 (Sun, 18 Aug 2013) | 1 line Add function to accept input and to display array contents After viewing the log messages, Jerry realizes that he did a serious mistake. Because Tom already implemented binary search operation, which is better than the linear search; his code is redundant, and now Jerry has to revert his changes to the previous revision. So, first find the current revision of the repository. Currently, the repository is at revision 22 and we have to revert it to the previous revision, i.e. revision 21. [jerry@CentOS trunk]$ svn up At revision 22. [jerry@CentOS trunk]$ svn merge -r 22:21 array.c --- Reverse-merging r22 into 'array.c': U array.c [jerry@CentOS trunk]$ svn commit -m "Reverted to revision 21" Sending trunk/array.c Transmitting file data . Committed revision 23. Print Add Notes Bookmark this page
[ { "code": null, "e": 2053, "s": 1776, "text": "Suppose Jerry accidently modifies array.c file and he is getting compilation errors. Now he wants to throw away the changes. In this situation, 'revert' operation will help. Revert operation will undo any local changes to a file or directory and resolve any conflicted states." }, { "code": null, "e": 2087, "s": 2053, "text": "[jerry@CentOS trunk]$ svn status\n" }, { "code": null, "e": 2136, "s": 2087, "text": "Above command will produce the following result." }, { "code": null, "e": 2153, "s": 2136, "text": "M array.c\n" }, { "code": null, "e": 2189, "s": 2153, "text": "Let's try to make array as follows:" }, { "code": null, "e": 2223, "s": 2189, "text": "[jerry@CentOS trunk]$ make array\n" }, { "code": null, "e": 2272, "s": 2223, "text": "Above command will produce the following result." }, { "code": null, "e": 2604, "s": 2272, "text": "cc array.c -o array\narray.c: In function ‘main’:\narray.c:26: error: ‘n’ undeclared (first use in this function)\narray.c:26: error: (Each undeclared identifier is reported only once\narray.c:26: error: for each function it appears in.)\narray.c:34: error: ‘arr’ undeclared (first use in this function)\nmake: *** [array] Error 1\n" }, { "code": null, "e": 2655, "s": 2604, "text": "Jerry performs 'revert' operation on array.c file." }, { "code": null, "e": 2773, "s": 2655, "text": "[jerry@CentOS trunk]$ svn revert array.c \nReverted 'array.c'\n\n[jerry@CentOS trunk]$ svn status\n[jerry@CentOS trunk]$\n" }, { "code": null, "e": 2795, "s": 2773, "text": "Now compile the code." }, { "code": null, "e": 2855, "s": 2795, "text": "[jerry@CentOS trunk]$ make array\ncc array.c -o array\n" }, { "code": null, "e": 3059, "s": 2855, "text": "After the revert operation, his working copy is back to its original state. Revert operation can revert a single file as well as a complete directory. To revert a directory, use -R option as shown below." }, { "code": null, "e": 3168, "s": 3059, "text": "[jerry@CentOS project_repo]$ pwd\n/home/jerry/project_repo\n\n[jerry@CentOS project_repo]$ svn revert -R trunk\n" }, { "code": null, "e": 3633, "s": 3168, "text": "Till now, we have seen how to revert changes, which has been made to the working copy. But what if you want to revert a committed revision! Version Control System tool doesn't allow to delete history from the repository. We can only append history. It will happen even if you delete files from the repository. To undo an old revision, we have to reverse whatever changes were made in the old revision and then commit a new revision. This is called a reverse merge." }, { "code": null, "e": 3738, "s": 3633, "text": "Let us suppose Jerry adds a code for linear search operation. After verification he commits his changes." }, { "code": null, "e": 4379, "s": 3738, "text": "[jerry@CentOS trunk]$ svn diff\nIndex: array.c\n===================================================================\n--- array.c (revision 21)\n+++ array.c (working copy)\n@@ -2,6 +2,16 @@\n \n #define MAX 16\n \n+int linear_search(int *arr, int n, int key)\n+{\n+ int i;\n+\n+ for (i = 0; i < n; ++i)\n+ if (arr[i] == key)\n+ return i;\n+ return -1;\n+}\n+\n void bubble_sort(int *arr, int n)\n {\n int i, j, temp, flag = 1;\n\n[jerry@CentOS trunk]$ svn status\n? array\nM array.c\n\n[jerry@CentOS trunk]$ svn commit -m \"Added code for linear search\"\nSending trunk/array.c\nTransmitting file data .\nCommitted revision 22.\n" }, { "code": null, "e": 4463, "s": 4379, "text": "Jerry is curious about what Tom is doing. So he checks the Subversion log messages." }, { "code": null, "e": 4494, "s": 4463, "text": "[jerry@CentOS trunk]$ svn log\n" }, { "code": null, "e": 4547, "s": 4494, "text": "The above command will produce the following result." }, { "code": null, "e": 4917, "s": 4547, "text": "------------------------------------------------------------------------\nr5 | tom | 2013-08-24 17:15:28 +0530 (Sat, 24 Aug 2013) | 1 line\n\nAdd binary search operation\n------------------------------------------------------------------------\nr4 | jerry | 2013-08-18 20:43:25 +0530 (Sun, 18 Aug 2013) | 1 line\n\nAdd function to accept input and to display array contents\n" }, { "code": null, "e": 5349, "s": 4917, "text": "After viewing the log messages, Jerry realizes that he did a serious mistake. Because Tom already implemented binary search operation, which is better than the linear search; his code is redundant, and now Jerry has to revert his changes to the previous revision. So, first find the current revision of the repository. Currently, the repository is at revision 22 and we have to revert it to the previous revision, i.e. revision 21." }, { "code": null, "e": 5640, "s": 5349, "text": "[jerry@CentOS trunk]$ svn up \nAt revision 22.\n\n[jerry@CentOS trunk]$ svn merge -r 22:21 array.c \n--- Reverse-merging r22 into 'array.c':\nU array.c\n\n[jerry@CentOS trunk]$ svn commit -m \"Reverted to revision 21\"\nSending trunk/array.c\nTransmitting file data .\nCommitted revision 23.\n" }, { "code": null, "e": 5647, "s": 5640, "text": " Print" }, { "code": null, "e": 5658, "s": 5647, "text": " Add Notes" } ]
How to add a constant column in a PySpark DataFrame? - GeeksforGeeks
23 Aug, 2021 In this article, we are going to see how to add a constant column in a PySpark Dataframe. It can be done in these ways: Using Lit() Using Sql query. Creating Dataframe for demonstration: Python3 # Create a spark sessionfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import litspark = SparkSession.builder.appName('SparkExamples').getOrCreate() # Create a spark dataframecolumns = ["Name", "Course_Name", "Months", "Course_Fees", "Discount", "Start_Date", "Payment_Done"]data = [ ("Amit Pathak", "Python", 3, 10000, 1000, "02-07-2021", True), ("Shikhar Mishra", "Soft skills", 2, 8000, 800, "07-10-2021", False), ("Shivani Suvarna", "Accounting", 6, 15000, 1500, "20-08-2021", True), ("Pooja Jain", "Data Science", 12, 60000, 900, "02-12-2021", False),]df = spark.createDataFrame(data).toDF(*columns) # View the dataframedf.show() Output: In these methods, we will use the lit() function, Here we can add the constant column ‘literal_values_1’ with value 1 by Using the select method. The lit() function will insert constant values to all the rows. We will use withColumn() select the dataframe: Syntax: df.withColumn(“NEW_COL”, lit(VALUE)) Example 1: Adding constant value in columns. Python3 df.withColumn('Status', lit(0)).show() Output: Example 2: Adding constant value based on another column. Python3 from pyspark.sql.functions import when, lit, col df.withColumn( "Great_Discount", when(col("Discount") >=1000,lit( "Yes")).otherwise(lit("NO"))).show() Output: Here we will use sql query inside the Pyspark, We will create a temp view of the table with the help of createTempView() and the life of this temp is up to the life of the sparkSession. registerTempTable() will create the temp table if it is not available or if it is available then replace it. Then after creating the table select the table by SQL clause which will take all the values as a string. Python3 df.registerTempTable('table')newDF = spark.sql('select *, 1 as newCol from table')newDF.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 Convert Python Dictionary To JSON? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n23 Aug, 2021" }, { "code": null, "e": 24383, "s": 24292, "text": "In this article, we are going to see how to add a constant column in a PySpark Dataframe. " }, { "code": null, "e": 24413, "s": 24383, "text": "It can be done in these ways:" }, { "code": null, "e": 24425, "s": 24413, "text": "Using Lit()" }, { "code": null, "e": 24442, "s": 24425, "text": "Using Sql query." }, { "code": null, "e": 24480, "s": 24442, "text": "Creating Dataframe for demonstration:" }, { "code": null, "e": 24488, "s": 24480, "text": "Python3" }, { "code": "# Create a spark sessionfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import litspark = SparkSession.builder.appName('SparkExamples').getOrCreate() # Create a spark dataframecolumns = [\"Name\", \"Course_Name\", \"Months\", \"Course_Fees\", \"Discount\", \"Start_Date\", \"Payment_Done\"]data = [ (\"Amit Pathak\", \"Python\", 3, 10000, 1000, \"02-07-2021\", True), (\"Shikhar Mishra\", \"Soft skills\", 2, 8000, 800, \"07-10-2021\", False), (\"Shivani Suvarna\", \"Accounting\", 6, 15000, 1500, \"20-08-2021\", True), (\"Pooja Jain\", \"Data Science\", 12, 60000, 900, \"02-12-2021\", False),]df = spark.createDataFrame(data).toDF(*columns) # View the dataframedf.show()", "e": 25199, "s": 24488, "text": null }, { "code": null, "e": 25207, "s": 25199, "text": "Output:" }, { "code": null, "e": 25464, "s": 25207, "text": "In these methods, we will use the lit() function, Here we can add the constant column ‘literal_values_1’ with value 1 by Using the select method. The lit() function will insert constant values to all the rows. We will use withColumn() select the dataframe:" }, { "code": null, "e": 25509, "s": 25464, "text": "Syntax: df.withColumn(“NEW_COL”, lit(VALUE))" }, { "code": null, "e": 25554, "s": 25509, "text": "Example 1: Adding constant value in columns." }, { "code": null, "e": 25562, "s": 25554, "text": "Python3" }, { "code": "df.withColumn('Status', lit(0)).show()", "e": 25601, "s": 25562, "text": null }, { "code": null, "e": 25609, "s": 25601, "text": "Output:" }, { "code": null, "e": 25667, "s": 25609, "text": "Example 2: Adding constant value based on another column." }, { "code": null, "e": 25675, "s": 25667, "text": "Python3" }, { "code": "from pyspark.sql.functions import when, lit, col df.withColumn( \"Great_Discount\", when(col(\"Discount\") >=1000,lit( \"Yes\")).otherwise(lit(\"NO\"))).show()", "e": 25832, "s": 25675, "text": null }, { "code": null, "e": 25840, "s": 25832, "text": "Output:" }, { "code": null, "e": 26135, "s": 25840, "text": "Here we will use sql query inside the Pyspark, We will create a temp view of the table with the help of createTempView() and the life of this temp is up to the life of the sparkSession. registerTempTable() will create the temp table if it is not available or if it is available then replace it." }, { "code": null, "e": 26240, "s": 26135, "text": "Then after creating the table select the table by SQL clause which will take all the values as a string." }, { "code": null, "e": 26248, "s": 26240, "text": "Python3" }, { "code": "df.registerTempTable('table')newDF = spark.sql('select *, 1 as newCol from table')newDF.show()", "e": 26343, "s": 26248, "text": null }, { "code": null, "e": 26351, "s": 26343, "text": "Output:" }, { "code": null, "e": 26358, "s": 26351, "text": "Picked" }, { "code": null, "e": 26373, "s": 26358, "text": "Python-Pyspark" }, { "code": null, "e": 26380, "s": 26373, "text": "Python" }, { "code": null, "e": 26478, "s": 26380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26487, "s": 26478, "text": "Comments" }, { "code": null, "e": 26500, "s": 26487, "text": "Old Comments" }, { "code": null, "e": 26532, "s": 26500, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26574, "s": 26532, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26629, "s": 26574, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26685, "s": 26629, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26727, "s": 26685, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26749, "s": 26727, "text": "Defaultdict in Python" }, { "code": null, "e": 26788, "s": 26749, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26819, "s": 26788, "text": "Python | os.path.join() method" }, { "code": null, "e": 26848, "s": 26819, "text": "Create a directory in Python" } ]
C# | UInt64 Struct - GeeksforGeeks
01 May, 2019 In C#, UInt64 struct is used to represent 64-bit unsigned integers(also termed as the ulong data type) starting from range 0 to 18,446,744,073,709,551,615. It also provides different types of methods to compare instances of this type, convert the value of an instance to its String representation, convert the String representation of a number to an instance of this type, etc. This struct is defined under System namespace. UInt64 struct inherits the ValueType class which inherits the Object class. Example: // C# program to illustrate the // fields of UInt64 structusing System; class GFG { // Main Method static public void Main() { // Unsigned 64-bit integer ulong val = 18446744073709551615; // Checking the unsigned integer if (val.Equals(UInt64.MinValue)) { Console.WriteLine("Equal to MinValue!"); } else if (val.Equals(UInt64.MaxValue)) { Console.WriteLine("Equal to MaxValue!"); } else { Console.WriteLine("Not Equal!"); } }} Equal to MaxValue! Example: // C# program to illustrate how to get the // hash code of the 64-bit Unsigned integerusing System; class GFG { // Main Method static public void Main() { // UInt64 variable ulong myval = 3654121225155; // Get the hash code // Using GetHashCode Method int res = myval.GetHashCode(); Console.WriteLine("The hash code of myval is: {0}", res); }} The hash code of myval is: -895944559 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.uint64?view=netframework-4.8 CSharp-UInt64-Struct C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Partial Classes in C# C# | Inheritance C# | List Class Difference between Hashtable and Dictionary in C# Lambda Expressions in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n01 May, 2019" }, { "code": null, "e": 24803, "s": 24302, "text": "In C#, UInt64 struct is used to represent 64-bit unsigned integers(also termed as the ulong data type) starting from range 0 to 18,446,744,073,709,551,615. It also provides different types of methods to compare instances of this type, convert the value of an instance to its String representation, convert the String representation of a number to an instance of this type, etc. This struct is defined under System namespace. UInt64 struct inherits the ValueType class which inherits the Object class." }, { "code": null, "e": 24812, "s": 24803, "text": "Example:" }, { "code": "// C# program to illustrate the // fields of UInt64 structusing System; class GFG { // Main Method static public void Main() { // Unsigned 64-bit integer ulong val = 18446744073709551615; // Checking the unsigned integer if (val.Equals(UInt64.MinValue)) { Console.WriteLine(\"Equal to MinValue!\"); } else if (val.Equals(UInt64.MaxValue)) { Console.WriteLine(\"Equal to MaxValue!\"); } else { Console.WriteLine(\"Not Equal!\"); } }}", "e": 25382, "s": 24812, "text": null }, { "code": null, "e": 25402, "s": 25382, "text": "Equal to MaxValue!\n" }, { "code": null, "e": 25411, "s": 25402, "text": "Example:" }, { "code": "// C# program to illustrate how to get the // hash code of the 64-bit Unsigned integerusing System; class GFG { // Main Method static public void Main() { // UInt64 variable ulong myval = 3654121225155; // Get the hash code // Using GetHashCode Method int res = myval.GetHashCode(); Console.WriteLine(\"The hash code of myval is: {0}\", res); }}", "e": 25818, "s": 25411, "text": null }, { "code": null, "e": 25857, "s": 25818, "text": "The hash code of myval is: -895944559\n" }, { "code": null, "e": 25868, "s": 25857, "text": "Reference:" }, { "code": null, "e": 25948, "s": 25868, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.uint64?view=netframework-4.8" }, { "code": null, "e": 25969, "s": 25948, "text": "CSharp-UInt64-Struct" }, { "code": null, "e": 25972, "s": 25969, "text": "C#" }, { "code": null, "e": 26070, "s": 25972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26088, "s": 26070, "text": "Destructors in C#" }, { "code": null, "e": 26111, "s": 26088, "text": "Extension Method in C#" }, { "code": null, "e": 26139, "s": 26111, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26179, "s": 26139, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26222, "s": 26179, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 26244, "s": 26222, "text": "Partial Classes in C#" }, { "code": null, "e": 26261, "s": 26244, "text": "C# | Inheritance" }, { "code": null, "e": 26277, "s": 26261, "text": "C# | List Class" }, { "code": null, "e": 26327, "s": 26277, "text": "Difference between Hashtable and Dictionary in C#" } ]
Python - Count of Words with specific letter - GeeksforGeeks
14 Oct, 2020 Given a string of words, extract count of words with specific letter. Input : test_str = ‘geeksforgeeks is best for geeks’, letter = “g”Output : 2Explanation : “g” occurs in 2 words. Input : test_str = ‘geeksforgeeks is best for geeks’, letter = “s”Output : sExplanation : “s” occurs in 4 words. Method #1 : Using list comprehension + len() + split() This is one of the ways in which this task can be performed. In this, we perform task of extracting words from string using split() and loop is used to iterate words to check for letter existence of letter and len() is used to fetch the number of words with letter. Python3 # Python3 code to demonstrate working of # Count of Words with specific letter# Using list comprehension + len() + split() # initializing stringtest_str = 'geeksforgeeks is best for geeks' # printing original stringprint("The original string is : " + str(test_str)) # initializing letter letter = "e" # extracting desired count using len()# list comprehension is used as shorthandres = len([ele for ele in test_str.split() if letter in ele]) # printing result print("Words count : " + str(res)) The original string is : geeksforgeeks is best for geeks Words count : 3 Method #2 : Using filter() + lambda + len() + split() This is yet another way in which this task can be performed. In this, we perform the task of filtering using filter() + lambda. Python3 # Python3 code to demonstrate working of # Count of Words with specific letter# Using filter() + lambda + len() + split() # initializing stringtest_str = 'geeksforgeeks is best for geeks' # printing original stringprint("The original string is : " + str(test_str)) # initializing letter letter = "e" # extracting desired count using len()# filter() used to check for letter existenceres = len(list(filter(lambda ele : letter in ele, test_str.split()))) # printing result print("Words count : " + str(res)) The original string is : geeksforgeeks is best for geeks Words count : 3 Python string-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 Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method 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": "\n14 Oct, 2020" }, { "code": null, "e": 24362, "s": 24292, "text": "Given a string of words, extract count of words with specific letter." }, { "code": null, "e": 24475, "s": 24362, "text": "Input : test_str = ‘geeksforgeeks is best for geeks’, letter = “g”Output : 2Explanation : “g” occurs in 2 words." }, { "code": null, "e": 24588, "s": 24475, "text": "Input : test_str = ‘geeksforgeeks is best for geeks’, letter = “s”Output : sExplanation : “s” occurs in 4 words." }, { "code": null, "e": 24643, "s": 24588, "text": "Method #1 : Using list comprehension + len() + split()" }, { "code": null, "e": 24909, "s": 24643, "text": "This is one of the ways in which this task can be performed. In this, we perform task of extracting words from string using split() and loop is used to iterate words to check for letter existence of letter and len() is used to fetch the number of words with letter." }, { "code": null, "e": 24917, "s": 24909, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Count of Words with specific letter# Using list comprehension + len() + split() # initializing stringtest_str = 'geeksforgeeks is best for geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing letter letter = \"e\" # extracting desired count using len()# list comprehension is used as shorthandres = len([ele for ele in test_str.split() if letter in ele]) # printing result print(\"Words count : \" + str(res)) ", "e": 25418, "s": 24917, "text": null }, { "code": null, "e": 25492, "s": 25418, "text": "The original string is : geeksforgeeks is best for geeks\nWords count : 3\n" }, { "code": null, "e": 25546, "s": 25492, "text": "Method #2 : Using filter() + lambda + len() + split()" }, { "code": null, "e": 25674, "s": 25546, "text": "This is yet another way in which this task can be performed. In this, we perform the task of filtering using filter() + lambda." }, { "code": null, "e": 25682, "s": 25674, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Count of Words with specific letter# Using filter() + lambda + len() + split() # initializing stringtest_str = 'geeksforgeeks is best for geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing letter letter = \"e\" # extracting desired count using len()# filter() used to check for letter existenceres = len(list(filter(lambda ele : letter in ele, test_str.split()))) # printing result print(\"Words count : \" + str(res)) ", "e": 26194, "s": 25682, "text": null }, { "code": null, "e": 26268, "s": 26194, "text": "The original string is : geeksforgeeks is best for geeks\nWords count : 3\n" }, { "code": null, "e": 26291, "s": 26268, "text": "Python string-programs" }, { "code": null, "e": 26298, "s": 26291, "text": "Python" }, { "code": null, "e": 26314, "s": 26298, "text": "Python Programs" }, { "code": null, "e": 26412, "s": 26314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26444, "s": 26412, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26486, "s": 26444, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26542, "s": 26486, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26584, "s": 26542, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26615, "s": 26584, "text": "Python | os.path.join() method" }, { "code": null, "e": 26637, "s": 26615, "text": "Defaultdict in Python" }, { "code": null, "e": 26683, "s": 26637, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26722, "s": 26683, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26760, "s": 26722, "text": "Python | Convert a list to dictionary" } ]
How to create bar plot with positive and negative values in R?
To create bar plot with positive and negative values, we can make use of ggplot function. For example, if we have a data frame called df that contains a categorical column say C and a numerical column Num which has some positive and some negative values then the bar plot for this data can be created by using the below command − ggplot(df,aes(C,Num))+geom_bar(stat="identity") Following snippet creates a sample data frame − Category<-c("Egypt","Sudan","Turkey","Indonesia") Response_Score<-c(10,-2,4,-5) df<-data.frame(Category,Response_Score) df The following dataframe is created − Category Response_Score 1 Egypt 10 2 Sudan -2 3 Turkey 4 4 Indonesia -5 To load ggplot2 package and create bar chart for data stored in df, add the following code to the above snippet − library(ggplot2) ggplot(df,aes(Category,Response_Score))+geom_bar(stat="identity") If you execute all the above given snippets as a single program, it generates the following output −
[ { "code": null, "e": 1152, "s": 1062, "text": "To create bar plot with positive and negative values, we can make use of ggplot function." }, { "code": null, "e": 1392, "s": 1152, "text": "For example, if we have a data frame called df that contains a categorical column say C and a numerical column Num which has some positive and some negative values then the bar plot for this data can be created by using the below command −" }, { "code": null, "e": 1440, "s": 1392, "text": "ggplot(df,aes(C,Num))+geom_bar(stat=\"identity\")" }, { "code": null, "e": 1488, "s": 1440, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 1611, "s": 1488, "text": "Category<-c(\"Egypt\",\"Sudan\",\"Turkey\",\"Indonesia\")\nResponse_Score<-c(10,-2,4,-5)\ndf<-data.frame(Category,Response_Score)\ndf" }, { "code": null, "e": 1648, "s": 1611, "text": "The following dataframe is created −" }, { "code": null, "e": 1743, "s": 1648, "text": " Category Response_Score\n1 Egypt 10\n2 Sudan -2\n3 Turkey 4\n4 Indonesia -5" }, { "code": null, "e": 1857, "s": 1743, "text": "To load ggplot2 package and create bar chart for data stored in df, add the following code to the above snippet −" }, { "code": null, "e": 1940, "s": 1857, "text": "library(ggplot2)\nggplot(df,aes(Category,Response_Score))+geom_bar(stat=\"identity\")" }, { "code": null, "e": 2041, "s": 1940, "text": "If you execute all the above given snippets as a single program, it generates the following output −" } ]
What is the difference between Select and SelectMany in Linq C#?
Select operator produces one result value for every source SelectMany Operator belong to Projection Operators category. It is used to project each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence. class Demo{ public string Name { get; set; } public List<string> Contents { get; set; } public static List<Demo>GetAllContents(){ List<Demo> listContents = new List<Demo>{ new Demo{ Name = "Cap", Contents = new List<string> { "Nike", "Adidas" } }, new Demo{ Name = "Shoes", Contents = new List<string> { "Nike", "Puma", "Adidas" } }, }; return listContents; } } class Program{ static void Main(){ IEnumerable<List<string>> result = Demo.GetAllContents().Select(s => s.Contents); foreach (List<string> stringList in result){ foreach (string str in stringList){ Console.WriteLine(str); } } Console.WriteLine("---Select Many---") IEnumerable<string> resultSelectMany = Demo.GetAllContents().SelectMany(s => s.Contents); foreach (string str in resultSelectMany){ Console.WriteLine(str); } Console.ReadKey(); } } Nike Adidas Nike Puma Adidas ---Select Many--- Nike Adidas Nike Puma Adidas
[ { "code": null, "e": 1305, "s": 1062, "text": "Select operator produces one result value for every source SelectMany Operator belong to Projection Operators category. It is used to project each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence." }, { "code": null, "e": 2320, "s": 1305, "text": "class Demo{\n public string Name { get; set; }\n public List<string> Contents { get; set; }\n public static List<Demo>GetAllContents(){\n List<Demo> listContents = new List<Demo>{\n new Demo{\n Name = \"Cap\",\n Contents = new List<string> { \"Nike\", \"Adidas\" }\n },\n new Demo{\n Name = \"Shoes\",\n Contents = new List<string> { \"Nike\", \"Puma\", \"Adidas\" }\n },\n };\n return listContents;\n }\n}\nclass Program{\n static void Main(){\n IEnumerable<List<string>> result = Demo.GetAllContents().Select(s => s.Contents);\n foreach (List<string> stringList in result){\n foreach (string str in stringList){\n Console.WriteLine(str);\n }\n }\n Console.WriteLine(\"---Select Many---\")\n IEnumerable<string> resultSelectMany = Demo.GetAllContents().SelectMany(s => s.Contents);\n foreach (string str in resultSelectMany){\n Console.WriteLine(str);\n }\n Console.ReadKey();\n }\n}" }, { "code": null, "e": 2396, "s": 2320, "text": "Nike\nAdidas\nNike\nPuma\nAdidas\n---Select Many---\nNike\nAdidas\nNike\nPuma\nAdidas" } ]